Compare commits
1 Commits
master
...
wip/invert
| Author | SHA1 | Date |
|---|---|---|
|
|
dbfc6eb56b |
30
README.md
30
README.md
|
|
@ -7,41 +7,34 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
|
||||||
## What it does
|
## What it does
|
||||||
|
|
||||||
- Parts: NAND, input switch, output pin, lamp, push button, clock, constant 1, ground, hex display, pixel, cable bundle and split, input panel, note.
|
- Parts: NAND, input switch, output pin, lamp, push button, clock, constant 1, ground, hex display, pixel, cable bundle and split, input panel, note.
|
||||||
- Layout like Figma: two floating rounded bars over the canvas, a panel on the left for the circuit you are in and one on the right for what is selected. The top bar, across the whole width: menu (pause menu) with the project name, "Main" and the way into the open component (each name leads back; every other circuit is a component and opens with a double-click, or the pencil in the Components list); every step into or out of a circuit, and to another project, is an entry in the browser's history, so the mouse's back and forward buttons (and Alt + ← →, the browser's buttons) go through them as visited, crumbs included, also after a reload. In Chrome the mouse's back button never leaves the editor: on the first entry it goes up a crumb. A share or puzzle address opens its link only when the page is loaded with it, not when going back or forward lands on it, Challenges (campaign, puzzle of the week, puzzles, challenges in a drop-down), the clock, search, undo, sound, settings, help, share and account. The bottom bar: your pinned parts first (NAND, AND, OR, NOT, XOR, input, output, lamp, clock to start with; pin from the lists, right-click to unpin, kept per browser, components by name), then one button per kind of part (Logic, Inputs, Outputs, Wiring, Notes, Connectors, Components) that opens its parts on pointing, and a search that opens quick add.
|
|
||||||
- Small windows: the bars keep their steady centred width on wide screens and are never narrower than 760px as far as the panels leave room; they move off the centre rather than under a panel. On a narrow bar the words go first, then the names between Main and the open component fold into "…" (a menu leading back to each), and sound, settings and help (then undo, redo and share, then challenges and search) move into a "⋯" menu; Main is always there. From 821 to 1100px the selection's panel floats over the canvas edge between the bars instead of narrowing the canvas; below that the panels sit under the canvas. Drop-downs, flyouts and the search box stay on screen.
|
|
||||||
- Quick add (Space, /, Shift+A, Ctrl+K): parts and actions at the mouse. Shift+Enter (or Ctrl+Enter, or the pencil on its line) opens the chosen component to edit it instead of placing it, and typing a name lists "Open <name>" for every circuit of the project, also those that cannot be placed here; the one you are in shows as where you are. Going to one on the way here goes back along the way ([app/lib/nav.ts](app/lib/nav.ts)).
|
|
||||||
- Lamps and output pins pass their signal on: the pin on their right carries the same value, so a lamp can sit in the middle of a wire.
|
- Lamps and output pins pass their signal on: the pin on their right carries the same value, so a lamp can sit in the middle of a wire.
|
||||||
- Gates with more inputs: a placed AND, OR, XOR, NAND or NOR (built in, from the examples, or your own) has an "Inputs" setting from 2 to 16. The wide version is a component built as a balanced tree of the two-input gate (NAND and NOR as the plain gate plus a final inverted one), made once per gate and width in "Wide gates" and reused; transistors count honestly and changes to the two-input gate carry through. Which gates qualify is read off their truth table ([app/lib/logic/wide.ts](app/lib/logic/wide.ts)).
|
- Gates with more inputs: a placed AND, OR, XOR, NAND or NOR (built in, from the examples, or your own) has an "Inputs" setting from 2 to 16. The wide version is a component built as a balanced tree of the two-input gate (NAND and NOR as the plain gate plus a final inverted one), made once per gate and width in "Wide gates" and reused; transistors count honestly and changes to the two-input gate carry through. Which gates qualify is read off their truth table ([app/lib/logic/wide.ts](app/lib/logic/wide.ts)).
|
||||||
- Campaign (Projects → New campaign): you start with NAND, inputs, outputs, lamps and notes, and no examples. Each challenge opens once the ones it builds on are solved (NOT → AND, OR, SR Latch → …), and your own solution becomes a part you can place. Other basic parts unlock on the way: constants with NOT, the input panel with AND, hex display and pixel with the decoder, cables with Adder 2, the button with the SR latch, the clock with the D latch. Rules in [app/lib/logic/progress.ts](app/lib/logic/progress.ts). Sandbox projects keep everything open.
|
- Campaign (Projects → New campaign): you start with NAND, inputs, outputs, lamps and notes, and no examples. Each challenge opens once the ones it builds on are solved (NOT → AND, OR, SR Latch → …), and your own solution becomes a part you can place. Other basic parts unlock on the way: constants with NOT, the input panel with AND, hex display and pixel with the decoder, cables with Adder 2, the button with the SR latch, the clock with the D latch. Rules in [app/lib/logic/progress.ts](app/lib/logic/progress.ts). Sandbox projects keep everything open.
|
||||||
- Puzzles: "Publish as puzzle" (This circuit) turns a circuit into a link `/puzzle/<id>`. Only its behaviour is published, as a truth table, or for circuits with memory as a run of input changes from power-on; the circuit stays private. Whoever opens the link gets the puzzle in their project, sees the target and the author's transistor count, and after a pass their solution goes to the server, which re-runs the checks and counts the transistors itself (with a fixed work budget) and keeps each player's best. The board shows everyone's transistor counts and your place. The puzzle of the week is generated from the ISO week, the same for everyone: three or four inputs, one or two outputs, each depending on every input. Players are anonymous ids per browser.
|
- Puzzles: "Publish as puzzle" (This circuit) turns a circuit into a link `/puzzle/<id>`. Only its behaviour is published, as a truth table, or for circuits with memory as a run of input changes from power-on; the circuit stays private. Whoever opens the link gets the puzzle in their project, sees the target and the author's transistor count, and after a pass their solution goes to the server, which re-runs the checks and counts the transistors itself (with a fixed work budget) and keeps each player's best. The board shows everyone's transistor counts and your place. The puzzle of the week is generated from the ISO week, the same for everyone: three or four inputs, one or two outputs, each depending on every input. Players are anonymous ids per browser.
|
||||||
- Library: everyone's published components in one public list (bottom bar → Components → Library, Space, or the main menu), searchable by name, description and author, each with its transistors, pins and what it uses. "Publish to the library…" in the menu on a circuit's name sends it with every component it uses and their connector types, under your leaderboard name; the server checks it like any project and counts transistors and pins itself. Publishing the same component again from the same browser and project makes the next version of the same entry; only that browser has the entry's edit key, so only it can update or remove it. "Add" brings an entry into the open project and starts placing it: what the project has in exactly that form already is used as it is, the rest comes with new ids (a name that is taken gets a number) and connector types join one with the same lines. The This panel says where a component came from and offers a newer version, which replaces it in place; what came along with the old version goes once nothing else uses it. Another entry's component is never reused, so updating one entry leaves the others as they were. Challenges and puzzles, and components with a solution anywhere inside, are never published. A campaign takes nothing from the library: it is built from your own work. Logic in [app/lib/logic/library.ts](app/lib/logic/library.ts).
|
|
||||||
- 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)).
|
- 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.
|
- 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. The cable button beside a selected component's outputs or inputs puts just a plug on those pins (pick the group when there are several); drag the cable out of the plug's cable pin, or press its "Pull the cable out" button and click: its other end goes where you let go, and let go on a part's pins its wires land on them from that pin down. Round buttons beside the selection do the everyday things in place: split a port into wires and join them again, pull a cable out of a plug, plug a cable end in or out, split a selected cable into single wires, bundle selected wires.
|
- 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 bottom bar's Connectors, "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 at the very top of its side, in ports on the left, out ports on the right, drawn as a socket in the type's colour. "Split … into lines" (selection panel or right click on the component) gives that box a pin per line right below the socket, named after the line, to wire lines by hand without an adapter: lines going into the component are inputs, lines coming out outputs, and a cable still plugs into the socket. Dropping a single wire on a socket does the same and takes the first free line (with a cable in the socket, only a line coming out: the cable feeds the others). "Join … lines" takes the line pins and their wires away again. On the box a line in the type's colour runs above and below a split port's wires, so it is clear which pins belong to it; a round button beside each socket splits or joins it. 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".
|
- 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.
|
- 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.
|
- 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.
|
||||||
- Every circuit is a component. Its input and output nodes become its pins, ordered top to bottom. Double-click a component to open it.
|
- Every circuit is a component. Its input and output nodes become its pins, ordered top to bottom. Double-click a component to open it.
|
||||||
- Lamps and hex displays inside a component show on its box, with their labels, lit by that instance's state. They are laid out in rows the way they sit inside. A checkbox in the inspector turns this off per component.
|
- Lamps and hex displays inside a component show on its box, with their labels, lit by that instance's state. They are laid out in rows the way they sit inside. A checkbox in the inspector turns this off per component.
|
||||||
- The panel on the left is about the circuit you are in and has two tabs. **This**: the challenge or puzzle being built with its Check (at the top when there is one), problems, name, statistics, the truth table, how it looks as a component, where the transistors are (each kind of part with its count; click a line to select those parts) and tools. **Pins**: every input and output of the circuit in pin order, one line each, with its live value (click it to flip a switch, hold it for a button; panel rows are framed under their panel); rename in place (Enter goes to the next), "Number all" names a whole side from a pattern (D# → D0, D1, …), duplicate names are flagged, the target icon centres the canvas on a part. Display and sound preferences are in Settings (gear in the top bar). It folds away to a strip of icons (the panel icon in its tab row, or [). The panel on the right is there only while something is selected: its settings and what to do with it (swap, wire them all, make a component out of it); x or Esc closes it.
|
- The right panel has four tabs. **Selection**: settings of what you clicked (switches to it when you select something on an idle panel). **Circuit**: name, symbol, group, statistics, and where the transistors are (each kind of part with its count; click a line to select those parts). **Pins**: every input and output of the circuit in pin order, one line each, with its live value (click it to flip a switch, hold it for a button; panel rows are framed under their panel); rename in place (Enter goes to the next), "Number all" names a whole side from a pattern (D# → D0, D1, …), duplicate names are flagged, the target icon centres the canvas on a part. **Test**: the challenge or puzzle check and the truth table (opens by itself for a challenge). Display and sound preferences are in Settings (gear in the top bar). Both side panels fold away to a strip of icons (the panel icon in their tab row, or [ and ]).
|
||||||
- Box selection: a box that touches no parts selects every wire and cable it crosses (drag across the wires between parts to bundle them). Dragged right to left (green box) it selects everything it touches, parts and wires. Left to right over parts it takes those parts and only the wires lying fully inside, so Delete never catches unrelated wires passing through.
|
- Box selection: a box that touches no parts selects every wire and cable it crosses (drag across the wires between parts to bundle them). Dragged right to left (green box) it selects everything it touches, parts and wires. Left to right over parts it takes those parts and only the wires lying fully inside, so Delete never catches unrelated wires passing through.
|
||||||
- Wiring many at once: select several parts and drag one wire from one of them to a pin of another part; the others follow onto that part's next pins, in position order (or use "Wire them all to" in the panel).
|
- Wiring many at once: select several parts and drag one wire from one of them to a pin of another part; the others follow onto that part's next pins, in position order (or use "Wire them all to" in the panel).
|
||||||
- Zooming out goes at least far enough to see the whole circuit, further for bigger circuits.
|
- Zooming out goes at least far enough to see the whole circuit, further for bigger circuits.
|
||||||
- Several selected parts are edited together: chips to narrow the selection by type, swap them all for another part, rename all top to bottom from a pattern, set every switch to 0 or 1 or flip each, one colour, one clock frequency or note size for all, line them up or spread them evenly, plus make component, connect one by one, unlink, duplicate, delete.
|
- Several selected parts are edited together: chips to narrow the selection by type, swap them all for another part, rename all top to bottom from a pattern, set every switch to 0 or 1 or flip each, one colour, one clock frequency or note size for all, line them up or spread them evenly, plus make component, connect one by one, unlink, duplicate, delete.
|
||||||
- Transistors: every part shows its count (4 for a NAND, 0 for switches, lamps and cables, the whole inside for a component; the NAND in the palette shows 4T). The count is 4 per CMOS NAND gate the simulator builds, at every depth; a test checks this against the flattened circuit for every example and every wide gate.
|
- Transistors: every part shows its count (4 for a NAND, 0 for switches, lamps and cables, the whole inside for a component; the NAND in the palette shows 4T). The count is 4 per CMOS NAND gate the simulator builds, at every depth; a test checks this against the flattened circuit for every example and every wide gate.
|
||||||
- Clicking anything opens its settings in the panel on the right. Parts can be swapped in place (wires stay on the pins in the same position): NAND and components with each other, switch/button/clock/constants with each other, output/lamp/display with each other. Clocks have their own frequency or follow the top bar. Switches and buttons can get a keyboard key. Lamps and displays have colours, notes have sizes, components a name on the canvas. Components can be unpacked into their parts or given their own copy of the definition; any part can have all its wires unlinked.
|
- Clicking anything opens its settings on the right. Parts can be swapped in place (wires stay on the pins in the same position): NAND and components with each other, switch/button/clock/constants with each other, output/lamp/display with each other. Clocks have their own frequency or follow the top bar. Switches and buttons can get a keyboard key. Lamps and displays have colours, notes have sizes, components a name on the canvas. Components can be unpacked into their parts or given their own copy of the definition; any part can have all its wires unlinked.
|
||||||
- Select parts and press "Make component" to turn them into a new component; wires crossing the selection become pins.
|
- Select parts and press "Make component" to turn them into a new component; wires crossing the selection become pins.
|
||||||
- Gate symbols in IEC 60617 (DIN, default) or ANSI. A component with one output can be drawn as a gate symbol.
|
- Gate symbols in IEC 60617 (DIN, default) or ANSI. A component with one output can be drawn as a gate symbol.
|
||||||
- Wires of different signals never share a line: auto-routed wires pick a free column or a detour, and anything still clashing (hand-placed bends) is drawn on its own lane. Crossings are drawn as a bow, triangle, bridge, gap or plain crossing (Settings, the gear in the top bar). Clicking a junction dot selects its whole signal.
|
- Wires of different signals never share a line: auto-routed wires pick a free column or a detour, and anything still clashing (hand-placed bends) is drawn on its own lane. Crossings are drawn as a bow, triangle, bridge, gap or plain crossing (Settings, the gear in the top bar). Clicking a junction dot selects its whole signal.
|
||||||
- Connecting: drag from a pin, or click a pin and then the other one. While a wire is drawn, every pin it can go to is ringed (dashed when it already has a wire, which would be replaced); dropping it on a part uses that part's next free pin. "Connect one by one" (W, or the button with several parts selected; on a component "Wire one by one: Inputs / Outputs") numbers the pins of the selection top to bottom and wires them in turn, one click each; clicking the same component again and again fills its pins in order.
|
- Connecting: drag from a pin, or click a pin and then the other one. While a wire is drawn, every pin it can go to is ringed (dashed when it already has a wire, which would be replaced); dropping it on a part uses that part's next free pin. "Connect one by one" (W, or the button with several parts selected; on a component "Wire one by one: Inputs / Outputs") numbers the pins of the selection top to bottom and wires them in turn, one click each; clicking the same component again and again fills its pins in order.
|
||||||
- Tidy wiring (Settings, or "Tidy all wires", which also drops hand-placed bends): every forward wire takes its vertical step in the free gap right in front of the part it feeds. All wires entering parts at the same column are ordered together (each goes where it adds the fewest crossings) and laid out as one compact staircase a grid step apart, slid sideways to where it runs along no other signal; one signal shares one trunk. Only the columns of that gap are looked at, so it stays cheap. On the 4-bit adder without hand routing this cuts crossings from 32 to 18.
|
- Tidy wiring (Settings, or "Tidy all wires", which also drops hand-placed bends): every forward wire takes its vertical step in the free gap right in front of the part it feeds. All wires entering parts at the same column are ordered together (each goes where it adds the fewest crossings) and laid out as one compact staircase a grid step apart, slid sideways to where it runs along no other signal; one signal shares one trunk. Only the columns of that gap are looked at, so it stays cheap. On the 4-bit adder without hand routing this cuts crossings from 32 to 18.
|
||||||
- Wire editing: drag any segment (a stub keeps the pin end straight), drag corner squares, Alt+drag to pull out a new bend, Ctrl+drag to branch a new wire off a signal, double-click to select the whole signal, Shift+click and box selection for several wires, arrow keys to shift them, six colour tags.
|
- Wire editing: drag any segment (a stub keeps the pin end straight), drag corner squares, Alt+drag to pull out a new bend, Ctrl+drag to branch a new wire off a signal, double-click to select the whole signal, Shift+click and box selection for several wires, arrow keys to shift them, six colour tags.
|
||||||
- Moving parts (drag one or several, or the arrow keys): wires between parts that move together go along with their bends. A wire to a part that stays keeps its hand-placed bends as long as the way through them stays clear (no part under it, a cable by its full width, no line of another signal, no pin it does not end on) and lets go of the others, which are laid out anew around the parts; a part put down on a wire's bends does the same to that wire. What shows while dragging is what stays, and one Ctrl+Z undoes the move.
|
- Several projects per browser (Projects dialog: open, rename, duplicate, delete). Export a project file, open a file as a new project, or add the components of a file to the open project.
|
||||||
- Saves are handled like a game: the main menu's "Load game" lists every save (open, rename, copy, delete, savegames, recently deleted, new, open a file), and in the editor Esc (with nothing selected) or the project button opens the pause menu: Resume, Save, Save as copy, Load, Settings, How to play, Main menu. Export a project file, open a file as a new project, or add the components of a file to the open project.
|
- Accounts: email and password. Signed in, every project in the browser is also kept in the account and synced in both directions (on sign-in, on focus, every minute, and two seconds after a change). If two computers changed the same project, both versions are kept. The untouched starter project of a new browser is not uploaded; signing in there opens your latest project instead.
|
||||||
- Accounts: email and password. Signed in, every project in the browser is also kept in the account and synced in both directions (on sign-in, on focus, every minute, and two seconds after a change). One save per project on every device: if two computers changed the same project, the newer save wins everywhere and the other one is kept as a savegame of that project (never as a second project). A new browser keeps its starter project unsaved until something changes in it, and while signed in the main menu waits for the account's saves before anything can be started, so a second device never makes a twin.
|
|
||||||
- Share links: `/p/<id>`. The creator's changes save to the link automatically. Anyone else who opens it gets their own copy; their first edit detaches it from the link.
|
- Share links: `/p/<id>`. The creator's changes save to the link automatically. Anyone else who opens it gets their own copy; their first edit detaches it from the link.
|
||||||
- Memory that stays: what latches, flip-flops, registers and RAM built from NANDs hold is kept per circuit, like a memory chip. Going into a component and back, reloading, or opening the project on another computer, a circuit starts from the bits it held. They are saved with the project (only the gates on feedback loops that are 1, plus the clocks that are high: 1,024 flip-flops take about 30 KB), whenever it is saved anyway. Between saves (a clock running, a button pressed) they go into this browser's copy every 30 seconds without counting as an edit; the account gets them when you leave the page or the project or sign out, never just because a clock runs, and an edit saved on another computer still wins over bits alone. A project that comes in (a newer save from another computer, a savegame) runs from its own bits. Each project has room for 500 KB of bits (roughly 15,000 flip-flops) on top of its 2 MB; when that is full, the circuits left longest ago start from 0, and a circuit that holds more than that on its own says so. "Power off and on" (menu on the circuit's name, or Space) starts the circuit again from all zeros. Switches keep their positions as before; buttons are let go.
|
|
||||||
- Truth table, NAND count, gate delay, and loop detection for the open circuit. The table can go full screen, be downloaded as CSV or copied as a Markdown table; the row the switches are set to is highlighted.
|
- Truth table, NAND count, gate delay, and loop detection for the open circuit. The table can go full screen, be downloaded as CSV or copied as a Markdown table; the row the switches are set to is highlighted.
|
||||||
- 17 challenges (NOT up to a D flip-flop) checked against a truth table or a step sequence.
|
- 17 challenges (NOT up to a D flip-flop) checked against a truth table or a step sequence.
|
||||||
- Example library, all built from NAND: NOT, AND, OR, NOR, XOR, XNOR, Mux, Half/Full Adder, SR Latch, D Latch, D Flip-Flop, Register 4, Increment 4, Adder 4, Counter 4, a counter demo with a hex display, and a 4×4 pixel screen with a demo.
|
- Example library, all built from NAND: NOT, AND, OR, NOR, XOR, XNOR, Mux, Half/Full Adder, SR Latch, D Latch, D Flip-Flop, Register 4, Increment 4, Adder 4, Counter 4, a counter demo with a hex display, and a 4×4 pixel screen with a demo.
|
||||||
|
|
@ -53,12 +46,9 @@ All in [app/lib/logic/](app/lib/logic/), plain TypeScript with no Vue dependency
|
||||||
- `compile.ts` flattens the component tree into a list of NAND gates over numbered nets. Chip boundaries and pins are aliases, merged with union-find. Net 0 is constant 0, net 1 constant 1.
|
- `compile.ts` flattens the component tree into a list of NAND gates over numbered nets. Chip boundaries and pins are aliases, merged with union-find. Net 0 is constant 0, net 1 constant 1.
|
||||||
- `sim.ts` is event-driven: a net change queues the gates that read it, and gates run in FIFO order on the newest values. NAND latches settle deterministically; a loop with an odd number of inversions never settles and the top bar shows "Oscillating".
|
- `sim.ts` is event-driven: a net change queues the gates that read it, and gates run in FIFO order on the newest values. NAND latches settle deterministically; a loop with an odd number of inversions never settles and the top bar shows "Oscillating".
|
||||||
- Gate outputs are keyed by their path ("chipNode/chipNode/nand"), so latch state survives editing.
|
- Gate outputs are keyed by their path ("chipNode/chipNode/nand"), so latch state survives editing.
|
||||||
- `state.ts` finds the gates on feedback loops (strongly connected gates, Tarjan) and packs those that are 1 for the project: each node id once, each gate as the path levels it shares with the gate before plus the rest. Restoring runs the gates in the order signals flow, so the gates in front of a latch are right before the latch reads them; ids that no longer exist are ignored.
|
|
||||||
- `analyze.ts` builds truth tables, counts NANDs, computes the longest gate path, and runs challenge tests.
|
- `analyze.ts` builds truth tables, counts NANDs, computes the longest gate path, and runs challenge tests.
|
||||||
- `examples.ts` builds the example library with a small builder; `ops.ts` holds project edits (package selection, copy/paste, prune dangling wires, recursion check).
|
- `examples.ts` builds the example library with a small builder; `ops.ts` holds project edits (package selection, copy/paste, prune dangling wires, recursion check).
|
||||||
- `routing.ts` lays out all wires of a circuit (free lanes, detours, separation, crossings, and the tidy layout), and after a move keeps the hand-placed bends that still leave a clear way (`settleCorners`).
|
- `routing.ts` lays out all wires of a circuit (free lanes, detours, separation, crossings, and the tidy layout).
|
||||||
- `move.ts` moves parts for a drag and the arrow keys, always from where they started, with their wires.
|
|
||||||
- `library.ts` gathers a component with everything it uses for the public library, checks what comes from outside and adds entries to a project (shared with the server, [server/api/library/](server/api/library/)).
|
|
||||||
- `progress.ts` holds the campaign rules; `puzzles.ts` makes, checks and scores puzzles and generates the weekly one (shared with the server, [server/api/puzzles/](server/api/puzzles/), storage in `data/puzzles`).
|
- `progress.ts` holds the campaign rules; `puzzles.ts` makes, checks and scores puzzles and generates the weekly one (shared with the server, [server/api/puzzles/](server/api/puzzles/), storage in `data/puzzles`).
|
||||||
- `cables.ts` bundles wires into cables (ends where you click, or next to sources and targets), takes them apart again, and lays out the ribbon lines (`offsetPath`, `ribbon`).
|
- `cables.ts` bundles wires into cables (ends where you click, or next to sources and targets), takes them apart again, and lays out the ribbon lines (`offsetPath`, `ribbon`).
|
||||||
- `panels.ts` docks input panels to components and keeps them in step; `labels.ts` does series names and names taken from pins.
|
- `panels.ts` docks input panels to components and keeps them in step; `labels.ts` does series names and names taken from pins.
|
||||||
|
|
@ -70,20 +60,16 @@ The editor UI is in [app/components/editor/](app/components/editor/) with state
|
||||||
|
|
||||||
[server/api/p/](server/api/p/): `POST /api/p` stores a project and returns `{ id, key }`; `GET /api/p/:id` reads it; `PUT /api/p/:id` with header `x-edit-key` replaces it. Only a SHA-256 of the key is stored. Each link is one JSON file in `data/shares/` (Nitro fs storage). Limits: 2 MB and 100,000 nodes per project, 30 new links and 600 saves per IP per 10 minutes (in memory). The edit key lives only in the creator's browser (project index in localStorage), never in exported files.
|
[server/api/p/](server/api/p/): `POST /api/p` stores a project and returns `{ id, key }`; `GET /api/p/:id` reads it; `PUT /api/p/:id` with header `x-edit-key` replaces it. Only a SHA-256 of the key is stored. Each link is one JSON file in `data/shares/` (Nitro fs storage). Limits: 2 MB and 100,000 nodes per project, 30 new links and 600 saves per IP per 10 minutes (in memory). The edit key lives only in the creator's browser (project index in localStorage), never in exported files.
|
||||||
|
|
||||||
## Library
|
|
||||||
|
|
||||||
[server/api/library/](server/api/library/): `POST /api/library` publishes `{ player, root, components, connectors }` and returns `{ id, key, version }`; `PUT /api/library/:id` with header `x-edit-key` publishes the next version; `DELETE /api/library/:id` with the key takes it out. `GET /api/library?q=` lists every entry, newest first, narrowed to those with every word in name, description, group or author; `GET /api/library/:id` returns one with its components (`?meta`: without). Each entry is one JSON file in `data/library/entries/`, plus `data/library/index` for the list (both in the daily backup). Only a SHA-256 of the key is stored; authors show by their leaderboard name, never by their player id. Challenge and library marks are dropped from what comes in, and the list keeps only short texts, pin counts and the first 16 pin names a side, so it stays small. Limits: 1 MB per entry, 30 publishes per IP per 10 minutes, 20,000 entries.
|
|
||||||
|
|
||||||
## Accounts
|
## Accounts
|
||||||
|
|
||||||
[server/api/auth/](server/api/auth/) (register, login, logout, me, password, delete) and [server/api/me/projects/](server/api/me/projects/) (list, get, put, delete). Passwords are hashed with scrypt; the session is a random token in an httpOnly, SameSite=Lax cookie, stored server-side as a SHA-256. API calls that change something are refused when their Origin is another site. Storage: `data/users`, `data/sessions`, `data/accounts/<uid>/` with an index (revision per project, deletions for a year), one file per project, and savegames in `h/<project>/`. Each save sends the revision it started from; a mismatch answers 409 and the browser keeps the other version as a copy. Limits: 1000 projects and 100 MB per account, 2 MB per project plus 500 KB for what its circuits hold, login 20 tries per 10 minutes per IP, 10 new accounts per hour per IP.
|
[server/api/auth/](server/api/auth/) (register, login, logout, me, password, delete) and [server/api/me/projects/](server/api/me/projects/) (list, get, put, delete). Passwords are hashed with scrypt; the session is a random token in an httpOnly, SameSite=Lax cookie, stored server-side as a SHA-256. API calls that change something are refused when their Origin is another site. Storage: `data/users`, `data/sessions`, `data/accounts/<uid>/` with an index (revision per project, deletions for a year), one file per project, and savegames in `h/<project>/`. Each save sends the revision it started from; a mismatch answers 409 and the browser keeps the other version as a copy. Limits: 1000 projects and 100 MB per account, 2 MB per project, login 20 tries per 10 minutes per IP, 10 new accounts per hour per IP.
|
||||||
|
|
||||||
## Power cuts, savegames, backups
|
## Power cuts, savegames, backups
|
||||||
|
|
||||||
No database: everything is JSON files under `data/`, which keeps memory use flat. Three layers protect it:
|
No database: everything is JSON files under `data/`, which keeps memory use flat. Three layers protect it:
|
||||||
|
|
||||||
- **Crash-safe writes** ([server/utils/safe-fs.ts](server/utils/safe-fs.ts), mounted in [server/plugins/storage.ts](server/plugins/storage.ts)). A save writes a temporary file, flushes it to disk, keeps the current intact version as `<file>.bak` and then renames the new file into place. A power cut at any moment leaves the old or the new version; reading falls back to `.bak` when a file is missing or damaged, and leftover temporary files are removed at start.
|
- **Crash-safe writes** ([server/utils/safe-fs.ts](server/utils/safe-fs.ts), mounted in [server/plugins/storage.ts](server/plugins/storage.ts)). A save writes a temporary file, flushes it to disk, keeps the current intact version as `<file>.bak` and then renames the new file into place. A power cut at any moment leaves the old or the new version; reading falls back to `.bak` when a file is missing or damaged, and leftover temporary files are removed at start.
|
||||||
- **Savegames** ([server/utils/history.ts](server/utils/history.ts)). Before a save replaces an account project, its state is kept as a version (at most one per 15 minutes; always before a restore and on deletion). Kept: the newest 30 plus the last of each day for 90 days. Deleted projects stay restorable for 30 days. In the app: Load game (main or pause menu), clock icon (restore, or open as copy), and "Recently deleted".
|
- **Savegames** ([server/utils/history.ts](server/utils/history.ts)). Before a save replaces an account project, its state is kept as a version (at most one per 15 minutes; always before a restore and on deletion). Kept: the newest 30 plus the last of each day for 90 days. Deleted projects stay restorable for 30 days. In the app: Projects dialog, clock icon (restore, or open as copy), and "Recently deleted".
|
||||||
- **Daily backup** ([server/utils/backup.ts](server/utils/backup.ts), [server/plugins/backup.ts](server/plugins/backup.ts)). Once a day the production server writes all of `data/` into `backups/logigate-YYYY-MM-DD.ndjson.gz`, leaving out damaged files. Kept: the newest 14 plus the first of each month for a year. `backups/` sits next to `data/` on the same disk, so it protects against damaged files and mistakes, not against losing the disk; copy it elsewhere for that.
|
- **Daily backup** ([server/utils/backup.ts](server/utils/backup.ts), [server/plugins/backup.ts](server/plugins/backup.ts)). Once a day the production server writes all of `data/` into `backups/logigate-YYYY-MM-DD.ndjson.gz`, leaving out damaged files. Kept: the newest 14 plus the first of each month for a year. `backups/` sits next to `data/` on the same disk, so it protects against damaged files and mistakes, not against losing the disk; copy it elsewhere for that.
|
||||||
|
|
||||||
Restore a backup on edgerealm (the current `data/` is moved aside first, so this can be undone):
|
Restore a backup on edgerealm (the current `data/` is moved aside first, so this can be undone):
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -7,14 +7,15 @@ function reload() {
|
||||||
location.reload()
|
location.reload()
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasSelection = computed(() => ed.selection.value.length + ed.wireSel.value.length > 0)
|
|
||||||
|
|
||||||
const link = computed(() => {
|
const link = computed(() => {
|
||||||
const l = ed.linking.value
|
const l = ed.linking.value
|
||||||
const end = l?.queue[l.at]
|
const end = l?.queue[l.at]
|
||||||
return l && end ? { n: l.at + 1, total: l.queue.length, label: end.label, dir: end.dir } : null
|
return l && end ? { n: l.at + 1, total: l.queue.length, label: end.label, dir: end.dir } : null
|
||||||
})
|
})
|
||||||
|
|
||||||
|
/** The side panel: kept open, or open while something is selected. */
|
||||||
|
const panel = computed(() => ed.sidebars.right || ed.selection.value.length + ed.wireSel.value.length > 0)
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
const stop = ed.startLoop()
|
const stop = ed.startLoop()
|
||||||
onBeforeUnmount(stop)
|
onBeforeUnmount(stop)
|
||||||
|
|
@ -36,18 +37,17 @@ watch(
|
||||||
<template>
|
<template>
|
||||||
<div class="app">
|
<div class="app">
|
||||||
<EditorMainMenu v-if="ed.screen.value === 'menu'" />
|
<EditorMainMenu v-if="ed.screen.value === 'menu'" />
|
||||||
<template v-else>
|
<div v-else class="workspace" :class="{ 'with-panel': panel, 'with-dock': ed.sidebars.left }">
|
||||||
<div class="workspace" :class="{ 'no-panel': !ed.panelOpen.value, 'has-selection': hasSelection }">
|
|
||||||
<EditorInspector v-if="ed.panelOpen.value" />
|
|
||||||
<EditorRail v-else />
|
|
||||||
<main class="stage">
|
<main class="stage">
|
||||||
<EditorCanvas />
|
<EditorCanvas />
|
||||||
</main>
|
</main>
|
||||||
<EditorSelectionPanel v-if="hasSelection" />
|
|
||||||
<EditorToolbar />
|
<EditorToolbar />
|
||||||
<EditorBottomBar />
|
<EditorInspector v-show="panel" />
|
||||||
|
<EditorDock v-if="ed.sidebars.left" />
|
||||||
|
<button v-else class="dock-show" title="Show the parts ([)" @click="ed.toggleSidebar('left', true)">
|
||||||
|
<Icon name="lucide:chevron-up" class="size-4" /> Parts
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
|
||||||
<Transition name="fade">
|
<Transition name="fade">
|
||||||
<div v-if="ed.notice.value" class="toast" :class="ed.notice.value.kind">{{ ed.notice.value.text }}</div>
|
<div v-if="ed.notice.value" class="toast" :class="ed.notice.value.kind">{{ ed.notice.value.text }}</div>
|
||||||
</Transition>
|
</Transition>
|
||||||
|
|
@ -68,23 +68,17 @@ watch(
|
||||||
<template v-if="link.total > 1">
|
<template v-if="link.total > 1">
|
||||||
<strong>{{ link.n }} of {{ link.total }}<template v-if="link.label">: {{ link.label }}</template></strong> ·
|
<strong>{{ link.n }} of {{ link.total }}<template v-if="link.label">: {{ link.label }}</template></strong> ·
|
||||||
</template>
|
</template>
|
||||||
Click the pin {{ link.dir === 'out' ? 'it goes to' : 'it comes from' }}, or a part to use its next free pin. <kbd>Shift</kbd> + click: one more from the same signal. <kbd>Esc</kbd> stops.
|
Click the pin {{ link.dir === 'out' ? 'it goes to' : 'it comes from' }}, or a part to use its next free pin. <kbd>Esc</kbd> stops.
|
||||||
</div>
|
</div>
|
||||||
<EditorTruthTableDialog v-if="ed.dialog.value === 'table'" />
|
<EditorTruthTableDialog v-if="ed.dialog.value === 'table'" />
|
||||||
<EditorPublishDialog v-if="ed.dialog.value === 'publish'" />
|
<EditorPublishDialog v-if="ed.dialog.value === 'publish'" />
|
||||||
<EditorConnectorDialog v-if="ed.dialog.value === 'connector'" />
|
|
||||||
<EditorHelp v-if="ed.showHelp.value" />
|
<EditorHelp v-if="ed.showHelp.value" />
|
||||||
<EditorPauseMenu v-if="ed.paused.value && ed.screen.value === 'editor'" />
|
<EditorProjectsDialog v-if="ed.dialog.value === 'projects'" />
|
||||||
<EditorShareDialog v-if="ed.dialog.value === 'share'" />
|
<EditorShareDialog v-if="ed.dialog.value === 'share'" />
|
||||||
<EditorAccountDialog v-if="ed.dialog.value === 'account'" />
|
<EditorAccountDialog v-if="ed.dialog.value === 'account'" />
|
||||||
<EditorVersionsDialog v-if="ed.dialog.value === 'versions'" />
|
<EditorVersionsDialog v-if="ed.dialog.value === 'versions'" />
|
||||||
<EditorSettingsDialog v-if="ed.dialog.value === 'settings'" />
|
<EditorSettingsDialog v-if="ed.dialog.value === 'settings'" />
|
||||||
<EditorSearchDialog v-if="ed.dialog.value === 'search'" />
|
<EditorSearchDialog v-if="ed.dialog.value === 'search'" />
|
||||||
<EditorFaceDialog v-if="ed.dialog.value === 'face'" />
|
<EditorFaceDialog v-if="ed.dialog.value === 'face'" />
|
||||||
<EditorLibraryDialog v-if="ed.dialog.value === 'library'" />
|
|
||||||
<EditorLibraryPublishDialog v-if="ed.dialog.value === 'library-publish'" />
|
|
||||||
<EditorConvertDialog v-if="ed.dialog.value === 'convert'" />
|
|
||||||
<EditorAsmDialog v-if="ed.dialog.value === 'asm'" />
|
|
||||||
<EditorBenchDialog v-if="ed.benchOpen.value" />
|
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
|
||||||
|
|
@ -1,128 +0,0 @@
|
||||||
<script setup lang="ts">
|
|
||||||
// The assembler: a program in your own instruction set becomes words, which
|
|
||||||
// copy out as hex or binary or go straight into the switch panels of the
|
|
||||||
// memory you built.
|
|
||||||
import { assemble, binWord, hexWord, MAX_WIDTH, memoryPanels } from '~/lib/asm'
|
|
||||||
|
|
||||||
const ed = useEditor()
|
|
||||||
const close = () => (ed.dialog.value = null)
|
|
||||||
const doc = ed.asmDoc
|
|
||||||
|
|
||||||
const result = computed(() => assemble(doc.value.source, doc.value.table, doc.value.width))
|
|
||||||
const sourceErrors = computed(() => result.value.errors.filter(e => e.where === 'source'))
|
|
||||||
const tableErrors = computed(() => result.value.errors.filter(e => e.where === 'table'))
|
|
||||||
const showTable = ref(!ed.project.value.asm)
|
|
||||||
|
|
||||||
/** Circuits with panels of switches to hold words. */
|
|
||||||
const targets = computed(() =>
|
|
||||||
ed.project.value.components
|
|
||||||
.map(d => {
|
|
||||||
const panels = memoryPanels(d)
|
|
||||||
const rows = Math.min(...panels.map(p => p.rows!.length))
|
|
||||||
return { d, panels, rows, outside: d.id === ed.def.value.id ? 0 : panels.filter(p => !p.inner).length }
|
|
||||||
})
|
|
||||||
.filter(t => t.panels.length),
|
|
||||||
)
|
|
||||||
const target = computed(() => targets.value.find(t => t.d.id === doc.value.target) ?? targets.value.find(t => t.d.id === ed.def.value.id) ?? targets.value[0])
|
|
||||||
|
|
||||||
function setWidth(e: Event) {
|
|
||||||
const v = Math.round(Number((e.target as HTMLInputElement).value))
|
|
||||||
if (v >= 1 && v <= MAX_WIDTH) ed.saveAsm({ width: v })
|
|
||||||
}
|
|
||||||
const copyAll = (fmt: 'hex' | 'bin') => ed.copyText(result.value.image.map(v => (fmt === 'hex' ? hexWord(v, doc.value.width) : binWord(v, doc.value.width))).join(' '), `${result.value.image.length} words copied`)
|
|
||||||
function load() {
|
|
||||||
const t = target.value
|
|
||||||
if (t) ed.loadProgram(t.d.id, result.value.image, doc.value.width, !!doc.value.msbTop)
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div class="modal-backdrop" @click.self="close">
|
|
||||||
<div class="modal asm" role="dialog" aria-labelledby="asm-title">
|
|
||||||
<div class="flex items-start justify-between gap-4">
|
|
||||||
<h2 id="asm-title">Assembler</h2>
|
|
||||||
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
|
|
||||||
</div>
|
|
||||||
<p class="hint">
|
|
||||||
Your own instruction set turns a program into words for the memory you built. Labels end with <code>:</code>, comments start with <code>;</code>.
|
|
||||||
<code>.org 16</code> moves on to an address, <code>.word 1, 'A', "Hi"</code> puts words as they are, <code>.fill 4, 0</code> repeats one, <code>N = 5</code> names a value.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div class="asm-grid">
|
|
||||||
<div class="asm-col">
|
|
||||||
<div class="asm-bar">
|
|
||||||
<span class="font-semibold">Program</span>
|
|
||||||
<span class="grow" />
|
|
||||||
<label class="asm-width" title="Bits per memory word">
|
|
||||||
Word
|
|
||||||
<input type="number" min="1" :max="MAX_WIDTH" :value="doc.width" class="field-input" @change="setWidth" />
|
|
||||||
bits
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
<textarea class="field-input asm-text" spellcheck="false" rows="14" :value="doc.source" @input="ed.saveAsm({ source: ($event.target as HTMLTextAreaElement).value })" />
|
|
||||||
<ul v-if="sourceErrors.length" class="asm-errors">
|
|
||||||
<li v-for="(e, i) in sourceErrors.slice(0, 20)" :key="i"><span class="tabular-nums">Line {{ e.line }}</span> {{ e.text }}</li>
|
|
||||||
</ul>
|
|
||||||
<button class="asm-fold" @click="showTable = !showTable">
|
|
||||||
<Icon :name="showTable ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-3.5" />
|
|
||||||
Instruction set
|
|
||||||
<span class="hint">{{ tableErrors.length ? `${tableErrors.length} to fix` : 'name, opcode bits, operands as name:bits' }}</span>
|
|
||||||
</button>
|
|
||||||
<template v-if="showTable">
|
|
||||||
<textarea class="field-input asm-text" spellcheck="false" rows="10" :value="doc.table" @input="ed.saveAsm({ table: ($event.target as HTMLTextAreaElement).value })" />
|
|
||||||
<ul v-if="tableErrors.length" class="asm-errors">
|
|
||||||
<li v-for="(e, i) in tableErrors.slice(0, 20)" :key="i"><span class="tabular-nums">Line {{ e.line }}</span> {{ e.text }}</li>
|
|
||||||
</ul>
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="asm-col">
|
|
||||||
<div class="asm-bar">
|
|
||||||
<span class="font-semibold">Words</span>
|
|
||||||
<span class="hint">{{ result.image.length }} words</span>
|
|
||||||
<span class="grow" />
|
|
||||||
<button class="btn-sm" :disabled="!result.image.length" @click="copyAll('hex')"><Icon name="lucide:copy" class="size-3.5" /> Hex</button>
|
|
||||||
<button class="btn-sm" :disabled="!result.image.length" @click="copyAll('bin')"><Icon name="lucide:copy" class="size-3.5" /> Binary</button>
|
|
||||||
</div>
|
|
||||||
<div class="asm-listing">
|
|
||||||
<table class="convert-table tabular-nums">
|
|
||||||
<thead>
|
|
||||||
<tr><th>Address</th><th>Hex</th><th>Binary</th><th>Line</th></tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
<template v-for="l in result.lines.slice(0, 512)" :key="l.line">
|
|
||||||
<tr v-for="(w, k) in l.words.slice(0, 64)" :key="k">
|
|
||||||
<td>{{ hexWord(l.addr + k, 8) }}</td>
|
|
||||||
<td>{{ hexWord(w, doc.width) }}</td>
|
|
||||||
<td>{{ binWord(w, doc.width) }}</td>
|
|
||||||
<td class="asm-src">{{ k ? '' : l.text }}</td>
|
|
||||||
</tr>
|
|
||||||
</template>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="asm-load">
|
|
||||||
<span class="font-semibold">Into memory</span>
|
|
||||||
<p v-if="!targets.length" class="hint">
|
|
||||||
Build memory from input panels of switches, one panel per word (in a component, set them to stay inside). Words then go in here, in reading order.
|
|
||||||
</p>
|
|
||||||
<template v-else>
|
|
||||||
<select class="tb-select" :value="target?.d.id" @change="ed.saveAsm({ target: ($event.target as HTMLSelectElement).value })">
|
|
||||||
<option v-for="t in targets" :key="t.d.id" :value="t.d.id">{{ t.d.name }} · {{ t.panels.length }} panels of {{ t.rows }}</option>
|
|
||||||
</select>
|
|
||||||
<div class="seg" title="Which switch of a panel is bit 0">
|
|
||||||
<button :class="{ active: !doc.msbTop }" @click="ed.saveAsm({ msbTop: false })">Top row is bit 0</button>
|
|
||||||
<button :class="{ active: doc.msbTop }" @click="ed.saveAsm({ msbTop: true })">Top row is the highest bit</button>
|
|
||||||
</div>
|
|
||||||
<p v-if="target?.outside" class="hint">{{ target.outside }} of its panels are inputs when it is placed: set them to stay inside to make them its memory.</p>
|
|
||||||
<button class="btn btn-primary" :disabled="!result.image.length || result.errors.length > 0" @click="load">
|
|
||||||
<Icon name="lucide:download" class="size-3.5" /> Load {{ result.image.length }} words into {{ target?.d.name }}
|
|
||||||
</button>
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
@ -1,191 +0,0 @@
|
||||||
<script setup lang="ts">
|
|
||||||
// A test bench's columns and rows. Drive columns are its output pins (it
|
|
||||||
// sets them), check columns its input pins (it reads and checks them). Each
|
|
||||||
// row sets the drive columns, gives the circuit ticks, then checks.
|
|
||||||
import { checkCols, combinationRows, driveCols, recordExpected } from '~/lib/logic/bench'
|
|
||||||
import { uid } from '~/lib/logic/ops'
|
|
||||||
import type { BenchCol, BenchRow } from '~/lib/logic/types'
|
|
||||||
|
|
||||||
const ed = useEditor()
|
|
||||||
const close = () => (ed.benchOpen.value = null)
|
|
||||||
const node = computed(() => ed.def.value.nodes.find(n => n.id === ed.benchOpen.value && n.kind === 'bench'))
|
|
||||||
watch(node, n => !n && close())
|
|
||||||
const cols = computed(() => node.value?.bench?.cols ?? [])
|
|
||||||
const drives = computed(() => driveCols(node.value?.bench))
|
|
||||||
const checks = computed(() => checkCols(node.value?.bench))
|
|
||||||
const rows = computed(() => node.value?.bench?.rows ?? [])
|
|
||||||
const result = computed(() => (node.value ? ed.benchResults.value.get(node.value.id) : undefined))
|
|
||||||
|
|
||||||
function onKey(e: KeyboardEvent) {
|
|
||||||
if (e.key === 'Escape') close()
|
|
||||||
}
|
|
||||||
onMounted(() => {
|
|
||||||
window.addEventListener('keydown', onKey)
|
|
||||||
if (node.value && !result.value) ed.runBenchNow(node.value.id)
|
|
||||||
})
|
|
||||||
onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
|
|
||||||
|
|
||||||
const id = () => node.value!.id
|
|
||||||
/** Columns change the bench's pins: a structural change. */
|
|
||||||
const setCols = (f: (c: BenchCol[]) => void) => ed.setBench(id(), b => f((b.cols ??= [])), true)
|
|
||||||
function addCol(dir: BenchCol['dir']) {
|
|
||||||
const used = new Set(cols.value.map(c => c.name))
|
|
||||||
let k = cols.value.filter(c => c.dir === dir).length
|
|
||||||
const base = dir === 'drive' ? 'IN' : 'OUT'
|
|
||||||
while (used.has(`${base}${k}`)) k++
|
|
||||||
setCols(c => c.push({ id: uid('c'), name: `${base}${k}`, bits: 1, dir }))
|
|
||||||
}
|
|
||||||
const renameCol = (i: number, name: string) => name.trim() && setCols(c => (c[i]!.name = name.trim().slice(0, 40)))
|
|
||||||
function setBits(i: number, v: string) {
|
|
||||||
const n = Math.round(Number(v))
|
|
||||||
if (n >= 1 && n <= 32) setCols(c => (c[i]!.bits = n))
|
|
||||||
}
|
|
||||||
const removeCol = (i: number) => setCols(c => c.splice(i, 1))
|
|
||||||
function moveCol(i: number, by: number) {
|
|
||||||
setCols(c => {
|
|
||||||
const j = i + by
|
|
||||||
if (j < 0 || j >= c.length) return
|
|
||||||
;[c[i], c[j]] = [c[j]!, c[i]!]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
function setCell(i: number, side: 'set' | 'expect', colId: string, v: string) {
|
|
||||||
ed.setBench(id(), b => {
|
|
||||||
const row = b.rows[i]
|
|
||||||
if (!row) return
|
|
||||||
const cells = { ...(row[side] ?? {}) }
|
|
||||||
if (v.trim()) cells[colId] = v.trim()
|
|
||||||
else delete cells[colId]
|
|
||||||
if (Object.keys(cells).length) row[side] = cells
|
|
||||||
else delete row[side]
|
|
||||||
})
|
|
||||||
}
|
|
||||||
function setTicks(i: number, v: string) {
|
|
||||||
ed.setBench(id(), b => {
|
|
||||||
const row = b.rows[i]
|
|
||||||
if (!row) return
|
|
||||||
if (v.trim()) row.ticks = v.trim()
|
|
||||||
else delete row.ticks
|
|
||||||
})
|
|
||||||
}
|
|
||||||
function addRow(at = rows.value.length) {
|
|
||||||
// A new row starts as a copy of the one above, without its checks.
|
|
||||||
const above = rows.value[at - 1]
|
|
||||||
const row: BenchRow = above?.set ? { set: { ...above.set } } : {}
|
|
||||||
ed.setBench(id(), b => b.rows.splice(at, 0, row))
|
|
||||||
}
|
|
||||||
const removeRow = (i: number) => ed.setBench(id(), b => b.rows.splice(i, 1))
|
|
||||||
function combinations() {
|
|
||||||
const b = node.value?.bench
|
|
||||||
if (!b) return
|
|
||||||
const r = combinationRows(b)
|
|
||||||
if ('error' in r) return ed.notify(r.error, 'error')
|
|
||||||
ed.setBench(id(), x => (x.rows = r))
|
|
||||||
ed.notify(`${r.length} rows, one for every combination. Fill in what it should read, or take what it does.`)
|
|
||||||
}
|
|
||||||
function takeExpected() {
|
|
||||||
ed.runBenchNow(id(), true)
|
|
||||||
const r = result.value
|
|
||||||
if (!r) return
|
|
||||||
ed.setBench(id(), b => (b.rows = recordExpected(r, b.rows)))
|
|
||||||
ed.notify('Empty checks set to what it reads now: the tests keep it that way')
|
|
||||||
}
|
|
||||||
|
|
||||||
/** What a failing check cell read, when it differs. */
|
|
||||||
function gotNote(i: number, colId: string): string {
|
|
||||||
const r = result.value?.rows[i]
|
|
||||||
const want = rows.value[i]?.expect?.[colId] ?? ''
|
|
||||||
const got = r?.got[colId]
|
|
||||||
if (!r || r.ok !== false || got === undefined || !want) return ''
|
|
||||||
return Number(want) === got ? '' : `is ${got}`
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div class="modal-backdrop" @click.self="close">
|
|
||||||
<div class="modal bench" role="dialog" aria-labelledby="bench-title">
|
|
||||||
<div class="flex items-start justify-between gap-4">
|
|
||||||
<h2 id="bench-title">{{ node?.label?.trim() || 'Test bench' }}</h2>
|
|
||||||
<button class="tb-btn" title="Close (Esc)" @click="close"><Icon name="lucide:x" class="size-4" /></button>
|
|
||||||
</div>
|
|
||||||
<p class="hint">
|
|
||||||
Wire its pins to what you test: <strong>drive</strong> columns are its outputs (on the right of its box), <strong>check</strong> columns its inputs (on the left).
|
|
||||||
Each row sets the drive columns, gives ticks, then checks. A run takes this circuit on its own from all zeros; what it holds carries to the next row.
|
|
||||||
Drive: a number (12, 0x0C, 0b1100), <code>P</code> for a clock pulse, empty to leave it. Check: what it should read, empty for any.
|
|
||||||
Ticks: <code>5</code> pulses (P columns and the circuit's clocks), or <code>≤1000</code> to wait until the checks hold. Click a row on the box to put it on the running circuit.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h3>Columns</h3>
|
|
||||||
<div class="bench-cols">
|
|
||||||
<div v-for="(c, i) in cols" :key="c.id" class="bench-col" :class="c.dir">
|
|
||||||
<span class="bench-col-dir">{{ c.dir === 'drive' ? 'Drive' : 'Check' }}</span>
|
|
||||||
<input class="field-input" :value="c.name" spellcheck="false" @change="renameCol(i, ($event.target as HTMLInputElement).value)" />
|
|
||||||
<label title="Bits: one pin each">
|
|
||||||
<input class="field-input bench-bits" type="number" min="1" max="32" :value="c.bits" @change="setBits(i, ($event.target as HTMLInputElement).value)" />
|
|
||||||
bits
|
|
||||||
</label>
|
|
||||||
<button class="icon-btn" title="Further left" :disabled="i === 0" @click="moveCol(i, -1)"><Icon name="lucide:chevron-up" class="size-3.5" /></button>
|
|
||||||
<button class="icon-btn" title="Further right" :disabled="i === cols.length - 1" @click="moveCol(i, 1)"><Icon name="lucide:chevron-down" class="size-3.5" /></button>
|
|
||||||
<button class="icon-btn" title="Remove the column (and its pins)" @click="removeCol(i)"><Icon name="lucide:trash-2" class="size-3.5" /></button>
|
|
||||||
</div>
|
|
||||||
<div class="bench-bar">
|
|
||||||
<button class="btn-sm" @click="addCol('drive')"><Icon name="lucide:plus" class="size-3.5" /> Drive column</button>
|
|
||||||
<button class="btn-sm" @click="addCol('check')"><Icon name="lucide:plus" class="size-3.5" /> Check column</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<h3>Rows</h3>
|
|
||||||
<div class="bench-bar">
|
|
||||||
<p v-if="result" class="bench-summary" :class="result.fail || result.error ? 'fail' : result.pass ? 'pass' : ''">
|
|
||||||
<template v-if="result.error">{{ result.error }}. </template>
|
|
||||||
<template v-if="result.fail">{{ result.fail }} failing, {{ result.pass }} pass</template>
|
|
||||||
<template v-else-if="result.pass">All {{ result.pass }} pass</template>
|
|
||||||
</p>
|
|
||||||
<span class="grow" />
|
|
||||||
<button class="btn-sm" :disabled="!drives.length" title="A row for every combination of the drive columns" @click="combinations"><Icon name="lucide:grid-3x3" class="size-3.5" /> Every combination</button>
|
|
||||||
<button class="btn-sm" :disabled="!rows.length || !checks.length" title="Empty checks: what it reads now" @click="takeExpected"><Icon name="lucide:camera" class="size-3.5" /> Take what it does</button>
|
|
||||||
<button class="btn-sm" :disabled="!rows.length" title="Run again, longer runs allowed" @click="node && ed.runBenchNow(node.id, true)"><Icon name="lucide:play" class="size-3.5" /> Run</button>
|
|
||||||
</div>
|
|
||||||
<div v-if="cols.length" class="bench-table-wrap">
|
|
||||||
<table class="bench-table">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th class="bench-num">#</th>
|
|
||||||
<th v-for="c in drives" :key="c.id" :title="`${c.bits} bit${c.bits === 1 ? '' : 's'}`">{{ c.name }}</th>
|
|
||||||
<th class="bench-arrow">→</th>
|
|
||||||
<th v-for="c in checks" :key="c.id" class="out" :title="`${c.bits} bit${c.bits === 1 ? '' : 's'}`">{{ c.name }}</th>
|
|
||||||
<th>Ticks</th>
|
|
||||||
<th />
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
<tr v-for="(row, i) in rows" :key="i" :class="result?.rows[i]?.ok === false ? 'fail' : result?.rows[i]?.ok ? 'pass' : ''">
|
|
||||||
<td class="bench-num tabular-nums">{{ i + 1 }}</td>
|
|
||||||
<td v-for="c in drives" :key="c.id">
|
|
||||||
<input :value="row.set?.[c.id] ?? ''" class="bench-cell" spellcheck="false" @change="setCell(i, 'set', c.id, ($event.target as HTMLInputElement).value)" />
|
|
||||||
</td>
|
|
||||||
<td class="bench-arrow" :title="result?.rows[i]?.error ?? ''">
|
|
||||||
<Icon v-if="result?.rows[i]?.ok === false" name="lucide:x" class="size-3.5 text-(--danger)" />
|
|
||||||
<Icon v-else-if="result?.rows[i]?.ok" name="lucide:check" class="size-3.5 text-(--on)" />
|
|
||||||
</td>
|
|
||||||
<td v-for="c in checks" :key="c.id" class="out">
|
|
||||||
<input :value="row.expect?.[c.id] ?? ''" class="bench-cell" spellcheck="false" :placeholder="String(result?.rows[i]?.got[c.id] ?? '')" @change="setCell(i, 'expect', c.id, ($event.target as HTMLInputElement).value)" />
|
|
||||||
<span v-if="gotNote(i, c.id)" class="bench-got">{{ gotNote(i, c.id) }}</span>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<input :value="row.ticks ?? ''" class="bench-cell" spellcheck="false" :placeholder="result?.rows[i]?.ticks ? String(result.rows[i]!.ticks) : ''" @change="setTicks(i, ($event.target as HTMLInputElement).value)" />
|
|
||||||
</td>
|
|
||||||
<td class="bench-actions">
|
|
||||||
<span v-if="result?.rows[i]?.error" class="bench-err" :title="result.rows[i]!.error">{{ result.rows[i]!.error }}</span>
|
|
||||||
<button class="icon-btn" title="New row below" @click="addRow(i + 1)"><Icon name="lucide:plus" class="size-3.5" /></button>
|
|
||||||
<button class="icon-btn" title="Remove this row" @click="removeRow(i)"><Icon name="lucide:trash-2" class="size-3.5" /></button>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
<p v-else class="hint">Add columns first, or drop the bench on a component to get one for each of its pins.</p>
|
|
||||||
<button v-if="cols.length" class="btn-sm bench-add" @click="addRow()"><Icon name="lucide:plus" class="size-3.5" /> Row</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
@ -1,371 +0,0 @@
|
||||||
<script setup lang="ts">
|
|
||||||
// The floating bar at the bottom of the canvas, like Figma's toolbar: one
|
|
||||||
// button per kind of part. Pointing at one opens its parts above it; click
|
|
||||||
// a part to place it (or drag it onto the canvas), pin it to keep it on the
|
|
||||||
// bar itself. Components and your connector types have their own buttons.
|
|
||||||
// Parts and components show as drawn tiles in a strip, like a city
|
|
||||||
// builder's: the mouse wheel scrolls it sideways.
|
|
||||||
import { shortCount } from '~/lib/logic/analyze'
|
|
||||||
import { BASIC_GROUPS } from '~/composables/useParts'
|
|
||||||
import { unusedComponents } from '~/lib/logic/check'
|
|
||||||
import type { ComponentDef, NodeKind } from '~/lib/logic/types'
|
|
||||||
|
|
||||||
const ed = useEditor()
|
|
||||||
const { place, dragStart, dragEnd, isPinned, togglePin, pinned, unpin } = usePlace()
|
|
||||||
const { componentGroups } = useParts()
|
|
||||||
|
|
||||||
const ICONS: Record<string, string> = {
|
|
||||||
Logic: 'lucide:square-function',
|
|
||||||
Inputs: 'lucide:toggle-left',
|
|
||||||
Outputs: 'lucide:lightbulb',
|
|
||||||
Wiring: 'lucide:spline',
|
|
||||||
Notes: 'lucide:sticky-note',
|
|
||||||
}
|
|
||||||
|
|
||||||
type Cat = { id: string; label: string; icon: string }
|
|
||||||
const cats = computed<Cat[]>(() => [
|
|
||||||
...BASIC_GROUPS.map(g => ({ id: g.name, label: g.name, icon: ICONS[g.name] ?? 'lucide:shapes' })),
|
|
||||||
{ id: 'connectors', label: 'Connectors', icon: 'lucide:plug' },
|
|
||||||
{ id: 'components', label: 'Components', icon: 'lucide:boxes' },
|
|
||||||
])
|
|
||||||
|
|
||||||
// ── Flyout: opens on pointing, stays while the pointer is over it ──
|
|
||||||
const open = ref<string | null>(null)
|
|
||||||
let timer: ReturnType<typeof setTimeout> | undefined
|
|
||||||
|
|
||||||
const dock = ref<HTMLElement>()
|
|
||||||
const fly = ref<HTMLElement>()
|
|
||||||
/** Pointer position along the dock, the dock's width and the flyout's, in px. */
|
|
||||||
const at = ref({ x: 0, dock: 0, fly: 250 })
|
|
||||||
/** Where the flyout opens: centred above the pointer, kept inside the canvas. */
|
|
||||||
const anchor = computed(() => {
|
|
||||||
const half = at.value.fly / 2
|
|
||||||
return Math.min(Math.max(at.value.x, half), Math.max(half, at.value.dock - half))
|
|
||||||
})
|
|
||||||
function anchorAt(x: number) {
|
|
||||||
const r = dock.value!.getBoundingClientRect()
|
|
||||||
at.value = { ...at.value, x: x - r.left, dock: r.width }
|
|
||||||
}
|
|
||||||
function measure() {
|
|
||||||
if (fly.value) at.value = { ...at.value, fly: fly.value.offsetWidth }
|
|
||||||
const el = strip.value
|
|
||||||
edges.value = el ? { left: el.scrollLeft > 4, right: el.scrollLeft + el.clientWidth < el.scrollWidth - 4 } : { left: false, right: false }
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── The strip of tiles: sideways with the wheel, arrows at the ends ──
|
|
||||||
const strip = ref<HTMLElement>()
|
|
||||||
const edges = ref({ left: false, right: false })
|
|
||||||
function onWheel(e: WheelEvent) {
|
|
||||||
const el = strip.value
|
|
||||||
if (!el || Math.abs(e.deltaX) > Math.abs(e.deltaY)) return
|
|
||||||
e.preventDefault()
|
|
||||||
el.scrollLeft += e.deltaY
|
|
||||||
}
|
|
||||||
/** Pinned parts that do not fit: the wheel scrolls them sideways too. */
|
|
||||||
function sideways(e: WheelEvent) {
|
|
||||||
const el = e.currentTarget as HTMLElement
|
|
||||||
if (el.scrollWidth <= el.clientWidth || Math.abs(e.deltaX) > Math.abs(e.deltaY)) return
|
|
||||||
e.preventDefault()
|
|
||||||
el.scrollLeft += e.deltaY
|
|
||||||
}
|
|
||||||
function page(dir: number) {
|
|
||||||
strip.value?.scrollBy({ left: dir * strip.value.clientWidth * 0.8, behavior: 'smooth' })
|
|
||||||
}
|
|
||||||
|
|
||||||
const placeable = (d: ComponentDef) => d.id !== ed.def.value.id && ed.canPlace(d.id)
|
|
||||||
|
|
||||||
/** Components placed nowhere (not the open one, Main, examples or challenges): a tab of their own, to clear out. */
|
|
||||||
const UNUSED = 'unused'
|
|
||||||
const unused = computed(() => unusedComponents(ed.project.value).filter(d => d.id !== ed.def.value.id && d.id !== ed.mainId.value))
|
|
||||||
const confirmDrop = ref<string | null>(null)
|
|
||||||
function drop(d: ComponentDef) {
|
|
||||||
if (confirmDrop.value !== d.id) return (confirmDrop.value = d.id)
|
|
||||||
confirmDrop.value = null
|
|
||||||
ed.removeComponent(d.id)
|
|
||||||
ed.notify(`Deleted "${d.name}" (Ctrl+Z brings it back)`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The component group shown; your own components first. */
|
|
||||||
const compTab = ref('')
|
|
||||||
const compGroup = computed(
|
|
||||||
() =>
|
|
||||||
(compTab.value === UNUSED && unused.value.length ? { name: 'Unused', defs: unused.value } : undefined) ??
|
|
||||||
componentGroups.value.find(g => g.name === compTab.value) ??
|
|
||||||
// Untouched: the first group with something that can go in here.
|
|
||||||
componentGroups.value.find(g => g.defs.some(placeable)) ??
|
|
||||||
componentGroups.value[0],
|
|
||||||
)
|
|
||||||
|
|
||||||
function show(id: string, e: PointerEvent) {
|
|
||||||
clearTimeout(timer)
|
|
||||||
const go = () => {
|
|
||||||
if (open.value !== id) anchorAt(e.clientX)
|
|
||||||
open.value = id
|
|
||||||
}
|
|
||||||
// Moving along the bar switches at once; the first one waits a moment.
|
|
||||||
if (open.value) go()
|
|
||||||
else timer = setTimeout(go, 110)
|
|
||||||
}
|
|
||||||
|
|
||||||
function leave() {
|
|
||||||
clearTimeout(timer)
|
|
||||||
// While a part is dragged out of it, the flyout stays (it closes when the drag ends).
|
|
||||||
if (ed.dragPart.value) return
|
|
||||||
timer = setTimeout(() => (open.value = null), 220)
|
|
||||||
}
|
|
||||||
|
|
||||||
function stay() {
|
|
||||||
clearTimeout(timer)
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggle(id: string, e: MouseEvent) {
|
|
||||||
if (open.value === id) open.value = null
|
|
||||||
else {
|
|
||||||
clearTimeout(timer)
|
|
||||||
anchorAt(e.clientX)
|
|
||||||
open.value = id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function pick(kind: NodeKind, chip?: string, conn?: string) {
|
|
||||||
place(kind, chip, conn)
|
|
||||||
open.value = null
|
|
||||||
}
|
|
||||||
|
|
||||||
function endDrag() {
|
|
||||||
dragEnd()
|
|
||||||
open.value = null
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/** Which button the part being placed belongs to, to show it as active. */
|
|
||||||
const activeCat = computed(() => {
|
|
||||||
const p = ed.placing.value
|
|
||||||
if (!p) return null
|
|
||||||
if (p.kind === 'chip') return 'components'
|
|
||||||
if (p.kind === 'portin' || p.kind === 'portout') return 'connectors'
|
|
||||||
return BASIC_GROUPS.find(g => g.parts.some(x => x.kind === p.kind))?.name ?? null
|
|
||||||
})
|
|
||||||
|
|
||||||
const group = computed(() => BASIC_GROUPS.find(g => g.name === open.value))
|
|
||||||
/** Components that belong with a kind of part: gates (drawn as one, or in the Gates group) under Logic. */
|
|
||||||
const groupComps = computed(() =>
|
|
||||||
open.value === 'Logic' ? ed.project.value.components.filter(d => d.group?.trim() === 'Gates' || (d.symbol && d.symbol !== 'box')) : [],
|
|
||||||
)
|
|
||||||
watch([open, compTab, () => compGroup.value?.defs.length, () => groupComps.value.length], () => nextTick(measure))
|
|
||||||
const connectors = computed(() => ed.project.value.connectors ?? [])
|
|
||||||
const portsOk = computed(() => ed.canPlaceKind('portin'))
|
|
||||||
// Pinned parts sit on the bar; a pinned component this project lacks is left out.
|
|
||||||
const shown = computed(() => pinned.value.filter(p => p.kind !== 'chip' || p.chip))
|
|
||||||
const named = (p: { kind: NodeKind }) => p.kind === 'chip' || p.kind === 'nand'
|
|
||||||
|
|
||||||
function onKey(e: KeyboardEvent) {
|
|
||||||
if (e.key === 'Escape' && open.value) {
|
|
||||||
open.value = null
|
|
||||||
e.stopPropagation()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
onMounted(() => window.addEventListener('keydown', onKey, true))
|
|
||||||
onBeforeUnmount(() => window.removeEventListener('keydown', onKey, true))
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div ref="dock" class="bottom-dock" @pointerdown.stop>
|
|
||||||
<Transition name="flyout">
|
|
||||||
<div v-if="open" ref="fly" class="flyout" :class="{ 'part-flyout': open !== 'connectors' }" :style="{ left: `${anchor}px` }" @pointerenter="stay" @pointerleave="leave">
|
|
||||||
<!-- Built-in parts -->
|
|
||||||
<template v-if="group">
|
|
||||||
<p class="flyout-head">{{ group.name }}</p>
|
|
||||||
<div class="strip-wrap">
|
|
||||||
<button v-if="edges.left" class="strip-arrow left" title="Scroll left" @click="page(-1)"><Icon name="lucide:chevron-left" class="size-4" /></button>
|
|
||||||
<div ref="strip" class="part-strip" @wheel="onWheel" @scroll="measure">
|
|
||||||
<div v-for="p in group.parts" :key="p.kind" class="part-slot">
|
|
||||||
<button
|
|
||||||
class="part-tile"
|
|
||||||
:class="{ blocked: !ed.canPlaceKind(p.kind), active: ed.placing.value?.kind === p.kind && !ed.placing.value?.chip }"
|
|
||||||
:title="p.hint"
|
|
||||||
draggable="true"
|
|
||||||
@click="pick(p.kind)"
|
|
||||||
@dragstart="dragStart($event, p.kind)"
|
|
||||||
@dragend="endDrag"
|
|
||||||
>
|
|
||||||
<span class="part-art"><EditorPartThumb :kind="p.kind" /></span>
|
|
||||||
<span class="part-name">{{ p.name }}</span>
|
|
||||||
<kbd v-if="p.key" class="part-key">{{ p.key }}</kbd>
|
|
||||||
<Icon v-if="!ed.canPlaceKind(p.kind)" name="lucide:lock" class="part-lock size-3.5" />
|
|
||||||
</button>
|
|
||||||
<button class="pin-btn" :class="{ on: isPinned(p.kind) }" :title="isPinned(p.kind) ? 'Unpin from the bar' : 'Pin to the bar, to have it at hand'" @click="togglePin(p.kind)">
|
|
||||||
<Icon :name="isPinned(p.kind) ? 'lucide:pin-off' : 'lucide:pin'" class="size-3.5" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div v-for="d in groupComps" :key="d.id" class="part-slot">
|
|
||||||
<button
|
|
||||||
class="part-tile"
|
|
||||||
:class="{ blocked: !placeable(d), active: ed.placing.value?.chip === d.id }"
|
|
||||||
:title="d.id === ed.def.value.id ? 'You are editing this one' : d.description || ''"
|
|
||||||
:draggable="placeable(d)"
|
|
||||||
@click="pick('chip', d.id)"
|
|
||||||
@dragstart="dragStart($event, 'chip', d.id)"
|
|
||||||
@dragend="endDrag"
|
|
||||||
>
|
|
||||||
<span class="part-art"><EditorPartThumb kind="chip" :chip="d.id" /></span>
|
|
||||||
<span class="part-name">{{ d.name }}</span>
|
|
||||||
<span v-if="d.id === ed.def.value.id" class="part-meta">editing</span>
|
|
||||||
<span v-else-if="ed.transistors(d.id)" class="part-meta">{{ shortCount(ed.transistors(d.id)) }} transistors</span>
|
|
||||||
</button>
|
|
||||||
<button class="pin-btn" :class="{ on: isPinned('chip', d) }" :title="isPinned('chip', d) ? 'Unpin from the bar' : 'Pin to the bar'" @click="togglePin('chip', d)">
|
|
||||||
<Icon :name="isPinned('chip', d) ? 'lucide:pin-off' : 'lucide:pin'" class="size-3.5" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<button v-if="edges.right" class="strip-arrow right" title="Scroll right" @click="page(1)"><Icon name="lucide:chevron-right" class="size-4" /></button>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<!-- Connector types -->
|
|
||||||
<template v-else-if="open === 'connectors'">
|
|
||||||
<p class="flyout-head">Connectors</p>
|
|
||||||
<p v-if="!connectors.length" class="flyout-empty">Make a cable type of your own: HDMI, RJ45, a bus. It gets an Out and an In port.</p>
|
|
||||||
<ul class="flyout-list">
|
|
||||||
<li v-for="c in connectors" :key="c.id">
|
|
||||||
<span class="flyout-item static">
|
|
||||||
<span class="conn-swatch" :class="c.color ? `c-${c.color}` : ''" />
|
|
||||||
<span class="grow truncate">{{ c.name }}</span>
|
|
||||||
<span class="flyout-note">{{ c.lines.length }} lines</span>
|
|
||||||
</span>
|
|
||||||
<button
|
|
||||||
v-for="side in ['portout', 'portin'] as const"
|
|
||||||
:key="side"
|
|
||||||
class="btn-sm"
|
|
||||||
:disabled="!portsOk"
|
|
||||||
draggable="true"
|
|
||||||
:title="side === 'portout' ? `Where a ${c.name} cable leaves this circuit` : `Where a ${c.name} cable comes in`"
|
|
||||||
@click="pick(side, undefined, c.id)"
|
|
||||||
@dragstart="dragStart($event, side, undefined, c.id)"
|
|
||||||
@dragend="dragEnd"
|
|
||||||
>
|
|
||||||
{{ side === 'portout' ? 'Out' : 'In' }}
|
|
||||||
</button>
|
|
||||||
<button class="pin-btn" title="Edit its name, colour and lines" @click="ed.editConnector(c.id), (open = null)"><Icon name="lucide:pencil" class="size-3.5" /></button>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
<button class="flyout-new" :disabled="!portsOk" @click="ed.addConnector(), (open = null)"><Icon name="lucide:plus" class="size-4" /> New connector type</button>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<!-- Components, by group -->
|
|
||||||
<template v-else-if="open === 'components'">
|
|
||||||
<div v-if="componentGroups.length > 1 || unused.length" class="part-tabs" role="tablist">
|
|
||||||
<button
|
|
||||||
v-for="g in componentGroups"
|
|
||||||
:key="g.name"
|
|
||||||
role="tab"
|
|
||||||
:aria-selected="compGroup?.name === g.name && compTab !== UNUSED"
|
|
||||||
:class="{ active: compGroup?.name === g.name && compTab !== UNUSED }"
|
|
||||||
@click="compTab = g.name"
|
|
||||||
>
|
|
||||||
{{ g.name }} <span class="count">{{ g.defs.length }}</span>
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
v-if="unused.length"
|
|
||||||
role="tab"
|
|
||||||
class="unused-tab"
|
|
||||||
:aria-selected="compTab === UNUSED"
|
|
||||||
:class="{ active: compTab === UNUSED }"
|
|
||||||
title="Placed in no other circuit: clear out what you no longer need"
|
|
||||||
@click="compTab = UNUSED"
|
|
||||||
>
|
|
||||||
<Icon name="lucide:archive" class="size-3.5" /> Unused <span class="count">{{ unused.length }}</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<p v-else class="flyout-head">{{ compGroup?.name ?? 'Components' }}</p>
|
|
||||||
<div class="strip-wrap">
|
|
||||||
<button v-if="edges.left" class="strip-arrow left" title="Scroll left" @click="page(-1)"><Icon name="lucide:chevron-left" class="size-4" /></button>
|
|
||||||
<div ref="strip" class="part-strip" @wheel="onWheel" @scroll="measure">
|
|
||||||
<div v-for="d in compGroup?.defs ?? []" :key="d.id" class="part-slot">
|
|
||||||
<button
|
|
||||||
class="part-tile"
|
|
||||||
:class="{ blocked: !placeable(d), active: ed.placing.value?.chip === d.id }"
|
|
||||||
:title="d.id === ed.def.value.id ? 'You are editing this one' : d.description || ''"
|
|
||||||
:draggable="placeable(d)"
|
|
||||||
@click="pick('chip', d.id)"
|
|
||||||
@dragstart="dragStart($event, 'chip', d.id)"
|
|
||||||
@dragend="endDrag"
|
|
||||||
>
|
|
||||||
<span class="part-art"><EditorPartThumb kind="chip" :chip="d.id" /></span>
|
|
||||||
<span class="part-name">{{ d.name }}</span>
|
|
||||||
<span v-if="d.id === ed.def.value.id" class="part-meta">editing</span>
|
|
||||||
<span v-else-if="ed.transistors(d.id)" class="part-meta">{{ shortCount(ed.transistors(d.id)) }} transistors</span>
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
v-if="compTab === UNUSED"
|
|
||||||
class="pin-btn drop-btn"
|
|
||||||
:class="{ confirm: confirmDrop === d.id }"
|
|
||||||
:title="confirmDrop === d.id ? 'Click again to delete it' : 'Delete this component'"
|
|
||||||
@click="drop(d)"
|
|
||||||
@pointerleave="confirmDrop === d.id && (confirmDrop = null)"
|
|
||||||
>
|
|
||||||
<Icon name="lucide:trash-2" class="size-3.5" />
|
|
||||||
<span v-if="confirmDrop === d.id">Delete?</span>
|
|
||||||
</button>
|
|
||||||
<button v-else class="pin-btn" :class="{ on: isPinned('chip', d) }" :title="isPinned('chip', d) ? 'Unpin from the bar' : 'Pin to the bar'" @click="togglePin('chip', d)">
|
|
||||||
<Icon :name="isPinned('chip', d) ? 'lucide:pin-off' : 'lucide:pin'" class="size-3.5" />
|
|
||||||
</button>
|
|
||||||
<button v-if="d.id !== ed.def.value.id" class="pin-btn edit" title="Open it and edit inside (or double-click it on the canvas)" @click="ed.open(d.id), (open = null)">
|
|
||||||
<Icon name="lucide:pencil" class="size-3.5" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<button v-if="edges.right" class="strip-arrow right" title="Scroll right" @click="page(1)"><Icon name="lucide:chevron-right" class="size-4" /></button>
|
|
||||||
</div>
|
|
||||||
<div class="flex gap-1">
|
|
||||||
<button class="flyout-new grow" @click="ed.createComponent(), (open = null)"><Icon name="lucide:plus" class="size-4" /> New component</button>
|
|
||||||
<button class="flyout-new" title="NOT, AND, … up to a 4-bit counter, all built from NAND" @click="ed.loadExamples(), (open = null)"><Icon name="lucide:book-open" class="size-4" /> Examples</button>
|
|
||||||
<button class="flyout-new" title="Components everyone published: find one and add it here" @click="(ed.dialog.value = 'library'), (open = null)"><Icon name="lucide:library-big" class="size-4" /> Library</button>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
</Transition>
|
|
||||||
|
|
||||||
<nav class="bottom-bar" aria-label="Parts" @pointerleave="leave">
|
|
||||||
<div class="bb-group pinned" @wheel="sideways">
|
|
||||||
<button
|
|
||||||
v-for="p in shown"
|
|
||||||
:key="p.pin"
|
|
||||||
class="bar-btn pinned-part"
|
|
||||||
:class="{ blocked: p.missing, active: ed.placing.value?.kind === p.kind && ed.placing.value?.chip === p.chip }"
|
|
||||||
:title="`${p.name}${p.key ? ` (${p.key})` : ''}: click to place, drag onto the canvas. Right-click to unpin`"
|
|
||||||
:draggable="!p.missing"
|
|
||||||
@pointerenter="leave"
|
|
||||||
@click="pick(p.kind, p.chip)"
|
|
||||||
@contextmenu.prevent="unpin(p.pin)"
|
|
||||||
@dragstart="dragStart($event, p.kind, p.chip)"
|
|
||||||
@dragend="dragEnd"
|
|
||||||
>
|
|
||||||
<!-- Gates and components by name, the rest (switch, lamp, clock) by icon. -->
|
|
||||||
<Icon v-if="!named(p)" :name="p.icon" class="size-[18px]" />
|
|
||||||
<span v-else>{{ p.name }}</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div class="bb-group">
|
|
||||||
<button
|
|
||||||
v-for="c in cats"
|
|
||||||
:key="c.id"
|
|
||||||
class="bar-btn"
|
|
||||||
:class="{ open: open === c.id, active: activeCat === c.id }"
|
|
||||||
:title="c.label"
|
|
||||||
@pointerenter="show(c.id, $event)"
|
|
||||||
@click="toggle(c.id, $event)"
|
|
||||||
>
|
|
||||||
<Icon :name="c.icon" class="size-[18px]" />
|
|
||||||
<span class="bar-label">{{ c.label }}</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div class="bb-group end">
|
|
||||||
<button class="bar-btn" title="Find a part, a circuit to open or an action (Space or /)" @click="ed.partSearch.value++">
|
|
||||||
<Icon name="lucide:search" class="size-[18px]" />
|
|
||||||
<kbd class="bar-label">Space</kbd>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</nav>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
@ -243,13 +243,6 @@ function pack() {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-if="only('pixel')" class="field">
|
|
||||||
<span>Colours, for all</span>
|
|
||||||
<div class="seg">
|
|
||||||
<button @click="ed.setRgb(ids, false)">One</button>
|
|
||||||
<button @click="ed.setRgb(ids, true)">RGB</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<label v-if="only('pixel')" class="field" title="Pixels with the same screen name make one screen on the component's box">
|
<label v-if="only('pixel')" class="field" title="Pixels with the same screen name make one screen on the component's box">
|
||||||
<span>Screen on the box, for all</span>
|
<span>Screen on the box, for all</span>
|
||||||
<input
|
<input
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,98 +0,0 @@
|
||||||
<script setup lang="ts">
|
|
||||||
// Challenges, puzzles and the puzzle of the week, opened from the top bar.
|
|
||||||
// Starting one opens its circuit; This on the left then shows what to build.
|
|
||||||
import { CHALLENGES } from '~/lib/logic/challenges'
|
|
||||||
import { campaignProgress, challengeName, challengeOpen, isCampaign, NEEDS } from '~/lib/logic/progress'
|
|
||||||
import { weekKey, weeklyId } from '~/lib/logic/puzzles'
|
|
||||||
|
|
||||||
const ed = useEditor()
|
|
||||||
const emit = defineEmits<{ close: [] }>()
|
|
||||||
|
|
||||||
const solved = computed(() => new Set(ed.project.value.solved))
|
|
||||||
const best = computed(() => ed.project.value.best ?? {})
|
|
||||||
const solvedCount = computed(() => CHALLENGES.filter(c => solved.value.has(c.id)).length)
|
|
||||||
const campaign = computed(() => isCampaign(ed.project.value))
|
|
||||||
const progress = computed(() => campaignProgress(ed.project.value))
|
|
||||||
const open = (id: string) => challengeOpen(ed.project.value, id)
|
|
||||||
const needsText = (id: string) => `Solve ${(NEEDS[id] ?? []).filter(n => !solved.value.has(n)).map(challengeName).join(' and ')} first`
|
|
||||||
const puzzles = computed(() => (ed.project.value.puzzles ?? []).filter(p => !p.id.startsWith('week:') || p.id === weeklyId(weekKey())))
|
|
||||||
const weeklyStarted = computed(() => ed.project.value.components.some(d => d.challenge === weeklyId(weekKey())))
|
|
||||||
const started = computed(() => new Map(ed.project.value.components.filter(d => d.challenge).map(d => [d.challenge!, d])))
|
|
||||||
|
|
||||||
function openWeekly() {
|
|
||||||
const spec = ed.project.value.puzzles?.find(p => p.id === weeklyId(weekKey()))
|
|
||||||
if (spec) ed.beginPuzzle(spec)
|
|
||||||
else void ed.openPuzzle('weekly')
|
|
||||||
emit('close')
|
|
||||||
}
|
|
||||||
|
|
||||||
defineExpose({ solvedCount })
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div class="challenges-panel" @click="($event.target as HTMLElement).closest('.btn-sm:not(:disabled)') && emit('close')">
|
|
||||||
<div v-if="campaign" class="campaign">
|
|
||||||
<div class="flex items-center justify-between">
|
|
||||||
<span class="font-semibold">Campaign</span>
|
|
||||||
<span class="tabular-nums text-(--muted)">{{ solvedCount }} / {{ CHALLENGES.length }}</span>
|
|
||||||
</div>
|
|
||||||
<div class="bar"><span :style="{ width: `${progress * 100}%` }" /></div>
|
|
||||||
<p>Every part you solve becomes yours to use. New parts and challenges open as you go.</p>
|
|
||||||
</div>
|
|
||||||
<p v-else class="intro">
|
|
||||||
Build each part from NAND and the parts you already made. Start a challenge, wire it up, then press
|
|
||||||
<strong>Check</strong> under This, on the left.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div class="weekly">
|
|
||||||
<div class="flex items-center gap-2">
|
|
||||||
<Icon name="lucide:calendar-days" class="size-4 shrink-0 text-(--accent)" />
|
|
||||||
<span class="grow font-medium">Puzzle of the week</span>
|
|
||||||
<button class="btn-sm" @click="openWeekly">{{ weeklyStarted ? 'Open' : 'Play' }}</button>
|
|
||||||
</div>
|
|
||||||
<p>A new logic puzzle every Monday, the same for everyone. Fewest transistors wins.</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<template v-if="puzzles.length">
|
|
||||||
<h3>Puzzles</h3>
|
|
||||||
<ul class="challenges">
|
|
||||||
<li v-for="p in puzzles" :key="p.id" :class="{ solved: solved.has(p.id) }">
|
|
||||||
<div class="flex items-center gap-2">
|
|
||||||
<Icon :name="solved.has(p.id) ? 'lucide:circle-check' : 'lucide:puzzle'" class="size-4 shrink-0" :class="solved.has(p.id) ? 'text-(--on)' : 'text-(--muted)'" />
|
|
||||||
<span class="grow font-medium">{{ p.name }}</span>
|
|
||||||
<button class="btn-sm" @click="ed.beginPuzzle(p)">Open</button>
|
|
||||||
</div>
|
|
||||||
<p class="pins">
|
|
||||||
{{ p.inputs.join(', ') }} → {{ p.outputs.join(', ') }}
|
|
||||||
<span v-if="best[p.id] !== undefined" class="best"> · best {{ best[p.id]!.toLocaleString() }} transistors</span>
|
|
||||||
</p>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<h3>Challenges</h3>
|
|
||||||
<ul class="challenges">
|
|
||||||
<li v-for="c in CHALLENGES" :key="c.id" :class="{ solved: solved.has(c.id), locked: !open(c.id) }">
|
|
||||||
<div class="flex items-center gap-2">
|
|
||||||
<Icon
|
|
||||||
:name="solved.has(c.id) ? 'lucide:circle-check' : open(c.id) ? 'lucide:circle' : 'lucide:lock'"
|
|
||||||
class="size-4 shrink-0"
|
|
||||||
:class="solved.has(c.id) ? 'text-(--on)' : 'text-(--muted)'"
|
|
||||||
/>
|
|
||||||
<span class="grow font-medium">{{ c.name }}</span>
|
|
||||||
<button class="btn-sm" :disabled="!open(c.id) && !started.has(c.id)" :title="open(c.id) ? '' : needsText(c.id)" @click="ed.beginChallenge(c)">
|
|
||||||
{{ started.has(c.id) ? 'Open' : 'Start' }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<p v-if="!open(c.id)" class="needs">{{ needsText(c.id) }}</p>
|
|
||||||
<p>{{ c.goal }}</p>
|
|
||||||
<p class="pins">
|
|
||||||
{{ c.inputs.join(', ') }} → {{ c.outputs.join(', ') }}
|
|
||||||
<span v-if="best[c.id] !== undefined" class="best" title="Fewest transistors in a passing solution so far">
|
|
||||||
· best {{ best[c.id]!.toLocaleString() }} transistors
|
|
||||||
</span>
|
|
||||||
</p>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
@ -1,13 +1,8 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
// "This": what the circuit you are in is. Its name, where it came from (the
|
|
||||||
// library, with a newer version to get) and health on top, four numbers
|
|
||||||
// (the transistors open their breakdown), its truth table and how it
|
|
||||||
// looks as a part. Things to do with it are in the menu on its name in the
|
|
||||||
// top bar; unused components are with the components in the parts bar.
|
|
||||||
import { TRANSISTORS_PER_NAND } from '~/lib/logic/analyze'
|
import { TRANSISTORS_PER_NAND } from '~/lib/logic/analyze'
|
||||||
import { transistorBreakdown } from '~/lib/logic/bulk'
|
import { transistorBreakdown } from '~/lib/logic/bulk'
|
||||||
import { chipPins } from '~/lib/logic/geometry'
|
import { chipPins } from '~/lib/logic/geometry'
|
||||||
import { importProblem } from '~/lib/logic/library'
|
import { unusedComponents } from '~/lib/logic/check'
|
||||||
import { usages } from '~/lib/logic/ops'
|
import { usages } from '~/lib/logic/ops'
|
||||||
import type { SymbolKind } from '~/lib/logic/types'
|
import type { SymbolKind } from '~/lib/logic/types'
|
||||||
|
|
||||||
|
|
@ -43,27 +38,7 @@ const groupNames = computed(() => [...new Set(ed.project.value.components.map(d
|
||||||
const hasFace = computed(() => def.value.nodes.some(n => n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel'))
|
const hasFace = computed(() => def.value.nodes.some(n => n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel'))
|
||||||
const total = computed(() => ed.transistors(def.value.id))
|
const total = computed(() => ed.transistors(def.value.id))
|
||||||
const breakdown = computed(() => transistorBreakdown(def.value, ed.nands.value, ed.getDef.value))
|
const breakdown = computed(() => transistorBreakdown(def.value, ed.nands.value, ed.getDef.value))
|
||||||
|
const showBreakdown = ref(true)
|
||||||
// ── From the library ────────────────────────────────────────────────
|
|
||||||
/** Where it came from, when it is in the library. */
|
|
||||||
const origin = computed(() => {
|
|
||||||
const f = def.value.from
|
|
||||||
if (ed.ownEntry(def.value)) return f ? `In the library as version ${f.version}, published from here` : 'In the library, published from here'
|
|
||||||
if (!f) return ''
|
|
||||||
return f.inside ? `Came along with a component from the library by ${f.author || 'Anonymous'}` : `From the library by ${f.author || 'Anonymous'}, version ${f.version}`
|
|
||||||
})
|
|
||||||
/** A newer version of it in the library, to update to (not in a campaign, which takes nothing from the library). */
|
|
||||||
const newer = ref<number | null>(null)
|
|
||||||
watch(
|
|
||||||
() => [def.value.id, def.value.from] as const,
|
|
||||||
async ([id, f]) => {
|
|
||||||
newer.value = null
|
|
||||||
if (!f || f.inside || ed.ownEntry(def.value) || importProblem(ed.project.value)) return
|
|
||||||
const v = await ed.libraryVersion(f.id)
|
|
||||||
if (def.value.id === id && v !== null && v > f.version) newer.value = v
|
|
||||||
},
|
|
||||||
{ immediate: true },
|
|
||||||
)
|
|
||||||
|
|
||||||
function toggleFace(e: Event) {
|
function toggleFace(e: Event) {
|
||||||
def.value.face = (e.target as HTMLInputElement).checked
|
def.value.face = (e.target as HTMLInputElement).checked
|
||||||
|
|
@ -73,48 +48,22 @@ function toggleFace(e: Event) {
|
||||||
// ── Problems ────────────────────────────────────────────────────────
|
// ── Problems ────────────────────────────────────────────────────────
|
||||||
const LEVEL_ICON = { error: 'lucide:circle-x', warn: 'lucide:triangle-alert', info: 'lucide:info' } as const
|
const LEVEL_ICON = { error: 'lucide:circle-x', warn: 'lucide:triangle-alert', info: 'lucide:info' } as const
|
||||||
const showInfo = ref(false)
|
const showInfo = ref(false)
|
||||||
const problems = computed(() => ed.issues.value.filter(i => i.level !== 'info'))
|
|
||||||
const worst = computed<'error' | 'warn' | 'ok'>(() => (problems.value.some(i => i.level === 'error') ? 'error' : problems.value.length ? 'warn' : 'ok'))
|
|
||||||
const shownIssues = computed(() => ed.issues.value.filter(i => showInfo.value || i.level !== 'info'))
|
const shownIssues = computed(() => ed.issues.value.filter(i => showInfo.value || i.level !== 'info'))
|
||||||
const infoCount = computed(() => ed.issues.value.filter(i => i.level === 'info').length)
|
const infoCount = computed(() => ed.issues.value.filter(i => i.level === 'info').length)
|
||||||
/** The transistors tile shows where they are. */
|
const unused = computed(() => unusedComponents(ed.project.value).filter(d => d.id !== def.value.id))
|
||||||
const showCost = ref(false)
|
const showUnused = ref(false)
|
||||||
|
const confirmRemove = ref<string | null>(null)
|
||||||
|
|
||||||
|
const confirmDelete = ref(false)
|
||||||
|
watch(() => def.value.id, () => (confirmDelete.value = false))
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<section class="this-head">
|
<section class="problems">
|
||||||
<input
|
<div class="problems-head">
|
||||||
ref="nameInput"
|
<h3>Check</h3>
|
||||||
v-model="def.name"
|
<span v-if="!shownIssues.length" class="ok"><Icon name="lucide:circle-check" class="size-4" /> {{ infoCount ? 'No problems' : 'All good' }}</span>
|
||||||
class="title-input"
|
<label v-if="infoCount" class="check ml-auto"><input v-model="showInfo" type="checkbox" /> Notes ({{ infoCount }})</label>
|
||||||
title="Rename this circuit"
|
|
||||||
spellcheck="false"
|
|
||||||
@change="ed.commit(false)"
|
|
||||||
@keydown.enter="($event.target as HTMLInputElement).blur()"
|
|
||||||
/>
|
|
||||||
<p class="this-sub">
|
|
||||||
<template v-if="users.length">
|
|
||||||
Used in
|
|
||||||
<template v-for="(u, i) in users" :key="u.id">
|
|
||||||
<a href="#" @click.prevent="ed.open(u.id)">{{ u.name }}</a><template v-if="i < users.length - 1">, </template>
|
|
||||||
</template>
|
|
||||||
</template>
|
|
||||||
<template v-else>{{ def.id === ed.mainId.value ? 'The main circuit' : 'Not used in another circuit' }}</template>
|
|
||||||
</p>
|
|
||||||
<p v-if="origin" class="lib-origin">
|
|
||||||
<Icon name="lucide:library-big" class="size-3.5 shrink-0" />
|
|
||||||
<span class="grow">{{ origin }}</span>
|
|
||||||
<button v-if="newer" class="btn-sm" title="Replace it here with the newer version, wherever it is used (Ctrl+Z goes back)" @click="ed.updateFromLibrary(def.id)">
|
|
||||||
Get version {{ newer }}
|
|
||||||
</button>
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div class="health" :class="worst">
|
|
||||||
<Icon :name="worst === 'ok' ? 'lucide:circle-check' : LEVEL_ICON[worst]" class="size-4 shrink-0" />
|
|
||||||
<span class="grow">{{ worst === 'ok' ? 'All good' : `${problems.length} ${problems.length === 1 ? 'problem' : 'problems'}` }}</span>
|
|
||||||
<label v-if="infoCount" class="health-notes" title="Show notes too: things that work but may not be meant">
|
|
||||||
<input v-model="showInfo" type="checkbox" /> {{ infoCount }} {{ infoCount === 1 ? 'note' : 'notes' }}
|
|
||||||
</label>
|
|
||||||
</div>
|
</div>
|
||||||
<ul v-if="shownIssues.length" class="issue-list">
|
<ul v-if="shownIssues.length" class="issue-list">
|
||||||
<li v-for="(i, k) in shownIssues.slice(0, 40)" :key="k">
|
<li v-for="(i, k) in shownIssues.slice(0, 40)" :key="k">
|
||||||
|
|
@ -125,61 +74,38 @@ const showCost = ref(false)
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
<p v-if="shownIssues.length > 40" class="hint">and {{ shownIssues.length - 40 }} more</p>
|
<p v-if="shownIssues.length > 40" class="hint">and {{ shownIssues.length - 40 }} more</p>
|
||||||
<p v-for="err in ed.errors.value" :key="err" class="result fail">
|
<template v-if="unused.length">
|
||||||
<Icon name="lucide:triangle-alert" class="size-4 shrink-0" /> {{ err }}
|
<button class="section-toggle mt-2" @click="showUnused = !showUnused">
|
||||||
</p>
|
<Icon :name="showUnused ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-4" />
|
||||||
|
Not used in another circuit ({{ unused.length }})
|
||||||
<div class="tiles">
|
|
||||||
<button class="tile" title="List and rename them" @click="ed.panelTab.value = 'pins'">
|
|
||||||
<span class="tile-label">Inputs</span>
|
|
||||||
<span class="tile-value">{{ pins.inputs.length }}</span>
|
|
||||||
</button>
|
</button>
|
||||||
<button class="tile" title="List and rename them" @click="ed.panelTab.value = 'pins'">
|
<template v-if="showUnused">
|
||||||
<span class="tile-label">Outputs</span>
|
<p class="hint">Circuits you work in directly show up here too. Delete only what you don't need.</p>
|
||||||
<span class="tile-value">{{ pins.outputs.length }}</span>
|
<ul class="issue-list">
|
||||||
</button>
|
<li v-for="d in unused" :key="d.id" class="unused-row">
|
||||||
<button class="tile" :class="{ active: showCost }" :aria-expanded="showCost" title="CMOS: 4 per NAND gate, at every depth. Click for where they are" @click="showCost = !showCost">
|
<a href="#" class="grow truncate" @click.prevent="ed.open(d.id)">{{ d.name }}</a>
|
||||||
<span class="tile-label">Transistors</span>
|
<template v-if="confirmRemove === d.id">
|
||||||
<span class="tile-value">{{ total.toLocaleString() }}</span>
|
<button class="btn-sm danger" @click="ed.removeComponent(d.id), (confirmRemove = null)">Delete</button>
|
||||||
<span class="tile-note">{{ ed.circuitStats.value.nands.toLocaleString() }} NAND</span>
|
<button class="btn-sm" @click="confirmRemove = null">Keep</button>
|
||||||
</button>
|
</template>
|
||||||
<div class="tile" :title="ed.circuitStats.value.sequential ? 'It has feedback loops, so it can hold state' : 'Longest path from an input to an output'">
|
<button v-else class="icon-btn" title="Delete this component" @click="confirmRemove = d.id"><Icon name="lucide:trash-2" class="size-3.5" /></button>
|
||||||
<span class="tile-label">{{ ed.circuitStats.value.sequential ? 'Memory' : 'Delay' }}</span>
|
|
||||||
<span class="tile-value">{{ ed.circuitStats.value.sequential ? 'Yes' : ed.circuitStats.value.delay }}</span>
|
|
||||||
<span class="tile-note">{{ ed.circuitStats.value.sequential ? 'feedback loops' : 'gates deep' }}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<template v-if="showCost">
|
|
||||||
<p v-if="!breakdown.length" class="hint mt-2">No gates here yet. Switches, lamps, displays and cables need no transistors.</p>
|
|
||||||
<ul v-else class="cost-list mt-2">
|
|
||||||
<li v-for="l in breakdown" :key="l.key" title="Select these parts" @click="ed.selectOnly(l.ids)">
|
|
||||||
<span class="cost-name">
|
|
||||||
<span class="truncate">{{ l.name }}</span>
|
|
||||||
<span class="cost-each">{{ l.count }} × {{ l.each.toLocaleString() }}</span>
|
|
||||||
</span>
|
|
||||||
<span class="cost-total">{{ l.total.toLocaleString() }}</span>
|
|
||||||
</li>
|
|
||||||
<li class="cost-sum">
|
|
||||||
<span class="cost-name">
|
|
||||||
<span>Total</span>
|
|
||||||
<span class="cost-each">{{ (total / TRANSISTORS_PER_NAND).toLocaleString() }} NAND × 4</span>
|
|
||||||
</span>
|
|
||||||
<span class="cost-total">{{ total.toLocaleString() }}</span>
|
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</template>
|
</template>
|
||||||
|
</template>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="folds">
|
<section>
|
||||||
<EditorFold id="circuit-table" title="Truth table">
|
<h3>This circuit</h3>
|
||||||
<EditorTestPane part="table" />
|
<label class="field">
|
||||||
</EditorFold>
|
<span>Name</span>
|
||||||
|
<input ref="nameInput" v-model="def.name" @change="ed.commit(false)" @keydown.enter="($event.target as HTMLInputElement).blur()" />
|
||||||
<EditorFold id="circuit-component" title="As a component" :note="def.group || ''">
|
</label>
|
||||||
<label class="field">
|
<label class="field">
|
||||||
<span>Description</span>
|
<span>Description</span>
|
||||||
<textarea v-model="def.description" rows="2" placeholder="What does it do?" @change="ed.commit(false)" />
|
<textarea v-model="def.description" rows="2" placeholder="What does it do?" @change="ed.commit(false)" />
|
||||||
</label>
|
</label>
|
||||||
|
<div class="grid grid-cols-2 gap-2">
|
||||||
<label class="field">
|
<label class="field">
|
||||||
<span>Drawn as</span>
|
<span>Drawn as</span>
|
||||||
<select v-model="def.symbol" @change="ed.commit(false)">
|
<select v-model="def.symbol" @change="ed.commit(false)">
|
||||||
|
|
@ -187,19 +113,111 @@ const showCost = ref(false)
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<label class="field">
|
<label class="field">
|
||||||
<span>Group in the parts list</span>
|
<span>Group</span>
|
||||||
<input v-model="def.group" list="groups" placeholder="My components" @change="ed.commit(false)" />
|
<input v-model="def.group" list="groups" placeholder="My components" @change="ed.commit(false)" />
|
||||||
<datalist id="groups">
|
<datalist id="groups">
|
||||||
<option v-for="g in groupNames" :key="g" :value="g" />
|
<option v-for="g in groupNames" :key="g" :value="g" />
|
||||||
</datalist>
|
</datalist>
|
||||||
</label>
|
</label>
|
||||||
<label v-if="hasFace" class="check mb-3">
|
</div>
|
||||||
|
<label v-if="hasFace" class="check">
|
||||||
<input type="checkbox" :checked="def.face !== false" @change="toggleFace" />
|
<input type="checkbox" :checked="def.face !== false" @change="toggleFace" />
|
||||||
Show its lamps and displays on the box
|
Show its lamps and displays on the component box
|
||||||
</label>
|
</label>
|
||||||
<button class="btn w-full" :title="`How it looks when placed: ${def.design ? 'drawn by hand' : 'laid out automatically'}`" @click="ed.designFace(def.id)">
|
<dl class="stats">
|
||||||
|
<dt>Pins</dt>
|
||||||
|
<dd>
|
||||||
|
<a href="#" title="List and rename them" @click.prevent="ed.rightTab.value = 'pins'">{{ pins.inputs.length }} in, {{ pins.outputs.length }} out</a>
|
||||||
|
</dd>
|
||||||
|
<dt>NAND gates</dt>
|
||||||
|
<dd>{{ ed.circuitStats.value.nands.toLocaleString() }}</dd>
|
||||||
|
<dt>Transistors</dt>
|
||||||
|
<dd>{{ total.toLocaleString() }}</dd>
|
||||||
|
<dt>{{ ed.circuitStats.value.sequential ? 'Memory' : 'Delay' }}</dt>
|
||||||
|
<dd>{{ ed.circuitStats.value.sequential ? 'yes (feedback loops)' : `${ed.circuitStats.value.delay} gates` }}</dd>
|
||||||
|
</dl>
|
||||||
|
<p v-for="err in ed.errors.value" :key="err" class="result fail">
|
||||||
|
<Icon name="lucide:triangle-alert" class="size-4 shrink-0" /> {{ err }}
|
||||||
|
</p>
|
||||||
|
<p v-if="users.length" class="hint">
|
||||||
|
Used in
|
||||||
|
<template v-for="(u, i) in users" :key="u.id">
|
||||||
|
<a href="#" @click.prevent="ed.open(u.id)">{{ u.name }}</a><template v-if="i < users.length - 1">, </template>
|
||||||
|
</template>
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h3>Its box</h3>
|
||||||
|
<p class="hint">How it looks when placed: {{ def.design ? 'drawn by hand' : 'laid out automatically' }}.</p>
|
||||||
|
<button class="btn w-full" title="Move lamps, displays and the name, draw lines, boxes and text, size the box" @click="ed.designFace(def.id)">
|
||||||
<Icon name="lucide:pen-tool" class="size-4" /> Design the box
|
<Icon name="lucide:pen-tool" class="size-4" /> Design the box
|
||||||
</button>
|
</button>
|
||||||
</EditorFold>
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h3>Sheet</h3>
|
||||||
|
<p class="hint">The circuit as a wiring sheet with a title block: print it, save it as PDF, or keep it as an SVG.</p>
|
||||||
|
<div class="grid grid-cols-2 gap-2">
|
||||||
|
<button class="btn" :disabled="!def.nodes.length" title="On white paper (Ctrl+P); choose Save as PDF in the print dialog" @click="ed.exportSheet('print')">
|
||||||
|
<Icon name="lucide:printer" class="size-4" /> Print / PDF
|
||||||
|
</button>
|
||||||
|
<button class="btn" :disabled="!def.nodes.length" title="As on screen, to open in a browser or drawing program" @click="ed.exportSheet('svg')">
|
||||||
|
<Icon name="lucide:file-image" class="size-4" /> SVG file
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<button class="section-toggle" @click="showBreakdown = !showBreakdown">
|
||||||
|
<Icon :name="showBreakdown ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-4" />
|
||||||
|
Where the transistors are
|
||||||
|
</button>
|
||||||
|
<template v-if="showBreakdown">
|
||||||
|
<p v-if="!breakdown.length" class="hint mt-2">No gates here yet. Switches, lamps, displays and cables need no transistors.</p>
|
||||||
|
<table v-else class="cost">
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="l in breakdown" :key="l.key" title="Select these parts" @click="ed.selectOnly(l.ids)">
|
||||||
|
<td class="what">{{ l.count }} × {{ l.name }}</td>
|
||||||
|
<td class="num">{{ l.each.toLocaleString() }} each</td>
|
||||||
|
<td class="num strong">{{ l.total.toLocaleString() }}</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
<tfoot>
|
||||||
|
<tr>
|
||||||
|
<td>Total</td>
|
||||||
|
<td class="num">{{ (total / TRANSISTORS_PER_NAND).toLocaleString() }} NAND</td>
|
||||||
|
<td class="num strong">{{ total.toLocaleString() }}</td>
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
</table>
|
||||||
|
<p class="hint mt-2">
|
||||||
|
Everything here is built from NAND gates, and a CMOS NAND gate has 4 transistors: 2 in parallel to the supply, 2 in series to
|
||||||
|
ground. So the count is 4 per NAND inside, at every depth: a NOT costs 4, an AND 8, a full adder 60. (A NOT made directly in
|
||||||
|
CMOS would need only 2; here it is built from a NAND.)
|
||||||
|
</p>
|
||||||
|
</template>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<div class="grid gap-2">
|
||||||
|
<button class="btn w-full" title="Remove hand-placed bends in this circuit and lay out every wire tidily (undo brings them back)" @click="ed.tidyAll()">
|
||||||
|
<Icon name="lucide:wand-sparkles" class="size-4" /> Tidy all wires
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
v-if="!ed.task.value"
|
||||||
|
class="btn w-full"
|
||||||
|
title="Turn this circuit into a puzzle link: others build the same behaviour, your circuit stays private"
|
||||||
|
@click="ed.dialog.value = 'publish'"
|
||||||
|
>
|
||||||
|
<Icon name="lucide:puzzle" class="size-4" /> Publish as puzzle
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="actions">
|
||||||
|
<button class="btn btn-ghost" @click="ed.copyComponent(def.id)"><Icon name="lucide:copy" class="size-4" /> Duplicate</button>
|
||||||
|
<button v-if="!confirmDelete" class="btn btn-ghost" @click="confirmDelete = true"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
|
||||||
|
<button v-else class="btn btn-danger" @click="ed.removeComponent(def.id); confirmDelete = false">Really delete?</button>
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
|
|
|
||||||
|
|
@ -1,147 +0,0 @@
|
||||||
<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()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Tab in the last line's name, once it is filled in, adds a line and goes on to it. */
|
|
||||||
function lineTab(i: number, e: KeyboardEvent) {
|
|
||||||
const lines = type.value?.lines
|
|
||||||
if (e.shiftKey || !lines || i !== lines.length - 1 || !(e.target as HTMLInputElement).value.trim()) return
|
|
||||||
e.preventDefault()
|
|
||||||
setLine(i, e)
|
|
||||||
addLine()
|
|
||||||
}
|
|
||||||
|
|
||||||
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.tab="lineTab(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>
|
|
||||||
|
|
@ -1,144 +0,0 @@
|
||||||
<script setup lang="ts">
|
|
||||||
// The converter: write text, hex, binary, decimal, octal or Base64 and read
|
|
||||||
// it in every other form at once, byte by byte (or word by word) below.
|
|
||||||
import {
|
|
||||||
charLabel,
|
|
||||||
ENCODING_NAMES,
|
|
||||||
ENCODINGS,
|
|
||||||
FORMAT_NAMES,
|
|
||||||
FORMATS,
|
|
||||||
formatAs,
|
|
||||||
parseAs,
|
|
||||||
signed,
|
|
||||||
toWords,
|
|
||||||
type ConvertOptions,
|
|
||||||
type Format,
|
|
||||||
type WordBits,
|
|
||||||
} from '~/lib/convert'
|
|
||||||
|
|
||||||
const ed = useEditor()
|
|
||||||
const close = () => (ed.dialog.value = null)
|
|
||||||
|
|
||||||
const KEY = 'logigate:convert'
|
|
||||||
function load(): { input: string; from: Format; opts: ConvertOptions } {
|
|
||||||
try {
|
|
||||||
const s = JSON.parse(localStorage.getItem(KEY) ?? '')
|
|
||||||
if (s && typeof s.input === 'string' && FORMATS.includes(s.from)) return s
|
|
||||||
} catch {}
|
|
||||||
return { input: 'Hello!', from: 'text', opts: { enc: 'utf8', word: 8, endian: 'big' } }
|
|
||||||
}
|
|
||||||
const start = load()
|
|
||||||
const input = ref(start.input)
|
|
||||||
const from = ref<Format>(start.from)
|
|
||||||
const opts = reactive<ConvertOptions>({ ...start.opts })
|
|
||||||
watch([input, from, opts], () => {
|
|
||||||
try {
|
|
||||||
localStorage.setItem(KEY, JSON.stringify({ input: input.value, from: from.value, opts }))
|
|
||||||
} catch {}
|
|
||||||
})
|
|
||||||
|
|
||||||
const bytes = computed(() => parseAs(input.value, from.value, opts))
|
|
||||||
const outputs = computed(() =>
|
|
||||||
FORMATS.filter(f => f !== from.value).map(f => {
|
|
||||||
const b = bytes.value
|
|
||||||
return { f, res: b.ok ? formatAs(b.value, f, opts) : null }
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
const words = computed(() => (bytes.value.ok ? toWords(bytes.value.value, opts) : []))
|
|
||||||
const ROWS = 256
|
|
||||||
/** A word as a character, where a word is one character of the encoding (a UTF-8 byte above 7F is only part of one). */
|
|
||||||
const charOf = (v: number) => {
|
|
||||||
const { enc, word, endian } = opts
|
|
||||||
if (word === 8 && (enc === 'ascii' || enc === 'latin1' || (enc === 'utf8' && v < 0x80))) return charLabel(v)
|
|
||||||
if (word === 16 && (enc === 'utf16le' ? endian === 'little' : enc === 'utf16be' && endian === 'big')) return charLabel(v)
|
|
||||||
if (word === 32 && enc === 'utf32be' && endian === 'big') return charLabel(v)
|
|
||||||
return '·'
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Takes an output as the new input. */
|
|
||||||
function use(f: Format, text: string) {
|
|
||||||
from.value = f
|
|
||||||
input.value = text
|
|
||||||
}
|
|
||||||
const WORDS: WordBits[] = [8, 16, 32]
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div class="modal-backdrop" @click.self="close">
|
|
||||||
<div class="modal convert" role="dialog" aria-labelledby="convert-title">
|
|
||||||
<div class="flex items-start justify-between gap-4">
|
|
||||||
<h2 id="convert-title">Converter</h2>
|
|
||||||
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
|
|
||||||
</div>
|
|
||||||
<p class="hint">Write in one form, read it in all others. Hex and binary take 0x and 0b, spaces and commas, or one long run of digits.</p>
|
|
||||||
|
|
||||||
<div class="convert-opts">
|
|
||||||
<label>
|
|
||||||
<span>Text encoding</span>
|
|
||||||
<select v-model="opts.enc" class="tb-select">
|
|
||||||
<option v-for="e in ENCODINGS" :key="e" :value="e">{{ ENCODING_NAMES[e] }}</option>
|
|
||||||
</select>
|
|
||||||
</label>
|
|
||||||
<label>
|
|
||||||
<span>Word</span>
|
|
||||||
<div class="seg">
|
|
||||||
<button v-for="w in WORDS" :key="w" :class="{ active: opts.word === w }" @click="opts.word = w">{{ w }} bits</button>
|
|
||||||
</div>
|
|
||||||
</label>
|
|
||||||
<label v-if="opts.word > 8">
|
|
||||||
<span>Byte order</span>
|
|
||||||
<div class="seg">
|
|
||||||
<button :class="{ active: opts.endian === 'big' }" title="Highest byte first" @click="opts.endian = 'big'">Big-endian</button>
|
|
||||||
<button :class="{ active: opts.endian === 'little' }" title="Lowest byte first" @click="opts.endian = 'little'">Little-endian</button>
|
|
||||||
</div>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="convert-in">
|
|
||||||
<div class="seg">
|
|
||||||
<button v-for="f in FORMATS" :key="f" :class="{ active: from === f }" @click="from = f">{{ FORMAT_NAMES[f] }}</button>
|
|
||||||
</div>
|
|
||||||
<textarea v-model="input" class="field-input convert-text" rows="3" spellcheck="false" :placeholder="`${FORMAT_NAMES[from]} here`" />
|
|
||||||
<p v-if="!bytes.ok" class="convert-error">{{ bytes.error }}</p>
|
|
||||||
<p v-else class="hint">{{ bytes.value.length }} bytes · {{ words.length }} {{ opts.word }}-bit words</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="convert-outs">
|
|
||||||
<div v-for="o in outputs" :key="o.f" class="convert-out">
|
|
||||||
<div class="convert-out-head">
|
|
||||||
<span>{{ FORMAT_NAMES[o.f] }}</span>
|
|
||||||
<span v-if="o.res?.ok && o.res.note" class="hint">{{ o.res.note }}</span>
|
|
||||||
<span class="grow" />
|
|
||||||
<template v-if="o.res?.ok">
|
|
||||||
<button class="icon-btn" title="Copy" @click="ed.copyText(o.res.value, `${FORMAT_NAMES[o.f]} copied`)"><Icon name="lucide:copy" class="size-3.5" /></button>
|
|
||||||
<button class="icon-btn" title="Write in this form from here on" @click="use(o.f, o.res.value)"><Icon name="lucide:arrow-up" class="size-3.5" /></button>
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
<pre class="convert-value">{{ o.res ? (o.res.ok ? o.res.value : o.res.error) : '' }}</pre>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<template v-if="words.length">
|
|
||||||
<h3>Word by word</h3>
|
|
||||||
<div class="convert-table-wrap">
|
|
||||||
<table class="convert-table tabular-nums">
|
|
||||||
<thead>
|
|
||||||
<tr><th>#</th><th>Hex</th><th>Binary</th><th>Decimal</th><th>Signed</th><th>Character</th></tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
<tr v-for="(v, i) in words.slice(0, ROWS)" :key="i">
|
|
||||||
<td>{{ i }}</td>
|
|
||||||
<td>{{ v.toString(16).toUpperCase().padStart(opts.word / 4, '0') }}</td>
|
|
||||||
<td>{{ v.toString(2).padStart(opts.word, '0') }}</td>
|
|
||||||
<td>{{ v }}</td>
|
|
||||||
<td>{{ signed(v, opts.word) }}</td>
|
|
||||||
<td>{{ charOf(v) }}</td>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
<p v-if="words.length > ROWS" class="hint">and {{ words.length - ROWS }} more</p>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
@ -3,7 +3,7 @@ import { wirePath } from '~/lib/draw'
|
||||||
import type { CrossingStyle } from '~/lib/logic/types'
|
import type { CrossingStyle } from '~/lib/logic/types'
|
||||||
|
|
||||||
const props = defineProps<{ style: CrossingStyle }>()
|
const props = defineProps<{ style: CrossingStyle }>()
|
||||||
const d = computed(() => wirePath([[3, 14], [37, 14]], new Map([[0, [{ lo: 15, hi: 25, r: 5 }]]]), props.style, 1))
|
const d = computed(() => wirePath([[3, 14], [37, 14]], new Map([[0, [20]]]), props.style, 1))
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,428 @@
|
||||||
|
<script setup lang="ts">
|
||||||
|
// The parts dock at the bottom, like a city builder's: a row of categories;
|
||||||
|
// pointing at one shows its parts in a strip above (scroll it sideways with
|
||||||
|
// the wheel). Click a part, then the canvas, or drag it where it goes.
|
||||||
|
// Clicking a category keeps it open. Typing searches every part.
|
||||||
|
import { shortCount } from '~/lib/logic/analyze'
|
||||||
|
import { CHALLENGES } from '~/lib/logic/challenges'
|
||||||
|
import { campaignProgress, challengeName, challengeOpen, defUsable, isCampaign, KIND_UNLOCK, NEEDS } from '~/lib/logic/progress'
|
||||||
|
import { weekKey, weeklyId } from '~/lib/logic/puzzles'
|
||||||
|
import { BASIC_GROUPS } from '~/composables/useParts'
|
||||||
|
import type { ComponentDef, NodeKind } from '~/lib/logic/types'
|
||||||
|
|
||||||
|
const ed = useEditor()
|
||||||
|
const { componentGroups, search } = useParts()
|
||||||
|
|
||||||
|
interface Tile {
|
||||||
|
id: string
|
||||||
|
kind: NodeKind
|
||||||
|
chip?: string
|
||||||
|
name: string
|
||||||
|
hint: string
|
||||||
|
/** Small text under the name: its key, transistors, "editing". */
|
||||||
|
meta?: string
|
||||||
|
/** Why it cannot be placed right now. */
|
||||||
|
blocked?: string
|
||||||
|
/** A component that can be opened for editing. */
|
||||||
|
edit?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Task {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
hint: string
|
||||||
|
state: 'solved' | 'open' | 'locked' | 'weekly' | 'puzzle'
|
||||||
|
meta?: string
|
||||||
|
run: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
type CatId = 'search' | 'logic' | 'inputs' | 'outputs' | 'wiring' | 'components' | 'challenges'
|
||||||
|
|
||||||
|
// ── What is in each category ──────────────────────────────────────
|
||||||
|
function lockedHint(kind: NodeKind) {
|
||||||
|
const by = KIND_UNLOCK[kind]
|
||||||
|
return by ? `Solve the ${challengeName(by)} challenge to unlock this part` : ''
|
||||||
|
}
|
||||||
|
|
||||||
|
const basic = (group: string): Tile[] =>
|
||||||
|
(BASIC_GROUPS.find(g => g.name === group)?.parts ?? []).map(p => ({
|
||||||
|
id: p.kind,
|
||||||
|
kind: p.kind,
|
||||||
|
name: p.name,
|
||||||
|
hint: p.hint,
|
||||||
|
meta: p.kind === 'nand' ? '4 transistors' : p.key ? `key ${p.key}` : undefined,
|
||||||
|
blocked: ed.canPlaceKind(p.kind) ? undefined : lockedHint(p.kind),
|
||||||
|
}))
|
||||||
|
|
||||||
|
function compTile(d: ComponentDef): Tile {
|
||||||
|
const editing = d.id === ed.def.value.id
|
||||||
|
const t = ed.transistors(d.id)
|
||||||
|
let blocked: string | undefined
|
||||||
|
if (editing) blocked = 'You are editing this one'
|
||||||
|
else if (!defUsable(ed.project.value, d)) blocked = 'Solve this challenge to use it as a part'
|
||||||
|
else if (!ed.canPlace(d.id)) blocked = 'It contains the circuit you are editing'
|
||||||
|
return {
|
||||||
|
id: d.id,
|
||||||
|
kind: 'chip',
|
||||||
|
chip: d.id,
|
||||||
|
name: d.name,
|
||||||
|
hint: d.description || 'Click, then click on the canvas to place',
|
||||||
|
meta: editing ? 'editing' : t ? `${shortCount(t)} transistors` : undefined,
|
||||||
|
blocked,
|
||||||
|
edit: !editing,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Components drawn like gates go with NAND under Logic; the rest under Components. */
|
||||||
|
const GATE_GROUP = 'Gates'
|
||||||
|
const compTabs = computed(() => componentGroups.value.filter(g => g.name !== GATE_GROUP))
|
||||||
|
const compTab = ref('')
|
||||||
|
const compTiles = computed(() => {
|
||||||
|
const tabs = compTabs.value
|
||||||
|
const g = tabs.find(t => t.name === compTab.value) ?? tabs[0]
|
||||||
|
return g ? g.defs.map(compTile) : []
|
||||||
|
})
|
||||||
|
|
||||||
|
const tiles = computed<Record<Exclude<CatId, 'challenges' | 'search'>, Tile[]>>(() => ({
|
||||||
|
logic: [...basic('Logic'), ...(componentGroups.value.find(g => g.name === GATE_GROUP)?.defs.map(compTile) ?? [])],
|
||||||
|
inputs: basic('Inputs'),
|
||||||
|
outputs: basic('Outputs'),
|
||||||
|
wiring: [...basic('Wiring'), ...basic('Notes')],
|
||||||
|
components: compTiles.value,
|
||||||
|
}))
|
||||||
|
|
||||||
|
const CATS: { id: Exclude<CatId, 'search'>; name: string; icon: string; key?: string }[] = [
|
||||||
|
{ id: 'logic', name: 'Logic', icon: 'lucide:square-function' },
|
||||||
|
{ id: 'inputs', name: 'Inputs', icon: 'lucide:toggle-left' },
|
||||||
|
{ id: 'outputs', name: 'Outputs', icon: 'lucide:lightbulb' },
|
||||||
|
{ id: 'wiring', name: 'Wiring', icon: 'lucide:cable' },
|
||||||
|
{ id: 'components', name: 'Components', icon: 'lucide:boxes' },
|
||||||
|
{ id: 'challenges', name: 'Challenges', icon: 'lucide:target' },
|
||||||
|
]
|
||||||
|
|
||||||
|
// ── Challenges and puzzles ────────────────────────────────────────
|
||||||
|
const solved = computed(() => new Set(ed.project.value.solved))
|
||||||
|
const solvedCount = computed(() => CHALLENGES.filter(c => solved.value.has(c.id)).length)
|
||||||
|
const campaign = computed(() => isCampaign(ed.project.value))
|
||||||
|
const started = computed(() => new Map(ed.project.value.components.filter(d => d.challenge).map(d => [d.challenge!, d])))
|
||||||
|
|
||||||
|
function openWeekly() {
|
||||||
|
const spec = ed.project.value.puzzles?.find(p => p.id === weeklyId(weekKey()))
|
||||||
|
if (spec) ed.beginPuzzle(spec)
|
||||||
|
else void ed.openPuzzle('weekly')
|
||||||
|
}
|
||||||
|
|
||||||
|
const tasks = computed<Task[]>(() => {
|
||||||
|
const best = ed.project.value.best ?? {}
|
||||||
|
const out: Task[] = [
|
||||||
|
{
|
||||||
|
id: 'weekly',
|
||||||
|
name: 'Puzzle of the week',
|
||||||
|
hint: 'A new logic puzzle every Monday, the same for everyone. Fewest transistors wins.',
|
||||||
|
state: 'weekly',
|
||||||
|
meta: started.value.has(weeklyId(weekKey())) ? 'open it' : 'new',
|
||||||
|
run: openWeekly,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
const puzzles = (ed.project.value.puzzles ?? []).filter(p => !p.id.startsWith('week:'))
|
||||||
|
for (const p of puzzles)
|
||||||
|
out.push({ id: p.id, name: p.name, hint: p.goal, state: solved.value.has(p.id) ? 'solved' : 'puzzle', meta: best[p.id] !== undefined ? `best ${best[p.id]}` : 'puzzle', run: () => ed.beginPuzzle(p) })
|
||||||
|
for (const c of CHALLENGES) {
|
||||||
|
const open = challengeOpen(ed.project.value, c.id) || started.value.has(c.id)
|
||||||
|
const needs = `Solve ${(NEEDS[c.id] ?? []).filter(n => !solved.value.has(n)).map(challengeName).join(' and ')} first`
|
||||||
|
out.push({
|
||||||
|
id: c.id,
|
||||||
|
name: c.name,
|
||||||
|
hint: open ? `${c.goal}\n${c.inputs.join(', ')} → ${c.outputs.join(', ')}` : needs,
|
||||||
|
state: solved.value.has(c.id) ? 'solved' : open ? 'open' : 'locked',
|
||||||
|
meta: best[c.id] !== undefined ? `best ${best[c.id]}` : open ? (started.value.has(c.id) ? 'started' : undefined) : 'locked',
|
||||||
|
run: () => ed.beginChallenge(c),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
})
|
||||||
|
const TASK_ICON: Record<Task['state'], string> = {
|
||||||
|
solved: 'lucide:circle-check',
|
||||||
|
open: 'lucide:circle',
|
||||||
|
locked: 'lucide:lock',
|
||||||
|
weekly: 'lucide:calendar-days',
|
||||||
|
puzzle: 'lucide:puzzle',
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Opening and closing ───────────────────────────────────────────
|
||||||
|
const shown = ref<CatId | null>(null)
|
||||||
|
const pinned = ref(false)
|
||||||
|
let closeTimer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
let openTimer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
|
||||||
|
function hover(id: CatId) {
|
||||||
|
clearTimeout(closeTimer)
|
||||||
|
clearTimeout(openTimer)
|
||||||
|
if (pinned.value && shown.value !== id) return
|
||||||
|
// Already open: follow the pointer at once; otherwise wait a moment, so passing over does not flash.
|
||||||
|
if (shown.value) shown.value = id
|
||||||
|
else openTimer = setTimeout(() => (shown.value = id), 90)
|
||||||
|
}
|
||||||
|
|
||||||
|
function click(id: CatId) {
|
||||||
|
clearTimeout(openTimer)
|
||||||
|
if (shown.value === id && pinned.value) return close()
|
||||||
|
shown.value = id
|
||||||
|
pinned.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function leave() {
|
||||||
|
clearTimeout(openTimer)
|
||||||
|
if (pinned.value || ed.dragPart.value || searching.value) return
|
||||||
|
closeTimer = setTimeout(close, 280)
|
||||||
|
}
|
||||||
|
|
||||||
|
function stay() {
|
||||||
|
clearTimeout(closeTimer)
|
||||||
|
}
|
||||||
|
|
||||||
|
function close() {
|
||||||
|
clearTimeout(closeTimer)
|
||||||
|
shown.value = null
|
||||||
|
pinned.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
const searchEl = ref<HTMLInputElement>()
|
||||||
|
const query = ref('')
|
||||||
|
const focused = ref(false)
|
||||||
|
const searching = computed(() => focused.value || !!query.value.trim())
|
||||||
|
const at = ref(0)
|
||||||
|
const hits = computed<Tile[]>(() =>
|
||||||
|
search(query.value, 40).map(h => ({ id: h.chip ?? h.kind, kind: h.kind, chip: h.chip, name: h.name, hint: h.group, meta: h.key ? `key ${h.key}` : h.group })),
|
||||||
|
)
|
||||||
|
watch(query, () => {
|
||||||
|
at.value = 0
|
||||||
|
if (query.value.trim()) shown.value = 'search'
|
||||||
|
})
|
||||||
|
watch(focused, f => {
|
||||||
|
if (f) shown.value = 'search'
|
||||||
|
else if (shown.value === 'search' && !query.value.trim()) close()
|
||||||
|
})
|
||||||
|
// "/" on the canvas, or a request from elsewhere, puts the cursor here.
|
||||||
|
watch(
|
||||||
|
() => ed.partSearch.value,
|
||||||
|
() => {
|
||||||
|
ed.toggleSidebar('left', true)
|
||||||
|
nextTick(() => {
|
||||||
|
searchEl.value?.focus()
|
||||||
|
searchEl.value?.select()
|
||||||
|
})
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
function onSearchKey(e: KeyboardEvent) {
|
||||||
|
e.stopPropagation()
|
||||||
|
const n = hits.value.length
|
||||||
|
if (['ArrowRight', 'ArrowDown', 'ArrowLeft', 'ArrowUp'].includes(e.key)) {
|
||||||
|
e.preventDefault()
|
||||||
|
if (n) at.value = (at.value + (e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : -1) + n) % n
|
||||||
|
nextTick(() => strip.value?.querySelector('.tile.active')?.scrollIntoView({ inline: 'nearest', block: 'nearest' }))
|
||||||
|
} else if (e.key === 'Enter') {
|
||||||
|
e.preventDefault()
|
||||||
|
const h = hits.value[at.value]
|
||||||
|
if (h) pick(h)
|
||||||
|
} else if (e.key === 'Escape') {
|
||||||
|
query.value = ''
|
||||||
|
searchEl.value?.blur()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const list = computed<Tile[]>(() => {
|
||||||
|
const s = shown.value
|
||||||
|
if (!s || s === 'challenges') return []
|
||||||
|
return s === 'search' ? hits.value : tiles.value[s]
|
||||||
|
})
|
||||||
|
|
||||||
|
// ── Using a tile ──────────────────────────────────────────────────
|
||||||
|
function pick(t: Tile) {
|
||||||
|
if (t.blocked) {
|
||||||
|
ed.play('error')
|
||||||
|
return ed.notify(t.blocked, 'error')
|
||||||
|
}
|
||||||
|
ed.placing.value = { kind: t.kind, chip: t.chip }
|
||||||
|
query.value = ''
|
||||||
|
searchEl.value?.blur()
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
|
||||||
|
function onDragStart(e: DragEvent, t: Tile) {
|
||||||
|
if (t.blocked) return e.preventDefault()
|
||||||
|
e.dataTransfer?.setData('application/x-logigate', JSON.stringify({ kind: t.kind, chip: t.chip }))
|
||||||
|
if (e.dataTransfer) e.dataTransfer.effectAllowed = 'copy'
|
||||||
|
ed.dragPart.value = { kind: t.kind, chip: t.chip }
|
||||||
|
}
|
||||||
|
|
||||||
|
function onDragEnd() {
|
||||||
|
ed.dragPart.value = null
|
||||||
|
if (!pinned.value) close()
|
||||||
|
}
|
||||||
|
|
||||||
|
function runTask(t: Task) {
|
||||||
|
if (t.state === 'locked') {
|
||||||
|
ed.play('error')
|
||||||
|
return ed.notify(t.hint, 'error')
|
||||||
|
}
|
||||||
|
t.run()
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Sideways scrolling ────────────────────────────────────────────
|
||||||
|
const strip = ref<HTMLElement>()
|
||||||
|
const edges = ref({ left: false, right: false })
|
||||||
|
function measure() {
|
||||||
|
const el = strip.value
|
||||||
|
if (!el) return
|
||||||
|
edges.value = { left: el.scrollLeft > 4, right: el.scrollLeft + el.clientWidth < el.scrollWidth - 4 }
|
||||||
|
}
|
||||||
|
function onWheel(e: WheelEvent) {
|
||||||
|
const el = strip.value
|
||||||
|
if (!el || Math.abs(e.deltaX) > Math.abs(e.deltaY)) return
|
||||||
|
e.preventDefault()
|
||||||
|
el.scrollLeft += e.deltaY
|
||||||
|
}
|
||||||
|
function page(dir: number) {
|
||||||
|
strip.value?.scrollBy({ left: dir * strip.value.clientWidth * 0.8, behavior: 'smooth' })
|
||||||
|
}
|
||||||
|
watch([shown, compTab, () => list.value.length], () => nextTick(measure))
|
||||||
|
|
||||||
|
const title = computed(() => {
|
||||||
|
const s = shown.value
|
||||||
|
if (s === 'search') return query.value.trim() ? `Parts matching "${query.value.trim()}"` : 'Recent and basic parts'
|
||||||
|
return CATS.find(c => c.id === s)?.name ?? ''
|
||||||
|
})
|
||||||
|
|
||||||
|
// Escape closes a strip that was clicked open.
|
||||||
|
function onKey(e: KeyboardEvent) {
|
||||||
|
if (e.key === 'Escape' && shown.value && !searching.value) close()
|
||||||
|
}
|
||||||
|
onMounted(() => window.addEventListener('keydown', onKey))
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
window.removeEventListener('keydown', onKey)
|
||||||
|
clearTimeout(closeTimer)
|
||||||
|
clearTimeout(openTimer)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="dock" @pointerleave="leave" @pointerenter="stay">
|
||||||
|
<Transition name="flyout">
|
||||||
|
<section v-if="shown" class="dock-flyout" :class="{ pinned }" :aria-label="title">
|
||||||
|
<header class="flyout-head">
|
||||||
|
<span class="flyout-title">{{ title }}</span>
|
||||||
|
<template v-if="shown === 'components' && compTabs.length > 1">
|
||||||
|
<div class="flyout-tabs" role="tablist">
|
||||||
|
<button
|
||||||
|
v-for="(g, i) in compTabs"
|
||||||
|
:key="g.name"
|
||||||
|
role="tab"
|
||||||
|
:aria-selected="(compTab || compTabs[0]!.name) === g.name"
|
||||||
|
:class="{ active: (compTab || compTabs[0]!.name) === g.name || (!compTab && i === 0) }"
|
||||||
|
@click="compTab = g.name"
|
||||||
|
>
|
||||||
|
{{ g.name }} <span class="count">{{ g.defs.length }}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template v-if="shown === 'challenges'">
|
||||||
|
<span v-if="campaign" class="flyout-progress" :title="`${solvedCount} of ${CHALLENGES.length} solved`">
|
||||||
|
<span class="bar"><span :style="{ width: `${campaignProgress(ed.project.value) * 100}%` }" /></span>
|
||||||
|
{{ solvedCount }}/{{ CHALLENGES.length }}
|
||||||
|
</span>
|
||||||
|
<span v-else class="flyout-note">{{ solvedCount }}/{{ CHALLENGES.length }} solved</span>
|
||||||
|
</template>
|
||||||
|
<span v-else-if="shown === 'search'" class="flyout-note">← → choose · Enter place</span>
|
||||||
|
<span v-else class="flyout-note">Click, then click the canvas · or drag</span>
|
||||||
|
<button v-if="pinned" class="icon-btn ml-auto" title="Close (Esc)" @click="close"><Icon name="lucide:x" class="size-3.5" /></button>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div class="strip-wrap">
|
||||||
|
<button v-if="edges.left" class="strip-arrow left" title="Scroll left" @click="page(-1)"><Icon name="lucide:chevron-left" class="size-4" /></button>
|
||||||
|
<div ref="strip" class="strip" @wheel="onWheel" @scroll="measure">
|
||||||
|
<template v-if="shown === 'challenges'">
|
||||||
|
<button
|
||||||
|
v-for="t in tasks"
|
||||||
|
:key="t.id"
|
||||||
|
class="tile task"
|
||||||
|
:class="[t.state, { current: ed.def.value.challenge === t.id || (t.id === 'weekly' && ed.def.value.challenge === weeklyId(weekKey())) }]"
|
||||||
|
:title="t.hint"
|
||||||
|
@click="runTask(t)"
|
||||||
|
>
|
||||||
|
<span class="tile-art"><Icon :name="TASK_ICON[t.state]" class="size-6" /></span>
|
||||||
|
<span class="tile-name">{{ t.name }}</span>
|
||||||
|
<span v-if="t.meta" class="tile-meta">{{ t.meta }}</span>
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
<div v-for="(t, i) in list" :key="t.id" class="tile-slot">
|
||||||
|
<button
|
||||||
|
class="tile"
|
||||||
|
:class="{ active: shown === 'search' && i === at, blocked: !!t.blocked, placing: ed.placing.value?.kind === t.kind && ed.placing.value?.chip === t.chip }"
|
||||||
|
:title="t.blocked || t.hint"
|
||||||
|
:draggable="!t.blocked"
|
||||||
|
@click="pick(t)"
|
||||||
|
@dragstart="onDragStart($event, t)"
|
||||||
|
@dragend="onDragEnd"
|
||||||
|
@pointerenter="shown === 'search' && (at = i)"
|
||||||
|
>
|
||||||
|
<span class="tile-art"><EditorPartThumb :kind="t.kind" :chip="t.chip" /></span>
|
||||||
|
<span class="tile-name">{{ t.name }}</span>
|
||||||
|
<span v-if="t.meta" class="tile-meta">{{ t.meta }}</span>
|
||||||
|
<Icon v-if="t.blocked && !t.meta?.startsWith('editing')" name="lucide:lock" class="tile-lock size-3.5" />
|
||||||
|
</button>
|
||||||
|
<button v-if="t.edit && t.chip" class="tile-edit" title="Open and edit" @click="ed.open(t.chip!); close()">
|
||||||
|
<Icon name="lucide:pencil" class="size-3" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<template v-if="shown === 'components'">
|
||||||
|
<button class="tile add" title="An empty component to build; its inputs and outputs become its pins" @click="ed.createComponent(); close()">
|
||||||
|
<span class="tile-art"><Icon name="lucide:plus" class="size-6" /></span>
|
||||||
|
<span class="tile-name">New component</span>
|
||||||
|
</button>
|
||||||
|
<button class="tile add" title="NOT, AND, … up to a 4-bit counter, all built from NAND" @click="ed.loadExamples(); close()">
|
||||||
|
<span class="tile-art"><Icon name="lucide:library" class="size-6" /></span>
|
||||||
|
<span class="tile-name">Example parts</span>
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
<p v-if="!list.length && shown === 'search'" class="strip-empty">Nothing called "{{ query.trim() }}" fits here.</p>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
<button v-if="edges.right" class="strip-arrow right" title="Scroll right" @click="page(1)"><Icon name="lucide:chevron-right" class="size-4" /></button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</Transition>
|
||||||
|
|
||||||
|
<nav class="dock-bar" aria-label="Parts">
|
||||||
|
<label class="dock-search" :class="{ open: searching }">
|
||||||
|
<Icon name="lucide:search" class="size-4 shrink-0" />
|
||||||
|
<input
|
||||||
|
ref="searchEl"
|
||||||
|
v-model="query"
|
||||||
|
placeholder="Find a part"
|
||||||
|
@focus="focused = true"
|
||||||
|
@blur="focused = false"
|
||||||
|
@keydown="onSearchKey"
|
||||||
|
/>
|
||||||
|
<kbd v-if="!searching">/</kbd>
|
||||||
|
</label>
|
||||||
|
<span class="dock-sep" />
|
||||||
|
<button
|
||||||
|
v-for="c in CATS"
|
||||||
|
:key="c.id"
|
||||||
|
class="dock-cat"
|
||||||
|
:class="{ active: shown === c.id, task: c.id === 'challenges' && !!ed.task.value }"
|
||||||
|
:aria-expanded="shown === c.id"
|
||||||
|
@pointerenter="hover(c.id)"
|
||||||
|
@click="click(c.id)"
|
||||||
|
>
|
||||||
|
<Icon :name="c.icon" class="size-5" />
|
||||||
|
<span>{{ c.name }}</span>
|
||||||
|
<span v-if="c.id === 'challenges'" class="dock-count">{{ solvedCount }}/{{ CHALLENGES.length }}</span>
|
||||||
|
</button>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
@ -1,11 +1,9 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
// Drawing a component's box by hand: place, size and turn its lamps,
|
// Drawing a component's box by hand: place, size and turn its lamps,
|
||||||
// displays, screens and name; split a screen into pixels to place one by
|
// displays, screens and name; show displays of the components inside it;
|
||||||
// one; show displays of the components inside it; space and reorder its
|
// space its pins apart; draw lines, boxes, circles and text. Everything
|
||||||
// pins; draw lines, boxes, circles and text. Pick several things (Shift +
|
// shows live on the box, and on every copy placed.
|
||||||
// click, or a box around them) to move them together. Everything shows live
|
import { faceCandidates, faceTransform, GRID as G, shapeTransform, type FaceItem } from '~/lib/logic/geometry'
|
||||||
// on the box, and on every copy placed.
|
|
||||||
import { faceCandidates, faceTransform, GRID as G, pixelKey, shapeTransform, type FaceItem } from '~/lib/logic/geometry'
|
|
||||||
import { uid } from '~/lib/logic/ops'
|
import { uid } from '~/lib/logic/ops'
|
||||||
import { FACE_INKS, type CircuitNode, type FaceDesign, type FaceInk, type FaceShape } from '~/lib/logic/types'
|
import { FACE_INKS, type CircuitNode, type FaceDesign, type FaceInk, type FaceShape } from '~/lib/logic/types'
|
||||||
|
|
||||||
|
|
@ -27,19 +25,8 @@ const INK_HEX: Record<FaceInk, string> = { muted: '#6b778a', text: '#dbe2ea', re
|
||||||
const tool = ref<Tool>('move')
|
const tool = ref<Tool>('move')
|
||||||
const ink = ref<FaceInk>('muted')
|
const ink = ref<FaceInk>('muted')
|
||||||
const fill = ref(false)
|
const fill = ref(false)
|
||||||
/** What is selected: a drawing's id, a box item's key, 'name', or 'pin:<key>'; the last one picked. */
|
/** What is selected: a drawing's id, a box item's key, 'name', or 'pin:<key>'. */
|
||||||
const sel = ref<string | null>(null)
|
const sel = ref<string | null>(null)
|
||||||
/** Everything picked, to move together (Shift + click, or a box around them). */
|
|
||||||
const group = ref<string[]>([])
|
|
||||||
const isSel = (id: string) => sel.value === id || group.value.includes(id)
|
|
||||||
function pick(id: string | null) {
|
|
||||||
sel.value = id
|
|
||||||
group.value = id ? [id] : []
|
|
||||||
}
|
|
||||||
watch(sel, v => {
|
|
||||||
if (v && !group.value.includes(v)) group.value = [v]
|
|
||||||
if (!v) group.value = []
|
|
||||||
})
|
|
||||||
|
|
||||||
const VIEW_W = 620
|
const VIEW_W = 620
|
||||||
const VIEW_H = 440
|
const VIEW_H = 440
|
||||||
|
|
@ -54,8 +41,7 @@ function design(): FaceDesign {
|
||||||
const s = shape.value
|
const s = shape.value
|
||||||
const place: Record<string, { x: number; y: number }> = {}
|
const place: Record<string, { x: number; y: number }> = {}
|
||||||
for (const it of s.face ?? []) place[it.key] = { x: it.x, y: it.y - s.body.y }
|
for (const it of s.face ?? []) place[it.key] = { x: it.x, y: it.y - s.body.y }
|
||||||
// A new design keeps the box as big as what is on it.
|
d.design = { w: s.body.w, h: s.body.h, place, shapes: [] }
|
||||||
d.design = { w: s.body.w, h: s.body.h, place, shapes: [], fit: true }
|
|
||||||
}
|
}
|
||||||
d.design.place ??= {}
|
d.design.place ??= {}
|
||||||
d.design.shapes ??= []
|
d.design.shapes ??= []
|
||||||
|
|
@ -82,13 +68,10 @@ const nameBox = computed(() => {
|
||||||
return { x: c.x - w / 2, y: c.y - 0.55, w, h: 1.1 }
|
return { x: c.x - w / 2, y: c.y - 0.55, w, h: 1.1 }
|
||||||
})
|
})
|
||||||
|
|
||||||
/** Pins on both edges, cable sockets too, to drag up and down. */
|
/** Pins on both edges, to drag up and down. */
|
||||||
const pins = computed(() => [
|
const pins = computed(() => [
|
||||||
...shape.value.inputs.filter(p => p.dx === 0).map(p => ({ ...p, side: 'in' as const })),
|
...shape.value.inputs.filter(p => !p.bus).map(p => ({ ...p, side: 'in' as const })),
|
||||||
...shape.value.outputs.filter(p => p.dx > 0).map(p => ({ ...p, side: 'out' as const })),
|
...shape.value.outputs.filter(p => !p.bus).map(p => ({ ...p, side: 'out' as const })),
|
||||||
// Pins on the other edge than usual (lines of a socket that run the other way) stay with their edge.
|
|
||||||
...shape.value.inputs.filter(p => p.dx > 0).map(p => ({ ...p, side: 'out' as const })),
|
|
||||||
...shape.value.outputs.filter(p => p.dx === 0).map(p => ({ ...p, side: 'in' as const })),
|
|
||||||
])
|
])
|
||||||
|
|
||||||
const shapes = computed(() => def.value?.design?.shapes ?? [])
|
const shapes = computed(() => def.value?.design?.shapes ?? [])
|
||||||
|
|
@ -107,11 +90,9 @@ const nameShown = computed(() => !(def.value?.design?.hide ?? []).includes('name
|
||||||
|
|
||||||
type Drag =
|
type Drag =
|
||||||
| { type: 'create'; id: string }
|
| { type: 'create'; id: string }
|
||||||
| { type: 'move'; start: { x: number; y: number }; origs: Map<string, { x: number; y: number }> }
|
| { type: 'move'; id: string; start: { x: number; y: number }; orig: { x: number; y: number } }
|
||||||
| { type: 'resize'; id: string; handle: 'a' | 'b'; orig: FaceShape }
|
| { type: 'resize'; id: string; handle: 'a' | 'b'; orig: FaceShape }
|
||||||
| { type: 'scale'; key: string }
|
| { type: 'pin'; key: string; side: 'in' | 'out'; start: number; rows: { key: string; dy: number; set: boolean }[]; index: number }
|
||||||
| { type: 'box'; start: { x: number; y: number }; cur: { x: number; y: number }; add: boolean }
|
|
||||||
| { type: 'pin'; key: string; side: 'in' | 'out'; start: number; rows: { key: string; dy: number; set: boolean; port?: string }[]; index: number }
|
|
||||||
const drag = ref<Drag | null>(null)
|
const drag = ref<Drag | null>(null)
|
||||||
|
|
||||||
function onDown(e: PointerEvent) {
|
function onDown(e: PointerEvent) {
|
||||||
|
|
@ -139,30 +120,16 @@ function onDown(e: PointerEvent) {
|
||||||
const el = (e.target as Element).closest('[data-face]')
|
const el = (e.target as Element).closest('[data-face]')
|
||||||
const id = el?.getAttribute('data-face')
|
const id = el?.getAttribute('data-face')
|
||||||
if (!id) {
|
if (!id) {
|
||||||
// Empty space: a box around things picks them (Shift: adds to what is picked).
|
sel.value = null
|
||||||
if (!e.shiftKey) pick(null)
|
|
||||||
drag.value = { type: 'box', start: p, cur: p, add: e.shiftKey }
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (e.shiftKey && !id.startsWith('pin:')) {
|
sel.value = id
|
||||||
// Shift + click: in or out of what is picked.
|
|
||||||
group.value = group.value.includes(id) ? group.value.filter(x => x !== id) : [...group.value, id]
|
|
||||||
sel.value = group.value.at(-1) ?? null
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (el!.getAttribute('data-handle') === 'scale') {
|
|
||||||
drag.value = { type: 'scale', key: id }
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const many = group.value.length > 1 && group.value.includes(id)
|
|
||||||
if (!many) pick(id)
|
|
||||||
else sel.value = id
|
|
||||||
if (id.startsWith('pin:')) {
|
if (id.startsWith('pin:')) {
|
||||||
const key = id.slice(4)
|
const key = id.slice(4)
|
||||||
const pin = pins.value.find(x => x.key === key)!
|
const pin = pins.value.find(x => x.key === key)!
|
||||||
const side = pins.value.filter(x => x.side === pin.side).sort((a, b) => a.dy - b.dy)
|
const side = pins.value.filter(x => x.side === pin.side)
|
||||||
const pinAt = def.value.design?.pinAt ?? {}
|
const pinAt = def.value.design?.pinAt ?? {}
|
||||||
drag.value = { type: 'pin', key, side: pin.side, start: p.y, rows: side.map(x => ({ key: x.key, dy: x.dy, set: pinAt[x.key] !== undefined, ...(x.port ? { port: x.port } : {}) })), index: side.findIndex(x => x.key === key) }
|
drag.value = { type: 'pin', key, side: pin.side, start: p.y, rows: side.map(x => ({ key: x.key, dy: x.dy, set: pinAt[x.key] !== undefined })), index: side.findIndex(x => x.key === key) }
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const handle = el!.getAttribute('data-handle') as 'a' | 'b' | null
|
const handle = el!.getAttribute('data-handle') as 'a' | 'b' | null
|
||||||
|
|
@ -171,54 +138,9 @@ function onDown(e: PointerEvent) {
|
||||||
drag.value = { type: 'resize', id, handle, orig: { ...sh } }
|
drag.value = { type: 'resize', id, handle, orig: { ...sh } }
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const origs = new Map<string, { x: number; y: number }>()
|
|
||||||
for (const g of many ? group.value : [id]) {
|
|
||||||
const o = origOf(g)
|
|
||||||
if (o) origs.set(g, o)
|
|
||||||
}
|
|
||||||
if (origs.size) drag.value = { type: 'move', start: p, origs }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Where a thing on the box is now, from the box's top left (a drawing's own corner, the name's box). */
|
|
||||||
function origOf(id: string): { x: number; y: number } | null {
|
|
||||||
const sh = shapes.value.find(s => s.id === id)
|
|
||||||
if (sh) return { x: sh.x, y: sh.y }
|
|
||||||
const it = items.value.find(x => x.key === id)
|
const it = items.value.find(x => x.key === id)
|
||||||
if (it) return { x: it.x, y: it.y - top.value }
|
const orig = sh ? { x: sh.x, y: sh.y } : it ? { x: it.x, y: it.y - top.value } : id === 'name' && nameBox.value ? { x: nameBox.value.x, y: nameBox.value.y - top.value } : null
|
||||||
if (id === 'name' && nameBox.value) return { x: nameBox.value.x, y: nameBox.value.y - top.value }
|
if (orig) drag.value = { type: 'move', id, start: p, orig }
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Puts a thing on the box with its top left (as origOf gives it) at x, y. */
|
|
||||||
function putAt(id: string, x: number, y: number) {
|
|
||||||
const s = shapes.value.find(sh => sh.id === id)
|
|
||||||
if (s) {
|
|
||||||
s.x = x
|
|
||||||
s.y = y
|
|
||||||
} else if (id === 'name') {
|
|
||||||
const w = nameText.value.length * 0.5 + 0.6
|
|
||||||
design().place!.name = { x: x + w / 2, y: y + 0.55 }
|
|
||||||
} else if (!id.startsWith('pin:')) design().place![id] = { x, y }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The area a thing covers on the box, from its top left, sized and turned as shown. */
|
|
||||||
function areaOf(id: string): { x: number; y: number; w: number; h: number } | null {
|
|
||||||
const sh = shapes.value.find(s => s.id === id)
|
|
||||||
if (sh) {
|
|
||||||
const w = sh.kind === 'text' ? (sh.text?.length ?? 1) * 0.42 * (sh.size ?? 1) : Math.abs(sh.w)
|
|
||||||
const h = sh.kind === 'text' ? (sh.size ?? 1) : Math.abs(sh.h)
|
|
||||||
return { x: Math.min(sh.x, sh.x + sh.w), y: Math.min(sh.y, sh.y + sh.h), w, h }
|
|
||||||
}
|
|
||||||
const it = items.value.find(x => x.key === id)
|
|
||||||
if (it) {
|
|
||||||
const k = it.scale ?? 1
|
|
||||||
const turned = it.rotate === 90 || it.rotate === 270
|
|
||||||
const w = (turned ? it.h : it.w) * k
|
|
||||||
const h = (turned ? it.w : it.h) * k
|
|
||||||
return { x: it.x + (it.w * k) / 2 - w / 2, y: it.y - top.value + (it.h * k) / 2 - h / 2, w, h }
|
|
||||||
}
|
|
||||||
if (id === 'name' && nameBox.value) return { ...nameBox.value, y: nameBox.value.y - top.value }
|
|
||||||
return null
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function onMove(e: PointerEvent) {
|
function onMove(e: PointerEvent) {
|
||||||
|
|
@ -238,56 +160,27 @@ function onMove(e: PointerEvent) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (d.type === 'pin') {
|
if (d.type === 'pin') {
|
||||||
const row = d.rows[d.index]!
|
// Dragging a pin moves it and the pins below it on that edge: a gap opens above it.
|
||||||
// A cable socket takes the lines split out of it along: they move as one block.
|
const prev = d.index > 0 ? d.rows[d.index - 1]!.dy : -1
|
||||||
const block = d.rows.filter(r => r === row || (r.port && r.port === row.key))
|
const delta = Math.max(Math.round(p.y - d.start), prev + 1 - d.rows[d.index]!.dy)
|
||||||
const others = d.rows.filter(r => !block.includes(r))
|
|
||||||
const span = Math.max(...block.map(r => r.dy)) - row.dy
|
|
||||||
const want = Math.max(0, Math.round(row.dy + p.y - d.start))
|
|
||||||
const above = others.filter(r => r.dy < row.dy).at(-1)
|
|
||||||
const below = others.find(r => r.dy > row.dy + span)
|
|
||||||
const pinAt = (design().pinAt ??= {})
|
const pinAt = (design().pinAt ??= {})
|
||||||
const putBlock = (top: number) => {
|
d.rows.forEach((r, i) => {
|
||||||
for (const r of block) pinAt[r.key] = top + (r.dy - row.dy)
|
if (i === d.index) pinAt[r.key] = Math.max(0, r.dy + delta)
|
||||||
}
|
else if (i > d.index && r.set) pinAt[r.key] = Math.max(0, r.dy + delta)
|
||||||
if ((below && want + span >= below.dy) || (above && want <= above.dy)) {
|
})
|
||||||
// Onto or past a neighbour: the pins change order. The others stay where they are, this one goes where it is dragged.
|
|
||||||
const at = others.filter(r => r.dy < want || (r.dy === want && want > row.dy)).length
|
|
||||||
const order = [...others.slice(0, at), ...block, ...others.slice(at)].map(r => r.key)
|
|
||||||
const keep = (design().pinOrder ?? []).filter(k => !d.rows.some(r => r.key === k))
|
|
||||||
design().pinOrder = [...keep, ...order]
|
|
||||||
for (const r of others) pinAt[r.key] = r.dy
|
|
||||||
putBlock(want)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// Moved along its own gap: it and the pins below it on that edge go, so a gap opens above it.
|
|
||||||
const delta = Math.max(Math.round(p.y - d.start), (above ? above.dy + 1 : 0) - row.dy)
|
|
||||||
putBlock(row.dy + delta)
|
|
||||||
for (const r of others) if (r.dy > row.dy && r.set) pinAt[r.key] = Math.max(0, r.dy + delta)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (d.type === 'move') {
|
if (d.type === 'move') {
|
||||||
const dx = p.x - d.start.x
|
const x = snap(d.orig.x + p.x - d.start.x)
|
||||||
const dy = p.y - d.start.y
|
const y = snap(d.orig.y + p.y - d.start.y)
|
||||||
for (const [id, o] of d.origs) putAt(id, snap(o.x + dx), snap(o.y + dy))
|
const s = shapes.value.find(sh => sh.id === d.id)
|
||||||
return
|
if (s) {
|
||||||
}
|
s.x = x
|
||||||
if (d.type === 'box') {
|
s.y = y
|
||||||
d.cur = p
|
} else if (d.id === 'name') {
|
||||||
return
|
const w = nameText.value.length * 0.5 + 0.6
|
||||||
}
|
design().place!.name = { x: x + w / 2, y: y + 0.55 }
|
||||||
if (d.type === 'scale') {
|
} else design().place![d.id] = { x, y }
|
||||||
// Grown from its top left corner, as far as the pointer is pulled.
|
|
||||||
const it = items.value.find(x => x.key === d.key)
|
|
||||||
if (!it) return
|
|
||||||
const turned = it.rotate === 90 || it.rotate === 270
|
|
||||||
const kx = (p.x - it.x) / (turned ? it.h : it.w)
|
|
||||||
const ky = (p.y + top.value - it.y) / (turned ? it.w : it.h)
|
|
||||||
const k = Math.min(4, Math.max(0.25, Math.round(Math.max(kx, ky) * 20) / 20))
|
|
||||||
const des = design()
|
|
||||||
des.scale ??= {}
|
|
||||||
if (k === 1) delete des.scale[d.key]
|
|
||||||
else des.scale[d.key] = k
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const s = shapes.value.find(sh => sh.id === d.id)
|
const s = shapes.value.find(sh => sh.id === d.id)
|
||||||
|
|
@ -308,21 +201,6 @@ function onUp() {
|
||||||
const d = drag.value
|
const d = drag.value
|
||||||
drag.value = null
|
drag.value = null
|
||||||
if (!d) return
|
if (!d) return
|
||||||
if (d.type === 'box') {
|
|
||||||
// Everything the box touches is picked.
|
|
||||||
const x0 = Math.min(d.start.x, d.cur.x)
|
|
||||||
const x1 = Math.max(d.start.x, d.cur.x)
|
|
||||||
const y0 = Math.min(d.start.y, d.cur.y)
|
|
||||||
const y1 = Math.max(d.start.y, d.cur.y)
|
|
||||||
if (x1 - x0 < 0.2 && y1 - y0 < 0.2) return
|
|
||||||
const ids = [...shapes.value.map(sh => sh.id), ...items.value.map(it => it.key), ...(nameBox.value ? ['name'] : [])].filter(id => {
|
|
||||||
const a = areaOf(id)
|
|
||||||
return a && a.x < x1 && a.x + a.w > x0 && a.y < y1 && a.y + a.h > y0
|
|
||||||
})
|
|
||||||
group.value = d.add ? [...new Set([...group.value, ...ids])] : ids
|
|
||||||
sel.value = group.value.at(-1) ?? null
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (d.type === 'create') {
|
if (d.type === 'create') {
|
||||||
const s = shapes.value.find(x => x.id === d.id)
|
const s = shapes.value.find(x => x.id === d.id)
|
||||||
// A click without dragging draws nothing.
|
// A click without dragging draws nothing.
|
||||||
|
|
@ -337,62 +215,9 @@ function onUp() {
|
||||||
}
|
}
|
||||||
|
|
||||||
function remove() {
|
function remove() {
|
||||||
const gone = new Set(group.value.filter(id => shapes.value.some(s => s.id === id)))
|
if (!selShape.value) return
|
||||||
if (selShape.value) gone.add(selShape.value.id)
|
design().shapes = shapes.value.filter(s => s !== selShape.value)
|
||||||
if (!gone.size) return
|
sel.value = null
|
||||||
design().shapes = shapes.value.filter(s => !gone.has(s.id))
|
|
||||||
pick(null)
|
|
||||||
ed.commit(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Moves everything picked a step (a quarter square; Shift: a whole one). */
|
|
||||||
function nudge(dx: number, dy: number) {
|
|
||||||
const ids = group.value.length ? group.value : sel.value ? [sel.value] : []
|
|
||||||
let moved = false
|
|
||||||
for (const id of ids) {
|
|
||||||
const o = origOf(id)
|
|
||||||
if (!o) continue
|
|
||||||
putAt(id, snap(o.x + dx), snap(o.y + dy))
|
|
||||||
moved = true
|
|
||||||
}
|
|
||||||
if (moved) ed.commit(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Screens pixel by pixel ──────────────────────────────────────────
|
|
||||||
/** The screen of the selected item, when it is a whole screen (to split) or one of its pixels (to join). */
|
|
||||||
const selScreen = computed(() => {
|
|
||||||
const it = selItem.value
|
|
||||||
if (!it || it.kind !== 'screen') return null
|
|
||||||
if (it.screenOf) return { key: it.screenOf, split: true }
|
|
||||||
return (it.pixels?.length ?? 0) > 1 ? { key: it.key, split: false } : null
|
|
||||||
})
|
|
||||||
|
|
||||||
/** Splits a screen into pixels placed one by one (each where it sat), or joins them into one screen again. */
|
|
||||||
function toggleSplit(key: string, split: boolean) {
|
|
||||||
const d = design()
|
|
||||||
const set = new Set(d.split ?? [])
|
|
||||||
if (split) set.add(key)
|
|
||||||
else {
|
|
||||||
set.delete(key)
|
|
||||||
// The pixels' own places go; the screen keeps the place it had.
|
|
||||||
const it = items.value.find(x => x.screenOf === key)
|
|
||||||
for (const p of items.value.filter(x => x.screenOf === key)) delete d.place?.[p.key]
|
|
||||||
if (it && !d.place?.[key]) d.place![key] = { x: it.x, y: it.y - top.value }
|
|
||||||
}
|
|
||||||
if (set.size) d.split = [...set]
|
|
||||||
else delete d.split
|
|
||||||
pick(split ? pixelKey(items.value.find(x => x.key === key)?.pixels?.[0]?.id ?? '') : key)
|
|
||||||
ed.commit(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Fitted: the box is as big as what is on it. Off: it keeps the width and height set. */
|
|
||||||
function toggleFit() {
|
|
||||||
const d = design()
|
|
||||||
if (d.fit) {
|
|
||||||
delete d.fit
|
|
||||||
d.w = body.value.w
|
|
||||||
d.h = body.value.h
|
|
||||||
} else d.fit = true
|
|
||||||
ed.commit(false)
|
ed.commit(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -411,18 +236,8 @@ function setShown(key: string, nested: boolean, on: boolean) {
|
||||||
d.show = [...show]
|
d.show = [...show]
|
||||||
if (!d.hide.length) delete d.hide
|
if (!d.hide.length) delete d.hide
|
||||||
if (!d.show.length) delete d.show
|
if (!d.show.length) delete d.show
|
||||||
if (!on && sel.value === key) pick(null)
|
if (!on && sel.value === key) sel.value = null
|
||||||
ed.commit(false)
|
ed.commit(false)
|
||||||
if (on && nested) {
|
|
||||||
nextTick(() => {
|
|
||||||
const it = items.value.find(x => x.key === key)
|
|
||||||
if (it && !d.place?.[key]) {
|
|
||||||
d.place![key] = { x: it.x, y: it.y - top.value }
|
|
||||||
pick(key)
|
|
||||||
ed.commit(false)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Grows or shrinks the selected item (steps of a quarter), or the size of a text. */
|
/** Grows or shrinks the selected item (steps of a quarter), or the size of a text. */
|
||||||
|
|
@ -435,7 +250,7 @@ function grow(by: number) {
|
||||||
const key = sel.value
|
const key = sel.value
|
||||||
if (!key || !selItem.value) return
|
if (!key || !selItem.value) return
|
||||||
const d = design()
|
const d = design()
|
||||||
const next = Math.min(4, Math.max(0.25, Math.round(((d.scale?.[key] ?? selItem.value.scale ?? 1) + by) * 4) / 4))
|
const next = Math.min(4, Math.max(0.25, Math.round(((d.scale?.[key] ?? 1) + by) * 4) / 4))
|
||||||
d.scale ??= {}
|
d.scale ??= {}
|
||||||
if (next === 1) delete d.scale[key]
|
if (next === 1) delete d.scale[key]
|
||||||
else d.scale[key] = next
|
else d.scale[key] = next
|
||||||
|
|
@ -488,14 +303,7 @@ function toggleFill() {
|
||||||
function setSize(axis: 'w' | 'h', e: Event) {
|
function setSize(axis: 'w' | 'h', e: Event) {
|
||||||
const v = Number((e.target as HTMLInputElement).value)
|
const v = Number((e.target as HTMLInputElement).value)
|
||||||
if (!(v > 0)) return
|
if (!(v > 0)) return
|
||||||
const d = design()
|
design()[axis] = Math.min(120, Math.max(2, Math.round(v * 2) / 2))
|
||||||
// A size typed in: the box keeps it (and what it shows can still make it bigger).
|
|
||||||
if (d.fit) {
|
|
||||||
delete d.fit
|
|
||||||
d.w = body.value.w
|
|
||||||
d.h = body.value.h
|
|
||||||
}
|
|
||||||
d[axis] = Math.min(120, Math.max(2, Math.round(v * 2) / 2))
|
|
||||||
ed.commit(false)
|
ed.commit(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -512,20 +320,9 @@ const textInput = ref<HTMLInputElement>()
|
||||||
onMounted(() => window.addEventListener('keydown', onKey))
|
onMounted(() => window.addEventListener('keydown', onKey))
|
||||||
onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
|
onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
|
||||||
|
|
||||||
const ARROW: Record<string, [number, number]> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }
|
|
||||||
|
|
||||||
function onKey(e: KeyboardEvent) {
|
function onKey(e: KeyboardEvent) {
|
||||||
if ((e.target as HTMLElement).closest?.('input, textarea, select') || e.ctrlKey || e.metaKey || e.altKey) return
|
if ((e.target as HTMLElement).closest?.('input, textarea, select') || e.ctrlKey || e.metaKey || e.altKey) return
|
||||||
const arrow = ARROW[e.key]
|
if ((e.key === 'Delete' || e.key === 'Backspace') && selShape.value) {
|
||||||
if (arrow && (sel.value || group.value.length)) {
|
|
||||||
e.preventDefault()
|
|
||||||
const step = e.shiftKey ? 1 : 0.25
|
|
||||||
nudge(arrow[0] * step, arrow[1] * step)
|
|
||||||
} else if (e.key === 'Escape' && group.value.length) {
|
|
||||||
e.preventDefault()
|
|
||||||
e.stopPropagation()
|
|
||||||
pick(null)
|
|
||||||
} else if ((e.key === 'Delete' || e.key === 'Backspace') && (selShape.value || group.value.some(id => shapes.value.some(s => s.id === id)))) {
|
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
remove()
|
remove()
|
||||||
} else if (e.key === 'r' || e.key === 'R') turn(e.shiftKey ? -90 : 90)
|
} else if (e.key === 'r' || e.key === 'R') turn(e.shiftKey ? -90 : 90)
|
||||||
|
|
@ -548,27 +345,10 @@ const grips = computed(() => {
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|
||||||
const kindName = (it: FaceItem) => (it.screenOf ? 'Pixel' : it.kind === 'screen' ? 'Screen' : it.kind === 'hex' ? 'Display' : 'Lamp')
|
const kindName = (it: FaceItem) => (it.kind === 'screen' ? 'Screen' : it.kind === 'hex' ? 'Display' : 'Lamp')
|
||||||
/** What a thing on the box is, and where from when it is a display of a part inside. */
|
|
||||||
const tipOf = (it: FaceItem) => `${it.label || kindName(it)}${it.from ? ` from ${it.from}` : ''}`
|
|
||||||
|
|
||||||
/** The size grip of the item picked alone: its bottom right corner, sized and turned with it. */
|
|
||||||
const scaleGrip = computed(() => {
|
|
||||||
const it = selItem.value
|
|
||||||
if (!it || group.value.length > 1) return null
|
|
||||||
return { it, x: (it.x + it.w) * G, y: (it.y + it.h) * G, r: 3.5 / (it.scale ?? 1) }
|
|
||||||
})
|
|
||||||
|
|
||||||
/** The box being dragged around things, in grid units from the box's top left. */
|
|
||||||
const pickBox = computed(() => {
|
|
||||||
const d = drag.value
|
|
||||||
if (d?.type !== 'box') return null
|
|
||||||
return { x: Math.min(d.start.x, d.cur.x), y: Math.min(d.start.y, d.cur.y), w: Math.abs(d.cur.x - d.start.x), h: Math.abs(d.cur.y - d.start.y) }
|
|
||||||
})
|
|
||||||
const selLabel = computed(() => {
|
const selLabel = computed(() => {
|
||||||
if (selShape.value) return { line: 'Line', rect: 'Box', ellipse: 'Circle', text: 'Text' }[selShape.value.kind]
|
if (selShape.value) return { line: 'Line', rect: 'Box', ellipse: 'Circle', text: 'Text' }[selShape.value.kind]
|
||||||
if (group.value.length > 1) return `${group.value.length} things`
|
if (selItem.value) return `${kindName(selItem.value)}${selItem.value.label ? ` ${selItem.value.label}` : ''}`
|
||||||
if (selItem.value) return `${kindName(selItem.value)}${selItem.value.label ? ` ${selItem.value.label}` : ''}${selItem.value.from ? ` from ${selItem.value.from}` : ''}`
|
|
||||||
if (sel.value === 'name') return 'The name'
|
if (sel.value === 'name') return 'The name'
|
||||||
if (sel.value?.startsWith('pin:')) return `Pin ${pins.value.find(p => `pin:${p.key}` === sel.value)?.label ?? ''}`
|
if (sel.value?.startsWith('pin:')) return `Pin ${pins.value.find(p => `pin:${p.key}` === sel.value)?.label ?? ''}`
|
||||||
return ''
|
return ''
|
||||||
|
|
@ -607,9 +387,6 @@ const ICON: Record<string, string> = { lamp: 'lucide:lightbulb', hex: 'lucide:bi
|
||||||
<button class="btn-sm" :class="{ on: selShape?.fill ?? fill }" title="Fill boxes and circles lightly" @click="toggleFill">
|
<button class="btn-sm" :class="{ on: selShape?.fill ?? fill }" title="Fill boxes and circles lightly" @click="toggleFill">
|
||||||
<Icon name="lucide:paint-bucket" class="size-3.5" /> Fill
|
<Icon name="lucide:paint-bucket" class="size-3.5" /> Fill
|
||||||
</button>
|
</button>
|
||||||
<button class="btn-sm" :class="{ on: def.design?.fit }" title="The box is as big as what is on it (pins, name, displays, drawings). Off: it keeps the width and height set" @click="toggleFit">
|
|
||||||
<Icon name="lucide:scan" class="size-3.5" /> Fit
|
|
||||||
</button>
|
|
||||||
<label class="face-size">W <input type="number" min="2" max="120" step="0.5" :value="body.w" @change="setSize('w', $event)" /></label>
|
<label class="face-size">W <input type="number" min="2" max="120" step="0.5" :value="body.w" @change="setSize('w', $event)" /></label>
|
||||||
<label class="face-size">H <input type="number" min="2" max="120" step="0.5" :value="body.h" @change="setSize('h', $event)" /></label>
|
<label class="face-size">H <input type="number" min="2" max="120" step="0.5" :value="body.h" @change="setSize('h', $event)" /></label>
|
||||||
<button class="btn-sm ml-auto" :disabled="!def.design" title="Back to the automatic layout; drawings are removed" @click="reset">
|
<button class="btn-sm ml-auto" :disabled="!def.design" title="Back to the automatic layout; drawings are removed" @click="reset">
|
||||||
|
|
@ -646,23 +423,9 @@ const ICON: Record<string, string> = { lamp: 'lucide:lightbulb', hex: 'lucide:bi
|
||||||
:height="it.h * G + 4"
|
:height="it.h * G + 4"
|
||||||
rx="3"
|
rx="3"
|
||||||
class="face-thing"
|
class="face-thing"
|
||||||
:class="{ sel: isSel(it.key), nested: !!it.from }"
|
:class="{ sel: sel === it.key }"
|
||||||
:data-face="it.key"
|
:data-face="it.key"
|
||||||
>
|
/>
|
||||||
<title>{{ tipOf(it) }}</title>
|
|
||||||
</rect>
|
|
||||||
<!-- Its size grip, picked alone: drag to make it bigger or smaller -->
|
|
||||||
<circle
|
|
||||||
v-if="scaleGrip?.it.key === it.key"
|
|
||||||
:cx="scaleGrip.x"
|
|
||||||
:cy="scaleGrip.y"
|
|
||||||
:r="scaleGrip.r"
|
|
||||||
class="face-grip scale"
|
|
||||||
:data-face="it.key"
|
|
||||||
data-handle="scale"
|
|
||||||
>
|
|
||||||
<title>Drag to size</title>
|
|
||||||
</circle>
|
|
||||||
</g>
|
</g>
|
||||||
<rect
|
<rect
|
||||||
v-if="nameBox"
|
v-if="nameBox"
|
||||||
|
|
@ -672,7 +435,7 @@ const ICON: Record<string, string> = { lamp: 'lucide:lightbulb', hex: 'lucide:bi
|
||||||
:height="nameBox.h * G"
|
:height="nameBox.h * G"
|
||||||
rx="3"
|
rx="3"
|
||||||
class="face-thing"
|
class="face-thing"
|
||||||
:class="{ sel: isSel('name') }"
|
:class="{ sel: sel === 'name' }"
|
||||||
data-face="name"
|
data-face="name"
|
||||||
/>
|
/>
|
||||||
<rect
|
<rect
|
||||||
|
|
@ -686,9 +449,7 @@ const ICON: Record<string, string> = { lamp: 'lucide:lightbulb', hex: 'lucide:bi
|
||||||
class="face-thing face-pinbox"
|
class="face-thing face-pinbox"
|
||||||
:class="{ sel: sel === `pin:${p.key}` }"
|
:class="{ sel: sel === `pin:${p.key}` }"
|
||||||
:data-face="`pin:${p.key}`"
|
:data-face="`pin:${p.key}`"
|
||||||
>
|
/>
|
||||||
<title>Drag up or down; past another pin, they swap</title>
|
|
||||||
</rect>
|
|
||||||
<g :transform="`translate(0 ${body.y * G})`">
|
<g :transform="`translate(0 ${body.y * G})`">
|
||||||
<g v-for="s in shapes" :key="s.id" :transform="shapeTransform(s)">
|
<g v-for="s in shapes" :key="s.id" :transform="shapeTransform(s)">
|
||||||
<line
|
<line
|
||||||
|
|
@ -698,7 +459,7 @@ const ICON: Record<string, string> = { lamp: 'lucide:lightbulb', hex: 'lucide:bi
|
||||||
:x2="(s.x + s.w) * G"
|
:x2="(s.x + s.w) * G"
|
||||||
:y2="(s.y + s.h) * G"
|
:y2="(s.y + s.h) * G"
|
||||||
class="face-hit"
|
class="face-hit"
|
||||||
:class="{ sel: isSel(s.id) }"
|
:class="{ sel: sel === s.id }"
|
||||||
:data-face="s.id"
|
:data-face="s.id"
|
||||||
/>
|
/>
|
||||||
<rect
|
<rect
|
||||||
|
|
@ -709,16 +470,15 @@ const ICON: Record<string, string> = { lamp: 'lucide:lightbulb', hex: 'lucide:bi
|
||||||
:height="(s.kind === 'text' ? 1 * (s.size ?? 1) : Math.abs(s.h)) * G + 4"
|
:height="(s.kind === 'text' ? 1 * (s.size ?? 1) : Math.abs(s.h)) * G + 4"
|
||||||
rx="2"
|
rx="2"
|
||||||
class="face-thing shape"
|
class="face-thing shape"
|
||||||
:class="{ sel: isSel(s.id) }"
|
:class="{ sel: sel === s.id }"
|
||||||
:data-face="s.id"
|
:data-face="s.id"
|
||||||
/>
|
/>
|
||||||
</g>
|
</g>
|
||||||
<g v-if="selShape && group.length <= 1" :transform="shapeTransform(selShape)">
|
<g v-if="selShape" :transform="shapeTransform(selShape)">
|
||||||
<circle v-for="g in grips" :key="g.h" :cx="g.x * G" :cy="g.y * G" r="3.5" class="face-grip" :data-face="sel!" :data-handle="g.h" />
|
<circle v-for="g in grips" :key="g.h" :cx="g.x * G" :cy="g.y * G" r="3.5" class="face-grip" :data-face="sel!" :data-handle="g.h" />
|
||||||
</g>
|
</g>
|
||||||
</g>
|
</g>
|
||||||
</g>
|
</g>
|
||||||
<rect v-if="pickBox" :x="PAD + pickBox.x * G * k" :y="PAD + pickBox.y * G * k" :width="pickBox.w * G * k" :height="pickBox.h * G * k" class="face-pickbox" />
|
|
||||||
</svg>
|
</svg>
|
||||||
|
|
||||||
<aside class="face-side">
|
<aside class="face-side">
|
||||||
|
|
@ -761,31 +521,27 @@ const ICON: Record<string, string> = { lamp: 'lucide:lightbulb', hex: 'lucide:bi
|
||||||
<div class="face-props">
|
<div class="face-props">
|
||||||
<template v-if="sel && selLabel">
|
<template v-if="sel && selLabel">
|
||||||
<span class="font-semibold">{{ selLabel }}</span>
|
<span class="font-semibold">{{ selLabel }}</span>
|
||||||
<button v-if="selScreen && group.length <= 1" class="btn-sm" :title="selScreen.split ? 'Back into one screen' : 'Each pixel on its own, to place one by one'" @click="toggleSplit(selScreen.key, !selScreen.split)">
|
<template v-if="selShape || selItem">
|
||||||
<Icon :name="selScreen.split ? 'lucide:grid-2x2' : 'lucide:grid-2x2-plus'" class="size-3.5" /> {{ selScreen.split ? 'Join pixels' : 'Split into pixels' }}
|
|
||||||
</button>
|
|
||||||
<template v-if="(selShape || selItem) && group.length <= 1">
|
|
||||||
<div class="flex gap-1" title="Turn (R, Shift+R)">
|
<div class="flex gap-1" title="Turn (R, Shift+R)">
|
||||||
<button class="icon-btn" @click="turn(-90)"><Icon name="lucide:rotate-ccw" class="size-4" /></button>
|
<button class="icon-btn" @click="turn(-90)"><Icon name="lucide:rotate-ccw" class="size-4" /></button>
|
||||||
<button class="icon-btn" @click="turn(90)"><Icon name="lucide:rotate-cw" class="size-4" /></button>
|
<button class="icon-btn" @click="turn(90)"><Icon name="lucide:rotate-cw" class="size-4" /></button>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="selItem || selShape?.kind === 'text'" class="flex items-center gap-1" title="Size (+, −)">
|
<div v-if="selItem || selShape?.kind === 'text'" class="flex items-center gap-1" title="Size (+, −)">
|
||||||
<button class="icon-btn" @click="grow(-0.25)"><Icon name="lucide:minus" class="size-4" /></button>
|
<button class="icon-btn" @click="grow(-0.25)"><Icon name="lucide:minus" class="size-4" /></button>
|
||||||
<span class="tabular-nums text-xs">{{ Math.round(((selShape ? selShape.size : (def.design?.scale?.[sel] ?? selItem?.scale)) ?? 1) * 100) }}%</span>
|
<span class="tabular-nums text-xs">{{ Math.round(((selShape ? selShape.size : def.design?.scale?.[sel]) ?? 1) * 100) }}%</span>
|
||||||
<button class="icon-btn" @click="grow(0.25)"><Icon name="lucide:plus" class="size-4" /></button>
|
<button class="icon-btn" @click="grow(0.25)"><Icon name="lucide:plus" class="size-4" /></button>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
<template v-if="selShape?.kind === 'text'">
|
<template v-if="selShape?.kind === 'text'">
|
||||||
<input ref="textInput" v-model="selShape.text" class="text-input" placeholder="Text" @change="ed.commit(false)" />
|
<input ref="textInput" v-model="selShape.text" class="text-input" placeholder="Text" @change="ed.commit(false)" />
|
||||||
</template>
|
</template>
|
||||||
<span v-if="group.length > 1" class="hint">Drag one to move them all, or use the arrow keys (Shift: a whole square).</span>
|
<button v-if="selShape" class="btn-sm danger ml-auto" @click="remove"><Icon name="lucide:trash-2" class="size-3.5" /> Delete</button>
|
||||||
<button v-if="selShape || group.some(id => shapes.some(x => x.id === id))" class="btn-sm danger ml-auto" @click="remove"><Icon name="lucide:trash-2" class="size-3.5" /> Delete</button>
|
<button v-else-if="selItem" class="btn-sm ml-auto" @click="setShown(selItem.key, selItem.key.includes('/'), false)">
|
||||||
<button v-else-if="selItem && group.length <= 1" class="btn-sm ml-auto" @click="setShown(selItem.key, selItem.key.includes('/'), false)">
|
|
||||||
<Icon name="lucide:eye-off" class="size-3.5" /> Leave off
|
<Icon name="lucide:eye-off" class="size-3.5" /> Leave off
|
||||||
</button>
|
</button>
|
||||||
<button v-else-if="sel === 'name'" class="btn-sm ml-auto" @click="setShown('name', false, false)"><Icon name="lucide:eye-off" class="size-3.5" /> Leave off</button>
|
<button v-else-if="sel === 'name'" class="btn-sm ml-auto" @click="setShown('name', false, false)"><Icon name="lucide:eye-off" class="size-3.5" /> Leave off</button>
|
||||||
</template>
|
</template>
|
||||||
<span v-else class="hint">Drag things on the box; Shift + click or a box around them picks several. The corner of a picked thing sizes it. R turns, + and − size, Delete removes a drawing.</span>
|
<span v-else class="hint">Pick a tool to draw, or drag things on the box. R turns, + and − size, Delete removes a drawing.</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
<script setup lang="ts">
|
|
||||||
// A folding group in a side panel. It remembers, per group, whether you
|
|
||||||
// left it open, so the panel stays as short as you like it.
|
|
||||||
const props = defineProps<{ title: string; id: string; open?: boolean; /** Short note after the title, like a count. */ note?: string }>()
|
|
||||||
|
|
||||||
const KEY = `logigate:fold:${props.id}`
|
|
||||||
const isOpen = ref(props.open ?? false)
|
|
||||||
try {
|
|
||||||
const saved = localStorage.getItem(KEY)
|
|
||||||
if (saved !== null) isOpen.value = saved === '1'
|
|
||||||
} catch {}
|
|
||||||
|
|
||||||
function toggle() {
|
|
||||||
isOpen.value = !isOpen.value
|
|
||||||
try {
|
|
||||||
localStorage.setItem(KEY, isOpen.value ? '1' : '0')
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div class="fold" :class="{ open: isOpen }">
|
|
||||||
<button class="fold-head" :aria-expanded="isOpen" @click="toggle">
|
|
||||||
<Icon name="lucide:chevron-right" class="fold-chev size-3.5" />
|
|
||||||
<span class="grow">{{ title }}</span>
|
|
||||||
<span v-if="note" class="fold-note">{{ note }}</span>
|
|
||||||
</button>
|
|
||||||
<div v-if="isOpen" class="fold-body"><slot /></div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
@ -2,14 +2,12 @@
|
||||||
const ed = useEditor()
|
const ed = useEditor()
|
||||||
|
|
||||||
const SHORTCUTS: [string, string][] = [
|
const SHORTCUTS: [string, string][] = [
|
||||||
['Esc (nothing selected)', 'Pause menu: save, save as copy, load, settings, main menu'],
|
|
||||||
['Click switch', 'Flip an input between 0 and 1 (give it a keyboard key in its settings)'],
|
['Click switch', 'Flip an input between 0 and 1 (give it a keyboard key in its settings)'],
|
||||||
['Click anything', 'A panel on the right shows its settings and what you can do with it: swap the part, clock speed, colours, keys, position'],
|
['Click anything', 'Its settings appear on the right: swap the part, clock speed, colours, keys, position'],
|
||||||
['Select several', 'Change them all at once: swap, rename D0, D1, …, switch all to 0 or 1, line up'],
|
['Select several', 'Change them all at once: swap, rename D0, D1, …, switch all to 0 or 1, line up'],
|
||||||
['Pins (panel on the left)', 'Every input and output in one list: rename them one after another with Enter'],
|
['Pins tab (right)', 'Every input and output in one list: rename them one after another with Enter'],
|
||||||
['Drag from a pin', 'Draw a wire to another pin; dropping it on a part uses that part’s next free pin'],
|
['Drag from a pin', 'Draw a wire to another pin; dropping it on a part uses that part’s next free pin'],
|
||||||
['Click a pin, then another', 'The same without holding the mouse button'],
|
['Click a pin, then another', 'The same without holding the mouse button'],
|
||||||
['Shift + click (or let go) on a pin while wiring', 'Connects it and keeps wiring from the same signal: click more pins, Esc stops'],
|
|
||||||
['Select parts, then W', 'Connect one by one: click where each of their pins goes, in order (Shift+W: their inputs)'],
|
['Select parts, then W', 'Connect one by one: click where each of their pins goes, in order (Shift+W: their inputs)'],
|
||||||
['Drag a wire segment', 'Move that segment; drag a corner square to move a bend'],
|
['Drag a wire segment', 'Move that segment; drag a corner square to move a bend'],
|
||||||
['Alt + drag a wire', 'Pull a new bend out of it'],
|
['Alt + drag a wire', 'Pull a new bend out of it'],
|
||||||
|
|
@ -17,7 +15,6 @@ const SHORTCUTS: [string, string][] = [
|
||||||
['Double-click a wire', 'Select the whole signal'],
|
['Double-click a wire', 'Select the whole signal'],
|
||||||
['Shift + click', 'Add parts or wires to the selection'],
|
['Shift + click', 'Add parts or wires to the selection'],
|
||||||
['Arrow keys', 'Move the selection one step (Shift: four)'],
|
['Arrow keys', 'Move the selection one step (Shift: four)'],
|
||||||
['Drag several parts', 'Wires between them keep their shape; a wire to a part that stays keeps its bends while they stay clear of parts and other wires'],
|
|
||||||
['Double-click a component', 'Open it and see inside'],
|
['Double-click a component', 'Open it and see inside'],
|
||||||
['Drag on empty space', 'Select parts; across wires (no parts in the box) it selects every wire it crosses'],
|
['Drag on empty space', 'Select parts; across wires (no parts in the box) it selects every wire it crosses'],
|
||||||
['Drag right to left', 'Select everything the box touches, parts and wires (green box)'],
|
['Drag right to left', 'Select everything the box touches, parts and wires (green box)'],
|
||||||
|
|
@ -25,24 +22,9 @@ const SHORTCUTS: [string, string][] = [
|
||||||
['Right or middle drag, Space + drag', 'Move the view'],
|
['Right or middle drag, Space + drag', 'Move the view'],
|
||||||
['Mouse wheel', 'Zoom'],
|
['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'],
|
['N, I, O, L, B, C, H, T, P, X', 'Place NAND, input, output, lamp, button, clock, hex display, note, input panel, pixel'],
|
||||||
['Bar at the bottom', 'Point at a kind of part to see them all; click to place, drag onto the canvas, pin the ones you use most to the bar itself (right-click a pinned part to unpin it)'],
|
|
||||||
['Mouse back / forward buttons, Alt + ← →', 'Back and forward through the circuits you went into and out of, like pages in the browser (the browser\'s own buttons do the same)'],
|
|
||||||
['Main (top bar)','Back to the main circuit; the names after it lead back to each component you entered (on a narrow bar the ones in between fold into …)'],
|
|
||||||
['Power off and on (circuit name in the top bar, or Space)', 'Latches, flip-flops and memory keep their bits when you go into a component and back, and in the saved project; this starts the circuit again from all zeros'],
|
|
||||||
['⋯ (top bar, small window)', 'Sound, settings, help and whatever else no longer fits in the bar'],
|
|
||||||
['[', 'Hide or show the panel on the left (This and Pins)'],
|
|
||||||
['Library (bottom bar: Components, or Space)', 'Components everyone published: search, add one to this project (what it uses comes along; not in a campaign) and place it. Publish your own, or a new version, from the menu on the circuit’s name'],
|
|
||||||
['Connectors (bottom bar)', 'Make a cable type of your own (HDMI, RJ45): its lines; place its Out and In ports; one cable joins them'],
|
|
||||||
['Split into lines (right-click a component)', 'A pin per line below a port\'s socket, to wire lines by hand; dropping a wire on the socket does the same. Join lines takes them away'],
|
|
||||||
['Select wires, Ctrl+G', 'Bundle them into one cable; an end whose wires all meet one part plugs straight into it'],
|
['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 plug on S0–S3 (or any group); drag the cable out of its pin and let go where it goes, or on the next part\'s pins'],
|
['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'],
|
||||||
['Point at a part', 'Its round buttons show, as if it were selected: cable plugs, split ports, plug in or out'],
|
|
||||||
['Drag a box around some pins of a part, or Shift + click pins', 'Picks exactly those pins: a cable plug on them, wire them one by one, invert or unwire them (buttons beside them, or right-click)'],
|
|
||||||
['Right-click a pin', 'What can be done right there: split a cable socket into wires, pull a cable out, invert an input'],
|
|
||||||
['Drag a docked panel up or down', 'It lets go of its component and stays a panel of its own; sideways it stays docked'],
|
|
||||||
['Round buttons beside the selection', 'Split a port into wires (or join them), pull a cable out of a plug, plug in or out, split a cable into wires, bundle selected wires'],
|
|
||||||
['Drag a part from the list onto pins', 'It lands on them and connects (green rings show where); Alt just places it'],
|
['Drag a part from the list onto pins', 'It lands on them and connects (green rings show where); Alt just places it'],
|
||||||
['Drag a part onto the pins it is wired to', 'When its pins line up with theirs one for one, it latches on (green rings): pins touching, no wires, and it moves with that part. Right-click: Latch onto / Unlatch'],
|
|
||||||
['Drag a plugged cable end away', 'Pull it out; drop its pins on a part\'s pins to plug it in again'],
|
['Drag a plugged cable end away', 'Pull it out; drop its pins on a part\'s pins to plug it in again'],
|
||||||
['Drag a part onto a pin', 'Connects there when dropped (a green ring shows where); hold Alt to just place it'],
|
['Drag a part onto a pin', 'Connects there when dropped (a green ring shows where); hold Alt to just place it'],
|
||||||
['Drag a wire by its end', 'Moves that end to another pin (grab it near the pin, or by the small circle)'],
|
['Drag a wire by its end', 'Moves that end to another pin (grab it near the pin, or by the small circle)'],
|
||||||
|
|
@ -50,20 +32,18 @@ const SHORTCUTS: [string, string][] = [
|
||||||
['Alt + click an input pin', 'Inverts it (a bubble); counted honestly as one NAND'],
|
['Alt + click an input pin', 'Inverts it (a bubble); counted honestly as one NAND'],
|
||||||
['Send signal / Use signal', 'Name a signal (CLK, RESET) once and use it anywhere in the circuit without a wire'],
|
['Send signal / Use signal', 'Name a signal (CLK, RESET) once and use it anywhere in the circuit without a wire'],
|
||||||
['Ctrl+F', 'Find a part, signal or component in every circuit, and where a component is used'],
|
['Ctrl+F', 'Find a part, signal or component in every circuit, and where a component is used'],
|
||||||
['Space (tap)', 'Search at the mouse: recent parts and actions like a new component; type a few letters, arrows to choose, Enter to take it'],
|
['Shift+A or Ctrl+K', 'Add a part at the mouse: type a few letters, arrows to choose, Enter to place'],
|
||||||
['Shift+Enter in the search', 'Open the chosen component to edit it instead of placing it (or click its pencil); typing any circuit\'s name also offers "Open …"'],
|
['/', 'Search the parts list; Enter starts placing the one chosen'],
|
||||||
['/, Shift+A or Ctrl+K', 'The same search box'],
|
|
||||||
['Ctrl+P', 'Print the circuit as a sheet with a title block, or save it as PDF'],
|
['Ctrl+P', 'Print the circuit as a sheet with a title block, or save it as PDF'],
|
||||||
['Select switches or buttons, Combine', 'One input panel (all rows can become buttons); lamps or output pins combine into an output panel'],
|
['Select switches or buttons, Combine', 'One input panel (all rows can become buttons); lamps or output pins combine into an output panel'],
|
||||||
['Select panels, Merge', 'One panel with all their rows; inside a component input panel rows are inputs, output panel rows outputs'],
|
['Select panels, Merge', 'One panel with all their rows; inside a component input panel rows are inputs, output panel rows outputs'],
|
||||||
['Design the box (This, As a component)', 'Move lamps, displays and the name on a component\'s box, draw lines, boxes, circles and text'],
|
['Design the box (Circuit tab)', 'Move lamps, displays and the name on a component\'s box, draw lines, boxes, circles and text'],
|
||||||
['Select several lamps, pins or switches', 'Green boxes show free pins in a row they fit; point along one, click to wire them all'],
|
['Select several lamps, pins or switches', 'Green boxes show free pins in a row they fit; point along one, click to wire them all'],
|
||||||
['Shift + click on canvas', 'Keep placing the same part'],
|
['Shift + click on canvas', 'Keep placing the same part'],
|
||||||
['Ctrl+C, Ctrl+V, Ctrl+D', 'Copy, paste, duplicate; names continue their series (D0 → D1)'],
|
['Ctrl+C, Ctrl+V, Ctrl+D', 'Copy, paste, duplicate; names continue their series (D0 → D1)'],
|
||||||
['Delete', 'Remove the selection'],
|
['Delete', 'Remove the selection'],
|
||||||
['Ctrl+Z, Ctrl+Shift+Z', 'Undo, redo'],
|
['Ctrl+Z, Ctrl+Shift+Z', 'Undo, redo'],
|
||||||
['Logo (top left), Esc', 'Pause menu: save, load, settings, back to the main menu. Your work is saved'],
|
['Logo (top left)', 'Back to the main menu: free play, campaign, challenges, leaderboard. Your work is saved'],
|
||||||
['Tidy this circuit / every circuit', 'In the Circuit panel (Tools) or with Space: hand-placed bends go, every wire is laid out anew around the parts. Ctrl+Z undoes it'],
|
|
||||||
['F', 'Fit the circuit to the screen'],
|
['F', 'Fit the circuit to the screen'],
|
||||||
['Enter', 'Open the selected component'],
|
['Enter', 'Open the selected component'],
|
||||||
]
|
]
|
||||||
|
|
@ -94,10 +74,10 @@ function close() {
|
||||||
<strong>It runs while you draw.</strong> Green wires carry a 1, grey wires a 0. Flip switches, press buttons, or start the clock in the top bar.
|
<strong>It runs while you draw.</strong> Green wires carry a 1, grey wires a 0. Flip switches, press buttons, or start the clock in the top bar.
|
||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<strong>Try the challenges</strong> (top bar), or open the examples (NOT up to a 4-bit counter) to see how each step is made of the previous one.
|
<strong>Try the challenges</strong> on the left, or open the examples (NOT up to a 4-bit counter) to see how each step is made of the previous one.
|
||||||
</li>
|
</li>
|
||||||
<li>
|
<li>
|
||||||
<strong>Select parts and press "Make component"</strong> in the panel on the right to turn a piece of your drawing into a reusable block.
|
<strong>Select parts and press "Make component"</strong> on the right to turn a piece of your drawing into a reusable block.
|
||||||
</li>
|
</li>
|
||||||
</ol>
|
</ol>
|
||||||
<h3>Controls</h3>
|
<h3>Controls</h3>
|
||||||
|
|
|
||||||
|
|
@ -1,67 +1,109 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
// The panel on the left, about the circuit you are in: "This" (its name,
|
// The panel on the right, floating over the canvas: tabs for the selection,
|
||||||
// check, challenge, truth table, statistics and tools) and its Pins.
|
// the circuit, its pins, and testing. It opens on its own while something is
|
||||||
|
// selected (like a building's info panel in a city builder); the pin keeps it
|
||||||
|
// open, and opening a challenge pins it on its Test tab.
|
||||||
import { ioList } from '~/lib/logic/bulk'
|
import { ioList } from '~/lib/logic/bulk'
|
||||||
|
|
||||||
const ed = useEditor()
|
const ed = useEditor()
|
||||||
type Tab = 'circuit' | 'pins'
|
type Tab = 'selection' | 'circuit' | 'pins' | 'test'
|
||||||
|
|
||||||
|
const single = computed(() =>
|
||||||
|
ed.selection.value.length === 1 && !ed.wireSel.value.length ? ed.def.value.nodes.find(n => n.id === ed.selection.value[0]) : undefined,
|
||||||
|
)
|
||||||
|
const selected = computed(() => ed.selection.value.length + ed.wireSel.value.length)
|
||||||
const pinCount = computed(() => {
|
const pinCount = computed(() => {
|
||||||
const io = ioList(ed.def.value)
|
const io = ioList(ed.def.value)
|
||||||
return io.inputs.length + io.outputs.length
|
return io.inputs.length + io.outputs.length
|
||||||
})
|
})
|
||||||
const hasTask = computed(() => !!ed.task.value)
|
const hasTask = computed(() => !!ed.task.value)
|
||||||
/** Errors and warnings in the open circuit, on the This tab. */
|
|
||||||
|
function close() {
|
||||||
|
ed.toggleSidebar('right', false)
|
||||||
|
ed.selection.value = []
|
||||||
|
ed.wireSel.value = []
|
||||||
|
}
|
||||||
|
/** Errors and warnings in the open circuit, on the Circuit tab. */
|
||||||
const problems = computed(() => ed.issues.value.filter(i => i.level !== 'info').length)
|
const problems = computed(() => ed.issues.value.filter(i => i.level !== 'info').length)
|
||||||
|
|
||||||
const tabs = computed(() => [
|
const tabs = computed(() => [
|
||||||
{ id: 'circuit' as Tab, label: 'This', icon: hasTask.value ? 'lucide:flag' : 'lucide:cpu', badge: problems.value || '', warn: problems.value > 0 },
|
{ id: 'selection' as Tab, label: 'Selection', icon: 'lucide:mouse-pointer-2', badge: selected.value || '' },
|
||||||
{ id: 'pins' as Tab, label: 'Pins', icon: 'lucide:list', badge: pinCount.value || '', warn: false },
|
{ id: 'circuit' as Tab, label: 'Circuit', icon: 'lucide:cpu', badge: problems.value || '', warn: problems.value > 0 },
|
||||||
|
{ id: 'pins' as Tab, label: 'Pins', icon: 'lucide:list', badge: pinCount.value || '' },
|
||||||
|
{ id: 'test' as Tab, label: 'Test', icon: hasTask.value ? 'lucide:flag' : 'lucide:table', badge: '' },
|
||||||
])
|
])
|
||||||
|
|
||||||
// Renaming with nothing selected renames the circuit; opening a challenge shows what to build.
|
// Selecting something shows its settings, unless you are working in Pins or
|
||||||
|
// Test (where clicking a switch to try the circuit also selects it).
|
||||||
|
let before: Tab = 'circuit'
|
||||||
|
watch(selected, (now, was) => {
|
||||||
|
const tab = ed.rightTab.value
|
||||||
|
if (now && !was && (tab === 'circuit' || !ed.sidebars.right)) {
|
||||||
|
before = tab
|
||||||
|
ed.rightTab.value = 'selection'
|
||||||
|
} else if (!now && tab === 'selection') ed.rightTab.value = before
|
||||||
|
})
|
||||||
watch(
|
watch(
|
||||||
() => ed.labelFocus.value,
|
() => ed.labelFocus.value,
|
||||||
() => {
|
() => {
|
||||||
if (!ed.selection.value.length) ed.panelTab.value = 'circuit'
|
if (selected.value) ed.rightTab.value = 'selection'
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
// Opening a challenge or puzzle shows what to build.
|
||||||
watch(
|
watch(
|
||||||
() => ed.def.value.id,
|
() => ed.def.value.id,
|
||||||
() => {
|
() => {
|
||||||
if (ed.task.value) ed.panelTab.value = 'circuit'
|
if (ed.task.value) {
|
||||||
|
ed.rightTab.value = 'test'
|
||||||
|
ed.toggleSidebar('right', true)
|
||||||
|
} else if (ed.rightTab.value === 'test') ed.rightTab.value = 'circuit'
|
||||||
},
|
},
|
||||||
|
{ immediate: true },
|
||||||
)
|
)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<aside class="inspector">
|
<aside class="inspector">
|
||||||
<div class="panel-head">
|
<nav class="itabs" role="tablist">
|
||||||
<nav class="seg-tabs" role="tablist">
|
|
||||||
<button
|
<button
|
||||||
v-for="t in tabs"
|
v-for="t in tabs"
|
||||||
:key="t.id"
|
:key="t.id"
|
||||||
role="tab"
|
role="tab"
|
||||||
:aria-selected="ed.panelTab.value === t.id"
|
:aria-selected="ed.rightTab.value === t.id"
|
||||||
:class="{ active: ed.panelTab.value === t.id, task: t.id === 'circuit' && hasTask }"
|
:class="{ active: ed.rightTab.value === t.id, task: t.id === 'test' && hasTask }"
|
||||||
:title="t.id === 'circuit' ? 'The circuit you are in' : 'Its inputs and outputs'"
|
:title="t.label"
|
||||||
@click="ed.panelTab.value = t.id"
|
@click="ed.rightTab.value = t.id"
|
||||||
>
|
>
|
||||||
<Icon :name="t.icon" class="size-4 shrink-0" />
|
<Icon :name="t.icon" class="size-4 shrink-0" />
|
||||||
<span class="label">{{ t.label }}</span>
|
<span class="label">{{ t.label }}</span>
|
||||||
<span v-if="t.badge" class="badge" :class="{ warn: t.warn }">{{ t.badge }}</span>
|
<span v-if="t.badge" class="badge" :class="{ warn: 'warn' in t && t.warn }">{{ t.badge }}</span>
|
||||||
</button>
|
</button>
|
||||||
</nav>
|
<div class="itabs-tools">
|
||||||
<button class="icon-btn" title="Hide this panel ([)" @click="ed.togglePanel(false)">
|
<button
|
||||||
<Icon name="lucide:panel-left-close" class="size-4" />
|
class="collapse-btn"
|
||||||
|
:class="{ active: ed.sidebars.right }"
|
||||||
|
:title="ed.sidebars.right ? 'Kept open; click to let it close with the selection (])' : 'Keep this panel open (])'"
|
||||||
|
@click="ed.toggleSidebar('right')"
|
||||||
|
>
|
||||||
|
<Icon :name="ed.sidebars.right ? 'lucide:pin' : 'lucide:pin-off'" class="size-3.5" />
|
||||||
</button>
|
</button>
|
||||||
|
<button class="collapse-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
|
||||||
</div>
|
</div>
|
||||||
|
</nav>
|
||||||
<div class="scroll">
|
<div class="scroll">
|
||||||
<template v-if="ed.panelTab.value === 'circuit'">
|
<template v-if="ed.rightTab.value === 'selection'">
|
||||||
<EditorTestPane part="task" />
|
<EditorNodeSettings v-if="single" :key="single.id" :node="single" />
|
||||||
<EditorCircuitPane />
|
<EditorBulkSettings v-else-if="ed.selection.value.length" />
|
||||||
|
<EditorWireSettings v-else-if="ed.wireSel.value.length" />
|
||||||
|
<section v-else class="empty-pane">
|
||||||
|
<Icon name="lucide:mouse-pointer-click" class="size-6" />
|
||||||
|
<p>Click a part or wire to change it.</p>
|
||||||
|
<p class="hint">Shift + click or drag a box to select several; you can then rename, swap or switch them all at once.</p>
|
||||||
|
</section>
|
||||||
</template>
|
</template>
|
||||||
<EditorPinsPane v-else />
|
<EditorCircuitPane v-else-if="ed.rightTab.value === 'circuit'" />
|
||||||
|
<EditorPinsPane v-else-if="ed.rightTab.value === 'pins'" />
|
||||||
|
<EditorTestPane v-else />
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
</template>
|
</template>
|
||||||
|
|
|
||||||
|
|
@ -1,170 +0,0 @@
|
||||||
<script setup lang="ts">
|
|
||||||
// The public library: components everyone published, newest first. Type to
|
|
||||||
// search names, descriptions and authors. "Add" brings one into the open
|
|
||||||
// project with everything it uses and starts placing it; entries published
|
|
||||||
// from this browser can be taken out again. A campaign can look, not add.
|
|
||||||
import { shortCount } from '~/lib/logic/analyze'
|
|
||||||
import { importProblem, type LibraryMeta } from '~/lib/logic/library'
|
|
||||||
|
|
||||||
const ed = useEditor()
|
|
||||||
const { place } = usePlace()
|
|
||||||
const close = () => (ed.dialog.value = null)
|
|
||||||
|
|
||||||
const query = ref('')
|
|
||||||
const entries = ref<LibraryMeta[] | null>(null)
|
|
||||||
const total = ref(0)
|
|
||||||
const error = ref('')
|
|
||||||
const busy = ref('')
|
|
||||||
const confirmRemove = ref('')
|
|
||||||
const input = ref<HTMLInputElement>()
|
|
||||||
|
|
||||||
// Only the answer to the latest search counts.
|
|
||||||
let asked = 0
|
|
||||||
let timer: ReturnType<typeof setTimeout> | undefined
|
|
||||||
async function load() {
|
|
||||||
const n = ++asked
|
|
||||||
try {
|
|
||||||
const res = await ed.listLibrary(query.value)
|
|
||||||
if (n !== asked) return
|
|
||||||
entries.value = res.entries
|
|
||||||
total.value = res.total
|
|
||||||
error.value = ''
|
|
||||||
} catch (e) {
|
|
||||||
if (n === asked) error.value = `Could not load the library: ${(e as Error).message}`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
watch(query, () => {
|
|
||||||
clearTimeout(timer)
|
|
||||||
timer = setTimeout(load, 250)
|
|
||||||
})
|
|
||||||
onMounted(() => {
|
|
||||||
void load()
|
|
||||||
input.value?.focus()
|
|
||||||
})
|
|
||||||
onBeforeUnmount(() => clearTimeout(timer))
|
|
||||||
|
|
||||||
const date = (t: number) => new Date(t).toLocaleDateString()
|
|
||||||
|
|
||||||
/** A box with a stub per pin (16 a side at most), inputs left and outputs right. */
|
|
||||||
function thumb(m: LibraryMeta) {
|
|
||||||
const ins = Math.min(m.inputs, 16)
|
|
||||||
const outs = Math.min(m.outputs, 16)
|
|
||||||
const rows = Math.max(1, ins, outs)
|
|
||||||
const at = (n: number) => Array.from({ length: n }, (_, i) => 1 + i + (rows - n) / 2)
|
|
||||||
return { box: `0 0 8 ${rows + 1}`, h: rows, ins: at(ins), outs: at(outs) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Pin names for a tooltip, with a mark when there are more than the listing keeps. */
|
|
||||||
const pinList = (names: string[], n: number) => names.join(', ') + (n > names.length ? ', …' : '')
|
|
||||||
|
|
||||||
/** The entries with their pictures, and whether they are yours. */
|
|
||||||
const shown = computed(() => (entries.value ?? []).map(m => ({ m, t: thumb(m), mine: m.id in ed.libKeys.value })))
|
|
||||||
|
|
||||||
/** Why nothing can be added to this project (a campaign); null when it can. */
|
|
||||||
const blocked = computed(() => importProblem(ed.project.value))
|
|
||||||
|
|
||||||
async function add(m: LibraryMeta) {
|
|
||||||
busy.value = m.id
|
|
||||||
error.value = ''
|
|
||||||
try {
|
|
||||||
const root = await ed.addFromLibrary(m.id)
|
|
||||||
close()
|
|
||||||
if (ed.screen.value === 'menu') ed.enterGame()
|
|
||||||
place('chip', root)
|
|
||||||
} catch (e) {
|
|
||||||
error.value = (e as Error).message
|
|
||||||
} finally {
|
|
||||||
busy.value = ''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function remove(m: LibraryMeta) {
|
|
||||||
if (confirmRemove.value !== m.id) return (confirmRemove.value = m.id)
|
|
||||||
confirmRemove.value = ''
|
|
||||||
busy.value = m.id
|
|
||||||
error.value = ''
|
|
||||||
try {
|
|
||||||
await ed.removeFromLibrary(m.id)
|
|
||||||
entries.value = entries.value?.filter(e => e.id !== m.id) ?? null
|
|
||||||
total.value--
|
|
||||||
ed.notify(`"${m.name}" is out of the library. Projects that added it keep their copy.`)
|
|
||||||
} catch (e) {
|
|
||||||
error.value = (e as Error).message
|
|
||||||
} finally {
|
|
||||||
busy.value = ''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function onKey(e: KeyboardEvent) {
|
|
||||||
if (e.key !== 'Escape') return
|
|
||||||
e.stopPropagation()
|
|
||||||
close()
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div class="modal-backdrop" @click.self="close">
|
|
||||||
<div class="modal library-modal" role="dialog" aria-labelledby="library-title" @keydown="onKey">
|
|
||||||
<div class="flex items-start justify-between gap-4">
|
|
||||||
<h2 id="library-title">Library</h2>
|
|
||||||
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
|
|
||||||
</div>
|
|
||||||
<p class="hint mt-1">
|
|
||||||
Components everyone published. Add one to "{{ ed.project.value.name }}": it comes with every component it uses, ready to place. To publish your own,
|
|
||||||
open it and use the menu on its name.
|
|
||||||
</p>
|
|
||||||
<div class="search part-search mt-3">
|
|
||||||
<Icon name="lucide:search" class="size-3.5 text-(--muted)" />
|
|
||||||
<input ref="input" v-model="query" placeholder="Search by name, description or author…" />
|
|
||||||
</div>
|
|
||||||
<p v-if="blocked" class="hint mt-2">{{ blocked }}.</p>
|
|
||||||
<p v-if="error" class="result fail"><Icon name="lucide:circle-x" class="size-4 shrink-0" /> {{ error }}</p>
|
|
||||||
|
|
||||||
<p v-if="entries === null" class="hint mt-3">{{ error ? '' : 'Loading…' }}</p>
|
|
||||||
<p v-else-if="!entries.length" class="hint mt-3">
|
|
||||||
{{ query.trim() ? `Nothing called "${query.trim()}" yet.` : 'Nothing published yet. Be the first: open a component and publish it from the menu on its name.' }}
|
|
||||||
</p>
|
|
||||||
<ul v-else class="lib-list">
|
|
||||||
<li v-for="{ m, t, mine } in shown" :key="m.id" class="lib-entry">
|
|
||||||
<svg class="lib-thumb" :viewBox="t.box" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
|
|
||||||
<line v-for="(y, i) in t.ins" :key="`i${i}`" x1="0.6" :y1="y" x2="2" :y2="y" />
|
|
||||||
<line v-for="(y, i) in t.outs" :key="`o${i}`" x1="6" :y1="y" x2="7.4" :y2="y" />
|
|
||||||
<rect x="2" y="0.5" width="4" :height="t.h" rx="0.4" />
|
|
||||||
</svg>
|
|
||||||
<div class="lib-main">
|
|
||||||
<div class="lib-title">
|
|
||||||
<span class="truncate">{{ m.name }}</span>
|
|
||||||
<span v-if="mine" class="you-tag">yours</span>
|
|
||||||
</div>
|
|
||||||
<div class="lib-by">by {{ m.author || 'Anonymous' }} · version {{ m.version }} · {{ date(m.updated) }}</div>
|
|
||||||
<p v-if="m.description" class="lib-desc">{{ m.description }}</p>
|
|
||||||
<div class="lib-stats">
|
|
||||||
<span title="Transistors at every depth, 4 per NAND">{{ shortCount(m.transistors) }} transistors</span>
|
|
||||||
<span :title="pinList(m.inNames, m.inputs)">{{ m.inputs }} in</span>
|
|
||||||
<span :title="pinList(m.outNames, m.outputs)">{{ m.outputs }} out</span>
|
|
||||||
<span v-if="m.uses" title="Components it uses; they come along">{{ m.uses }} inside</span>
|
|
||||||
<span v-if="m.connectors">{{ m.connectors }} connector {{ m.connectors === 1 ? 'type' : 'types' }}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="lib-actions">
|
|
||||||
<button class="btn btn-primary" :disabled="!!busy || !!blocked" :title="blocked ?? 'Add it to this project and place it'" @click="add(m)">
|
|
||||||
<Icon name="lucide:plus" class="size-4" /> {{ busy === m.id ? 'Adding…' : 'Add' }}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
v-if="mine"
|
|
||||||
class="btn-sm"
|
|
||||||
:class="{ danger: confirmRemove === m.id }"
|
|
||||||
:disabled="!!busy"
|
|
||||||
:title="confirmRemove === m.id ? 'Click again to take it out of the library' : 'Take it out of the library; copies others added stay theirs'"
|
|
||||||
@click="remove(m)"
|
|
||||||
@pointerleave="confirmRemove === m.id && (confirmRemove = '')"
|
|
||||||
>
|
|
||||||
{{ confirmRemove === m.id ? 'Remove?' : 'Remove' }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
<p v-if="entries && !query.trim() && total > entries.length" class="hint mt-2">The newest {{ entries.length }} of {{ total }}. Search to find the others.</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
@ -1,137 +0,0 @@
|
||||||
<script setup lang="ts">
|
|
||||||
// Publishing the open circuit to the library: its name and description as
|
|
||||||
// everyone will see them, your name, and what goes along with it. Published
|
|
||||||
// from this browser before, it goes up as a new version of the same entry.
|
|
||||||
import { shortCount } from '~/lib/logic/analyze'
|
|
||||||
import { chipPins } from '~/lib/logic/geometry'
|
|
||||||
import { LIBRARY_LIMITS, libraryBundle } from '~/lib/logic/library'
|
|
||||||
import type { LibraryOrigin } from '~/lib/logic/types'
|
|
||||||
|
|
||||||
const ed = useEditor()
|
|
||||||
const close = () => (ed.dialog.value = null)
|
|
||||||
|
|
||||||
const def = ed.def
|
|
||||||
/** The entry this is a new version of, when this browser published it before. */
|
|
||||||
const own = ed.ownEntry(def.value)
|
|
||||||
const name = ref(def.value.name)
|
|
||||||
const description = ref(def.value.description ?? '')
|
|
||||||
const author = ref(ed.playerName.value)
|
|
||||||
const busy = ref(false)
|
|
||||||
const error = ref('')
|
|
||||||
const done = ref<LibraryOrigin | null>(null)
|
|
||||||
const confirmRemove = ref(false)
|
|
||||||
|
|
||||||
const pins = computed(() => chipPins(def.value))
|
|
||||||
|
|
||||||
/** A list of names, the first few spelled out. */
|
|
||||||
const names = (list: string[]) => (list.length > 6 ? `${list.slice(0, 6).join(', ')} and ${list.length - 6} more` : list.join(', '))
|
|
||||||
|
|
||||||
/** What goes along with it, in words, and whether it all fits. */
|
|
||||||
const along = computed(() => {
|
|
||||||
const b = libraryBundle(ed.project.value, def.value.id)
|
|
||||||
const uses = b.components.filter(d => d.id !== b.root).map(d => d.name)
|
|
||||||
const types = (b.connectors ?? []).map(c => c.name)
|
|
||||||
const parts = [
|
|
||||||
uses.length ? `the ${uses.length === 1 ? 'component' : `${uses.length} components`} it uses (${names(uses)})` : '',
|
|
||||||
types.length ? `${types.length === 1 ? 'the connector type' : 'the connector types'} ${names(types)}` : '',
|
|
||||||
].filter(Boolean)
|
|
||||||
const text = parts.length ? `Goes along: ${parts.join(' and ')}.` : 'It uses no other components.'
|
|
||||||
return { text, tooLarge: JSON.stringify(b).length > LIBRARY_LIMITS.bytes }
|
|
||||||
})
|
|
||||||
const problem = computed(() => ed.libraryProblem.value ?? (along.value.tooLarge ? 'Too large for the library (1 MB at most)' : null))
|
|
||||||
|
|
||||||
async function publish() {
|
|
||||||
busy.value = true
|
|
||||||
error.value = ''
|
|
||||||
try {
|
|
||||||
done.value = await ed.publishToLibrary(name.value, description.value, author.value)
|
|
||||||
ed.play('unlock')
|
|
||||||
} catch (e) {
|
|
||||||
error.value = (e as Error).message
|
|
||||||
} finally {
|
|
||||||
busy.value = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function remove() {
|
|
||||||
if (!confirmRemove.value) return (confirmRemove.value = true)
|
|
||||||
busy.value = true
|
|
||||||
error.value = ''
|
|
||||||
try {
|
|
||||||
await ed.removeFromLibrary(own!)
|
|
||||||
ed.notify(`"${def.value.name}" is out of the library. Projects that added it keep their copy.`)
|
|
||||||
close()
|
|
||||||
} catch (e) {
|
|
||||||
error.value = (e as Error).message
|
|
||||||
} finally {
|
|
||||||
busy.value = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function onKey(e: KeyboardEvent) {
|
|
||||||
if (e.key !== 'Escape') return
|
|
||||||
e.stopPropagation()
|
|
||||||
close()
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div class="modal-backdrop" @click.self="close">
|
|
||||||
<div class="modal" role="dialog" aria-labelledby="lib-publish-title" @keydown="onKey">
|
|
||||||
<div class="flex items-start justify-between gap-4">
|
|
||||||
<h2 id="lib-publish-title">{{ own ? 'Update in the library' : 'Publish to the library' }}</h2>
|
|
||||||
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<template v-if="!done">
|
|
||||||
<p class="hint mt-1">
|
|
||||||
<template v-if="own">It goes up as the next version of your entry; projects that added it before are offered the update.</template>
|
|
||||||
<template v-else>Everyone can find it in the library and add it to their projects, together with everything it uses.</template>
|
|
||||||
Only this browser can update or remove it later.
|
|
||||||
</p>
|
|
||||||
<label class="field mt-4">
|
|
||||||
<span>Name</span>
|
|
||||||
<input v-model="name" :maxlength="LIBRARY_LIMITS.name" />
|
|
||||||
</label>
|
|
||||||
<label class="field">
|
|
||||||
<span>Description</span>
|
|
||||||
<textarea v-model="description" rows="3" :maxlength="LIBRARY_LIMITS.description" placeholder="What does it do, how do you use it?" />
|
|
||||||
</label>
|
|
||||||
<label class="field">
|
|
||||||
<span>Your name, also on the leaderboards</span>
|
|
||||||
<input v-model="author" maxlength="24" placeholder="Anonymous" autocomplete="nickname" />
|
|
||||||
</label>
|
|
||||||
<p class="hint">{{ pins.inputs.length }} in, {{ pins.outputs.length }} out, {{ shortCount(ed.transistors(def.id)) }} transistors. {{ along.text }}</p>
|
|
||||||
<p v-if="problem" class="result fail"><Icon name="lucide:circle-x" class="size-4 shrink-0" /> {{ problem }}</p>
|
|
||||||
<p v-if="error" class="result fail"><Icon name="lucide:circle-x" class="size-4 shrink-0" /> {{ error }}</p>
|
|
||||||
<div class="mt-3 flex flex-wrap items-center gap-2">
|
|
||||||
<button class="btn btn-primary" :disabled="!!problem || busy || !name.trim()" @click="publish">
|
|
||||||
<Icon name="lucide:book-up" class="size-4" /> {{ busy ? 'Publishing…' : own ? 'Publish new version' : 'Publish' }}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
v-if="own"
|
|
||||||
class="btn-sm ml-auto"
|
|
||||||
:class="{ danger: confirmRemove }"
|
|
||||||
:disabled="busy"
|
|
||||||
:title="confirmRemove ? 'Click again to take it out of the library' : 'Take it out of the library; copies others added stay theirs'"
|
|
||||||
@click="remove"
|
|
||||||
@pointerleave="confirmRemove = false"
|
|
||||||
>
|
|
||||||
{{ confirmRemove ? 'Remove from the library?' : 'Remove from the library' }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<template v-else>
|
|
||||||
<p class="result pass">
|
|
||||||
<Icon name="lucide:circle-check" class="size-4 shrink-0" />
|
|
||||||
<span>"{{ def.name }}" is in the library as version {{ done.version }}. Everyone can find it and add it to their projects.</span>
|
|
||||||
</p>
|
|
||||||
<div class="mt-3 flex gap-2">
|
|
||||||
<button class="btn btn-primary" @click="ed.dialog.value = 'library'"><Icon name="lucide:library-big" class="size-4" /> Open the library</button>
|
|
||||||
<button class="btn" @click="close">Done</button>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
@ -9,14 +9,13 @@ const page = ed.menuPage
|
||||||
const nav = ref<HTMLElement>()
|
const nav = ref<HTMLElement>()
|
||||||
|
|
||||||
const ITEMS: { page?: MenuPage; label: string; icon: string; sub: string }[] = [
|
const ITEMS: { page?: MenuPage; label: string; icon: string; sub: string }[] = [
|
||||||
{ page: 'load', label: 'Load game', icon: 'lucide:folder-open', sub: 'Every save: open, rename, copy, savegames' },
|
|
||||||
{ page: 'free', label: 'Free play', icon: 'lucide:cpu', sub: 'Every part from the start, your own projects' },
|
{ page: 'free', label: 'Free play', icon: 'lucide:cpu', sub: 'Every part from the start, your own projects' },
|
||||||
{ page: 'campaign', label: 'Campaign', icon: 'lucide:route', sub: 'Start with NAND, earn each part you build' },
|
{ page: 'campaign', label: 'Campaign', icon: 'lucide:route', sub: 'Start with NAND, earn each part you build' },
|
||||||
{ page: 'challenges', label: 'Challenges', icon: 'lucide:target', sub: 'Single tasks and the puzzle of the week' },
|
{ page: 'challenges', label: 'Challenges', icon: 'lucide:target', sub: 'Single tasks and the puzzle of the week' },
|
||||||
{ page: 'leaderboard', label: 'Leaderboard', icon: 'lucide:trophy', sub: 'Fewest transistors wins' },
|
{ page: 'leaderboard', label: 'Leaderboard', icon: 'lucide:trophy', sub: 'Fewest transistors wins' },
|
||||||
]
|
]
|
||||||
|
|
||||||
const TITLES: Record<MenuPage, string> = { main: '', load: 'Load game', free: 'Free play', campaign: 'Campaign', challenges: 'Challenges', leaderboard: 'Leaderboard' }
|
const TITLES: Record<MenuPage, string> = { main: '', free: 'Free play', campaign: 'Campaign', challenges: 'Challenges', leaderboard: 'Leaderboard' }
|
||||||
|
|
||||||
function go(p: MenuPage) {
|
function go(p: MenuPage) {
|
||||||
page.value = page.value === p ? 'main' : p
|
page.value = page.value === p ? 'main' : p
|
||||||
|
|
@ -70,22 +69,14 @@ onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
|
||||||
<p class="title-tag">From one NAND gate to a computer</p>
|
<p class="title-tag">From one NAND gate to a computer</p>
|
||||||
|
|
||||||
<nav ref="nav" class="title-nav" aria-label="Main menu">
|
<nav ref="nav" class="title-nav" aria-label="Main menu">
|
||||||
<button class="title-item primary" :disabled="!ed.savesReady.value" @click="ed.enterGame()">
|
<button class="title-item primary" @click="ed.enterGame()">
|
||||||
<Icon name="lucide:play" class="size-5 shrink-0" />
|
<Icon name="lucide:play" class="size-5 shrink-0" />
|
||||||
<span class="grow">
|
<span class="grow">
|
||||||
<span class="label">Continue</span>
|
<span class="label">Continue</span>
|
||||||
<span class="sub">{{ ed.savesReady.value ? ed.project.value.name : 'Loading your saves…' }}</span>
|
<span class="sub">{{ ed.project.value.name }}</span>
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button v-for="it in ITEMS" :key="it.label" class="title-item" :class="{ active: page === it.page }" @click="go(it.page!)">
|
||||||
v-for="it in ITEMS"
|
|
||||||
:key="it.label"
|
|
||||||
class="title-item"
|
|
||||||
:class="{ active: page === it.page }"
|
|
||||||
:disabled="!ed.savesReady.value && it.page !== 'leaderboard'"
|
|
||||||
:title="ed.savesReady.value ? '' : 'Loading your saves from your account…'"
|
|
||||||
@click="go(it.page!)"
|
|
||||||
>
|
|
||||||
<Icon :name="it.icon" class="size-5 shrink-0" />
|
<Icon :name="it.icon" class="size-5 shrink-0" />
|
||||||
<span class="grow">
|
<span class="grow">
|
||||||
<span class="label">{{ it.label }}</span>
|
<span class="label">{{ it.label }}</span>
|
||||||
|
|
@ -93,13 +84,6 @@ onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
|
||||||
</span>
|
</span>
|
||||||
<Icon name="lucide:chevron-right" class="chev size-4 shrink-0" />
|
<Icon name="lucide:chevron-right" class="chev size-4 shrink-0" />
|
||||||
</button>
|
</button>
|
||||||
<button class="title-item" :disabled="!ed.savesReady.value" @click="ed.dialog.value = 'library'">
|
|
||||||
<Icon name="lucide:library-big" class="size-5 shrink-0" />
|
|
||||||
<span class="grow">
|
|
||||||
<span class="label">Library</span>
|
|
||||||
<span class="sub">Components everyone published, to add to your project</span>
|
|
||||||
</span>
|
|
||||||
</button>
|
|
||||||
<button class="title-item" @click="ed.dialog.value = 'settings'">
|
<button class="title-item" @click="ed.dialog.value = 'settings'">
|
||||||
<Icon name="lucide:settings" class="size-5 shrink-0" />
|
<Icon name="lucide:settings" class="size-5 shrink-0" />
|
||||||
<span class="grow"><span class="label">Settings</span></span>
|
<span class="grow"><span class="label">Settings</span></span>
|
||||||
|
|
@ -122,8 +106,7 @@ onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
|
||||||
<h2>{{ TITLES[page] }}</h2>
|
<h2>{{ TITLES[page] }}</h2>
|
||||||
</header>
|
</header>
|
||||||
<div class="title-page-body">
|
<div class="title-page-body">
|
||||||
<EditorProjectList v-if="page === 'load'" @done="ed.enterGame()" />
|
<EditorProjectList v-if="page === 'free'" free-only @done="ed.enterGame()" />
|
||||||
<EditorProjectList v-else-if="page === 'free'" free-only @done="ed.enterGame()" />
|
|
||||||
<EditorMenuCampaign v-else-if="page === 'campaign'" />
|
<EditorMenuCampaign v-else-if="page === 'campaign'" />
|
||||||
<EditorMenuChallenges v-else-if="page === 'challenges'" />
|
<EditorMenuChallenges v-else-if="page === 'challenges'" />
|
||||||
<EditorMenuLeaderboard v-else-if="page === 'leaderboard'" />
|
<EditorMenuLeaderboard v-else-if="page === 'leaderboard'" />
|
||||||
|
|
|
||||||
|
|
@ -15,8 +15,7 @@ const parts = (id: string) =>
|
||||||
.join(', ')
|
.join(', ')
|
||||||
|
|
||||||
function fresh() {
|
function fresh() {
|
||||||
ed.newProject(false, true)
|
ed.startCampaign()
|
||||||
ed.challengesOpen.value = true
|
|
||||||
ed.enterGame()
|
ed.enterGame()
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,10 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import type { MenuEntry } from '~/composables/useMenu'
|
|
||||||
import { stats } from '~/lib/logic/analyze'
|
import { stats } from '~/lib/logic/analyze'
|
||||||
import { compile } from '~/lib/logic/compile'
|
import { compile } from '~/lib/logic/compile'
|
||||||
import { cableOf } from '~/lib/logic/cables'
|
import { cableOf } from '~/lib/logic/cables'
|
||||||
import { INVERTIBLE } from '~/lib/logic/compile'
|
import { INVERTIBLE } from '~/lib/logic/compile'
|
||||||
import { cableBits, cableOffsets, chipPins, MAX_BITS, panelOffsets, portName, rowLabel } from '~/lib/logic/geometry'
|
import { cableBits, cableOffsets, chipPins, MAX_BITS, panelOffsets, rowLabel } from '~/lib/logic/geometry'
|
||||||
import { SINK_KINDS, SOURCE_KINDS, uid } from '~/lib/logic/ops'
|
import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
|
||||||
import { DISPLAY_SIZES, displaySize, isDisplay, ratioText, type DisplayKind } from '~/lib/logic/displays'
|
|
||||||
import { KIND_NAMES } from '~/lib/logic/progress'
|
import { KIND_NAMES } from '~/lib/logic/progress'
|
||||||
import { baseOf, gateFamily, inputCount, MAX_GATE_INPUTS } from '~/lib/logic/wide'
|
import { baseOf, gateFamily, inputCount, MAX_GATE_INPUTS } from '~/lib/logic/wide'
|
||||||
import { LAMP_COLORS, WIRE_COLORS, type CircuitNode, type NodeKind, type PanelControl, type PanelRow } from '~/lib/logic/types'
|
import { LAMP_COLORS, WIRE_COLORS, type CircuitNode, type NodeKind, type PanelControl, type PanelRow } from '~/lib/logic/types'
|
||||||
|
|
@ -14,10 +12,10 @@ import { LAMP_COLORS, WIRE_COLORS, type CircuitNode, type NodeKind, type PanelCo
|
||||||
const props = defineProps<{ node: CircuitNode }>()
|
const props = defineProps<{ node: CircuitNode }>()
|
||||||
const ed = useEditor()
|
const ed = useEditor()
|
||||||
|
|
||||||
const CONTROLS: { value: PanelControl; label: string; icon: string }[] = [
|
const CONTROLS: { value: PanelControl; label: string }[] = [
|
||||||
{ value: 'switch', label: 'Switch', icon: 'lucide:toggle-left' },
|
{ value: 'switch', label: 'Switch' },
|
||||||
{ value: 'button', label: 'Button', icon: 'lucide:circle-dot' },
|
{ value: 'button', label: 'Button' },
|
||||||
{ value: 'clock', label: 'Clock', icon: 'lucide:audio-waveform' },
|
{ value: 'clock', label: 'Clock' },
|
||||||
]
|
]
|
||||||
|
|
||||||
const HINTS: Record<string, string> = {
|
const HINTS: Record<string, string> = {
|
||||||
|
|
@ -35,7 +33,7 @@ const HINTS: Record<string, string> = {
|
||||||
tag: 'Wire a signal into it and give it a name. Every "Use signal" with that name in this circuit carries the same signal, without a wire. Names stay inside this circuit.',
|
tag: 'Wire a signal into it and give it a name. Every "Use signal" with that name in this circuit carries the same signal, without a wire. Names stay inside this circuit.',
|
||||||
ref: 'Carries the signal of the "Send signal" with the same name in this circuit. Select it to see all places that signal goes.',
|
ref: 'Carries the signal of the "Send signal" with the same name in this circuit. Select it to see all places that signal goes.',
|
||||||
outpanel: 'A lamp per row, named after what it shows. Inside a component its rows are output pins, top to bottom with the other outputs. Each row passes its signal on to the right.',
|
outpanel: 'A lamp per row, named after what it shows. Inside a component its rows are output pins, top to bottom with the other outputs. Each row passes its signal on to the right.',
|
||||||
panel: 'Click a row on the canvas to flip its switch or hold its button, or press its key. Rows without a name take the name of the pin they are wired to. Drag a row by its grip to move it; point between two rows to add one there or change the space.',
|
panel: 'Click a row on the canvas to flip its switch or hold its button, or press its key. Rows without a name take the name of the pin they are wired to. Open a row (the arrow) for its key, colour, spacing and order.',
|
||||||
}
|
}
|
||||||
|
|
||||||
const n = computed(() => props.node)
|
const n = computed(() => props.node)
|
||||||
|
|
@ -107,6 +105,14 @@ function setColor(c: (typeof LAMP_COLORS)[number] | undefined) {
|
||||||
ed.commit(false)
|
ed.commit(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function setPos(axis: 'x' | 'y', e: Event) {
|
||||||
|
const v = Math.round(Number((e.target as HTMLInputElement).value))
|
||||||
|
if (Number.isFinite(v)) {
|
||||||
|
n.value[axis] = v
|
||||||
|
ed.commit(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function setSize(size: 'sm' | 'md' | 'lg') {
|
function setSize(size: 'sm' | 'md' | 'lg') {
|
||||||
if (size === 'md') delete n.value.size
|
if (size === 'md') delete n.value.size
|
||||||
else n.value.size = size
|
else n.value.size = size
|
||||||
|
|
@ -153,65 +159,19 @@ const cables = computed(() => ed.cableChoices(n.value))
|
||||||
const invertible = computed(() => {
|
const invertible = computed(() => {
|
||||||
if (!INVERTIBLE.has(n.value.kind)) return []
|
if (!INVERTIBLE.has(n.value.kind)) return []
|
||||||
const inv = new Set(n.value.invert ?? [])
|
const inv = new Set(n.value.invert ?? [])
|
||||||
return ed.shape(n.value).inputs.filter(p => !p.bus && !p.port).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.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)
|
/** The bundle of the cable this bundle or split belongs to. */
|
||||||
|
|
||||||
const transistors = computed(() => ed.transistorsOfNode(n.value))
|
|
||||||
const transistorNote = computed(() =>
|
|
||||||
n.value.kind === 'nand'
|
|
||||||
? 'CMOS NAND: 2 transistors in parallel to the supply, 2 in series to ground'
|
|
||||||
: transistors.value
|
|
||||||
? `${(transistors.value / 4).toLocaleString()} NAND gates inside, 4 transistors each`
|
|
||||||
: '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)
|
|
||||||
let closedAt = 0
|
|
||||||
function openMore(e: MouseEvent) {
|
|
||||||
// A click on the button while the menu is open closes it (the press already did).
|
|
||||||
if (performance.now() - closedAt < 300) return
|
|
||||||
const r = (e.currentTarget as HTMLElement).getBoundingClientRect()
|
|
||||||
more.value = { x: r.right - 220, y: r.bottom + 4, entries: menu.build({ kind: 'selection' }, { fit: () => {}, place: () => {} }) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The bundle of the cable this bundle or split belongs to: none for a plug whose cable isn't pulled out yet. */
|
|
||||||
const cableBundle = computed(() => {
|
const cableBundle = computed(() => {
|
||||||
const d = ed.def.value
|
if (n.value.kind === 'bundle') return n.value
|
||||||
const bundle =
|
if (n.value.kind !== 'split') return undefined
|
||||||
n.value.kind === 'bundle' ? n.value : n.value.kind === 'split' ? (w => (w ? cableOf(d, w) : undefined))(d.wires.find(w => w.to.node === n.value.id)) : undefined
|
const feed = ed.def.value.wires.find(w => w.to.node === n.value.id)
|
||||||
return bundle && d.wires.some(w => w.from.node === bundle.id && w.from.pin === 'q') ? bundle : undefined
|
return feed ? cableOf(ed.def.value, feed) : undefined
|
||||||
})
|
})
|
||||||
|
|
||||||
/** Starts the cable out of a plug that has none: the next click puts its other end. */
|
|
||||||
function pullOut() {
|
|
||||||
const bus = n.value.kind === 'bundle' ? { pin: 'q', dir: 'out' as const } : { pin: 'a', dir: 'in' as const }
|
|
||||||
ed.linking.value = { queue: [{ node: n.value.id, ...bus, label: '' }], at: 0 }
|
|
||||||
}
|
|
||||||
|
|
||||||
const sleeveColor = computed(() => (cableBundle.value ? ed.def.value.wires.find(w => w.from.node === cableBundle.value!.id)?.color : undefined))
|
const sleeveColor = computed(() => (cableBundle.value ? ed.def.value.wires.find(w => w.from.node === cableBundle.value!.id)?.color : undefined))
|
||||||
|
|
||||||
/** Connector ports on the component's box: each one can show its lines as pins on this box. */
|
|
||||||
const boxPorts = computed(() =>
|
|
||||||
(chipDef.value ? (chipPins(chipDef.value).ports ?? []) : []).map(p => ({ key: p.key, name: portName(p, ed.getDef.value), split: !!n.value.splitPorts?.includes(p.key) })),
|
|
||||||
)
|
|
||||||
|
|
||||||
const chipInputs = computed(() => (chipDef.value ? chipPins(chipDef.value).inputs.length : 0))
|
const chipInputs = computed(() => (chipDef.value ? chipPins(chipDef.value).inputs.length : 0))
|
||||||
const chipOutputs = computed(() => (chipDef.value ? chipPins(chipDef.value).outputs.length : 0))
|
const chipOutputs = computed(() => (chipDef.value ? chipPins(chipDef.value).outputs.length : 0))
|
||||||
const hasPanel = computed(() => ed.def.value.nodes.some(x => x.kind === 'panel' && x.attach === n.value.id))
|
const hasPanel = computed(() => ed.def.value.nodes.some(x => x.kind === 'panel' && x.attach === n.value.id))
|
||||||
|
|
@ -225,76 +185,13 @@ function setRowLabel(row: PanelRow, e: Event) {
|
||||||
ed.commit()
|
ed.commit()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Tab in the last row's name, once it is filled in, adds a row and goes on to it. */
|
/** Rows showing their extra settings (key, colour, spacing, order). */
|
||||||
function tabOn(row: PanelRow, i: number, e: KeyboardEvent) {
|
const openRows = ref(new Set<string>())
|
||||||
const input = e.target as HTMLInputElement
|
function toggleRow(id: string) {
|
||||||
if (e.shiftKey || n.value.attach || i !== (n.value.rows?.length ?? 0) - 1 || !input.value.trim()) return
|
const s = new Set(openRows.value)
|
||||||
e.preventDefault()
|
if (!s.delete(id)) s.add(id)
|
||||||
setRowLabel(row, e)
|
openRows.value = s
|
||||||
addAt(n.value.rows?.length ?? 0)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const rowList = ref<HTMLElement>()
|
|
||||||
const focusRow = (id: string) => nextTick(() => rowList.value?.querySelector<HTMLInputElement>(`[data-row-id="${id}"] .row-name`)?.focus())
|
|
||||||
|
|
||||||
/** A new row at a place in the order, its name ready to type. */
|
|
||||||
function addAt(index: number) {
|
|
||||||
const row = ed.insertRow(n.value, index)
|
|
||||||
if (row) focusRow(row.id)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The row's colour: a click takes the next one, Shift + click the one before. */
|
|
||||||
function nextColor(row: PanelRow, e: MouseEvent) {
|
|
||||||
const order = [undefined, ...LAMP_COLORS]
|
|
||||||
const k = order.indexOf(row.color)
|
|
||||||
ed.setRowColor(row, order[(k + (e.shiftKey ? -1 : 1) + order.length) % order.length])
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Alt + ↑/↓ in a row's name moves the row. */
|
|
||||||
function moveByKey(i: number, e: KeyboardEvent) {
|
|
||||||
if (!e.altKey || n.value.attach) return
|
|
||||||
const to = i + (e.key === 'ArrowUp' ? -1 : 1)
|
|
||||||
const row = n.value.rows?.[i]
|
|
||||||
if (!row || to < 0 || to >= (n.value.rows?.length ?? 0)) return
|
|
||||||
e.preventDefault()
|
|
||||||
ed.moveRowTo(n.value, i, to)
|
|
||||||
focusRow(row.id)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Dragging a row by its grip: a line shows where it goes; dropping moves it there.
|
|
||||||
const rowDrag = ref<{ from: number; before: number } | null>(null)
|
|
||||||
function startRowDrag(from: number, e: PointerEvent) {
|
|
||||||
if (n.value.attach) return
|
|
||||||
e.preventDefault()
|
|
||||||
rowDrag.value = { from, before: from }
|
|
||||||
const move = (ev: PointerEvent) => {
|
|
||||||
const items = [...(rowList.value?.querySelectorAll<HTMLElement>('li.row') ?? [])]
|
|
||||||
let before = items.length
|
|
||||||
for (let k = 0; k < items.length; k++) {
|
|
||||||
const r = items[k]!.getBoundingClientRect()
|
|
||||||
if (ev.clientY < r.top + r.height / 2) {
|
|
||||||
before = k
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
rowDrag.value = { from, before }
|
|
||||||
}
|
|
||||||
const up = () => {
|
|
||||||
window.removeEventListener('pointermove', move)
|
|
||||||
window.removeEventListener('pointerup', up)
|
|
||||||
const d = rowDrag.value
|
|
||||||
rowDrag.value = null
|
|
||||||
if (d) ed.moveRowTo(n.value, d.from, d.before > d.from ? d.before - 1 : d.before)
|
|
||||||
}
|
|
||||||
window.addEventListener('pointermove', move)
|
|
||||||
window.addEventListener('pointerup', up)
|
|
||||||
}
|
|
||||||
/** Where the drop line shows: above row k, or (k = rows) below the last. */
|
|
||||||
const dropAt = computed(() => {
|
|
||||||
const d = rowDrag.value
|
|
||||||
return d && d.before !== d.from && d.before !== d.from + 1 ? d.before : null
|
|
||||||
})
|
|
||||||
|
|
||||||
const rowGaps = computed(() => {
|
const rowGaps = computed(() => {
|
||||||
const at = panelOffsets(n.value.rows ?? [])
|
const at = panelOffsets(n.value.rows ?? [])
|
||||||
return at.map((y, i) => (i ? y - at[i - 1]! - 1 : 0))
|
return at.map((y, i) => (i ? y - at[i - 1]! - 1 : 0))
|
||||||
|
|
@ -320,8 +217,6 @@ function partName(id: string | undefined): string {
|
||||||
}
|
}
|
||||||
|
|
||||||
const isCableEnd = computed(() => n.value.kind === 'bundle' || n.value.kind === 'split')
|
const isCableEnd = computed(() => n.value.kind === 'bundle' || n.value.kind === 'split')
|
||||||
/** The part this one fits straight onto (its pins line up with the ones it is wired to). */
|
|
||||||
const latchHost = computed(() => (isCableEnd.value ? undefined : ed.latchTargetOf(n.value)))
|
|
||||||
const plugPart = computed(() => (isCableEnd.value && !n.value.plug ? ed.plugTarget(n.value) : undefined))
|
const plugPart = computed(() => (isCableEnd.value && !n.value.plug ? ed.plugTarget(n.value) : undefined))
|
||||||
const pitch = computed(() => {
|
const pitch = computed(() => {
|
||||||
const o = cableOffsets(n.value)
|
const o = cableOffsets(n.value)
|
||||||
|
|
@ -345,89 +240,21 @@ function setRowHz(row: PanelRow, e: Event) {
|
||||||
else delete row.hz
|
else delete row.hz
|
||||||
ed.commit()
|
ed.commit()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Monitor sizes a click away. */
|
|
||||||
const SIZE_PRESETS: [number, number][] = [[16, 16], [32, 32], [64, 32], [64, 64], [128, 64], [128, 128]]
|
|
||||||
|
|
||||||
/** Logic analyzer channels. */
|
|
||||||
function addChannel(bits: number) {
|
|
||||||
const used = new Set((n.value.scope?.cols ?? []).map(c => c.name))
|
|
||||||
let k = 0
|
|
||||||
while (used.has(`CH${k}`)) k++
|
|
||||||
ed.setScope(n.value.id, cols => cols.push({ id: uid('c'), name: `CH${k}`, bits }))
|
|
||||||
}
|
|
||||||
function renameChannel(i: number, name: string) {
|
|
||||||
if (name.trim()) ed.setScope(n.value.id, cols => (cols[i]!.name = name.trim().slice(0, 40)))
|
|
||||||
}
|
|
||||||
function setChannelBits(i: number, v: string) {
|
|
||||||
const bits = Math.round(Number(v))
|
|
||||||
if (bits >= 1 && bits <= 32) ed.setScope(n.value.id, cols => (cols[i]!.bits = bits))
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<section class="sel">
|
<section>
|
||||||
<!-- What it is, and the everyday actions -->
|
<h3>{{ title }}</h3>
|
||||||
<header class="sel-head">
|
<p class="score" :title="n.kind === 'nand' ? 'CMOS NAND: 2 transistors in parallel to the supply, 2 in series to ground' : ''">
|
||||||
<div class="sel-title">
|
<Icon name="lucide:cpu" class="size-4 shrink-0" />
|
||||||
<h3 :title="HINTS[n.kind] ?? ''">{{ title }}</h3>
|
<span v-if="n.kind === 'nand'">4 transistors (CMOS: 2 in parallel to the supply, 2 in series to ground)</span>
|
||||||
<span class="sel-t" :title="transistorNote">{{ transistors.toLocaleString() }} T</span>
|
<span v-else-if="n.kind === 'chip'">
|
||||||
</div>
|
{{ ed.transistorsOfNode(n).toLocaleString() }} transistors, from {{ (ed.transistorsOfNode(n) / 4).toLocaleString() }} NAND gates inside
|
||||||
<div class="sel-actions">
|
</span>
|
||||||
<button v-if="n.kind === 'chip' && chipDef" class="icon-btn" title="Open component (Enter)" @click="ed.open(chipDef.id)">
|
<span v-else>0 transistors: no logic gate inside</span>
|
||||||
<Icon name="lucide:log-in" class="size-4" />
|
</p>
|
||||||
</button>
|
|
||||||
<button class="icon-btn" title="Duplicate (Ctrl+D)" @click="ed.duplicate()"><Icon name="lucide:copy" class="size-4" /></button>
|
|
||||||
<button class="icon-btn" :disabled="!wired" title="Unlink all its wires" @click="ed.unlink([n.id])"><Icon name="lucide:unlink" class="size-4" /></button>
|
|
||||||
<button class="icon-btn danger" title="Delete (Del)" @click="ed.deleteSelected()"><Icon name="lucide:trash-2" class="size-4" /></button>
|
|
||||||
<button class="icon-btn" title="Everything else you can do with it (also on right click)" @click="openMore"><Icon name="lucide:ellipsis" class="size-4" /></button>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<!-- The few settings that matter for this kind of part -->
|
<label v-if="logic" class="field">
|
||||||
<label v-if="hasLabel" class="field">
|
|
||||||
<span>{{ n.kind === 'note' ? 'Text' : n.kind === 'chip' ? 'Name on the canvas' : n.kind === 'tag' ? 'Signal name' : n.kind === 'ref' ? 'Signal' : 'Name' }}</span>
|
|
||||||
<textarea v-if="n.kind === 'note'" ref="labelInput" v-model="n.label" rows="3" @change="ed.commit(false)" />
|
|
||||||
<input
|
|
||||||
v-else
|
|
||||||
ref="labelInput"
|
|
||||||
v-model="n.label"
|
|
||||||
:class="{ 'auto-name': n.autoLabel }"
|
|
||||||
:title="n.autoLabel ? 'Named automatically; typing a name keeps it' : ''"
|
|
||||||
:placeholder="n.kind === 'chip' ? 'e.g. U1, ALU' : n.kind === 'panel' ? 'Shown above the panel' : n.kind === 'tag' || n.kind === 'ref' ? 'e.g. CLK, RESET' : ''"
|
|
||||||
:list="n.kind === 'ref' ? 'signal-names' : undefined"
|
|
||||||
@change="onLabel"
|
|
||||||
@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>
|
|
||||||
|
|
||||||
<div v-if="logic || family.length || widens" class="sel-row">
|
|
||||||
<label v-if="logic" class="field grow" title="Swapping keeps the wires on the pins in the same position">
|
|
||||||
<span>Part</span>
|
<span>Part</span>
|
||||||
<select :value="currentType" @change="onSwap">
|
<select :value="currentType" @change="onSwap">
|
||||||
<option value="nand">NAND (2 → 1)</option>
|
<option value="nand">NAND (2 → 1)</option>
|
||||||
|
|
@ -436,25 +263,200 @@ function setChannelBits(i: number, v: string) {
|
||||||
</optgroup>
|
</optgroup>
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<label v-else-if="family.length" class="field grow" title="Swapping keeps the wires on the pins in the same position">
|
<label v-else-if="family.length" class="field">
|
||||||
<span>Type</span>
|
<span>Type</span>
|
||||||
<select :value="currentType" @change="onSwap">
|
<select :value="currentType" @change="onSwap">
|
||||||
<option v-for="k in family" :key="k" :value="k">{{ KIND_NAMES[k] }}</option>
|
<option v-for="k in family" :key="k" :value="k">{{ KIND_NAMES[k] }}</option>
|
||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<label v-if="widens" class="field narrow" :title="inputs > 2 ? `Built from ${inputs - 1} two-input gates in a tree, so the transistors count honestly` : 'Up to 16 inputs'">
|
<p v-if="logic || family.length" class="hint -mt-1">Swapping keeps the wires on the pins in the same position.</p>
|
||||||
|
|
||||||
|
<label v-if="widens" class="field">
|
||||||
<span>Inputs</span>
|
<span>Inputs</span>
|
||||||
<input type="number" min="2" :max="MAX_GATE_INPUTS" step="1" :value="inputs" @change="ed.setInputs(n, Number(($event.target as HTMLInputElement).value))" />
|
<input
|
||||||
|
type="number"
|
||||||
|
min="2"
|
||||||
|
:max="MAX_GATE_INPUTS"
|
||||||
|
step="1"
|
||||||
|
:value="inputs"
|
||||||
|
@change="ed.setInputs(n, Number(($event.target as HTMLInputElement).value))"
|
||||||
|
/>
|
||||||
</label>
|
</label>
|
||||||
|
<p v-if="widens && inputs > 2" class="hint -mt-1">Built from {{ inputs - 1 }} two-input gates in a tree, so the transistors count honestly.</p>
|
||||||
|
|
||||||
|
<div v-if="invertible.length" class="field">
|
||||||
|
<span>Inverted inputs (Alt + click a pin)</span>
|
||||||
|
<div class="invert-pins">
|
||||||
|
<button
|
||||||
|
v-for="p in invertible"
|
||||||
|
:key="p.key"
|
||||||
|
class="invert-pin"
|
||||||
|
:class="{ on: p.on }"
|
||||||
|
:title="p.on ? 'Inverted: one NAND, 4 transistors. Click to take the bubble off.' : 'Invert this input'"
|
||||||
|
@click="ed.toggleInvert(n, p.key)"
|
||||||
|
>
|
||||||
|
<span class="dot" />{{ p.label }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-if="n.kind === 'input'" class="field">
|
<label v-if="hasLabel" class="field">
|
||||||
|
<span>{{ n.kind === 'note' ? 'Text' : n.kind === 'chip' ? 'Name on the canvas' : n.kind === 'tag' ? 'Signal name' : n.kind === 'ref' ? 'Signal' : 'Label' }}</span>
|
||||||
|
<textarea v-if="n.kind === 'note'" ref="labelInput" v-model="n.label" rows="3" @change="ed.commit(false)" />
|
||||||
|
<input
|
||||||
|
v-else
|
||||||
|
ref="labelInput"
|
||||||
|
v-model="n.label"
|
||||||
|
:placeholder="n.kind === 'chip' ? 'e.g. U1, ALU' : n.kind === 'panel' ? 'Shown above the panel' : n.kind === 'tag' || n.kind === 'ref' ? 'e.g. CLK, RESET' : ''"
|
||||||
|
:list="n.kind === 'ref' ? 'signal-names' : undefined"
|
||||||
|
@change="onLabel"
|
||||||
|
@keydown.enter="($event.target as HTMLInputElement).blur()"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<p v-if="n.autoLabel && n.label" class="hint -mt-1">Named automatically. Typing a name keeps it.</p>
|
||||||
|
<datalist id="signal-names">
|
||||||
|
<option v-for="name in signalNames" :key="name" :value="name" />
|
||||||
|
</datalist>
|
||||||
|
|
||||||
|
<!-- Signals -->
|
||||||
|
<template v-if="n.kind === 'tag'">
|
||||||
|
<p v-if="senders.length > 1" class="result fail">
|
||||||
|
<Icon name="lucide:triangle-alert" class="size-4 shrink-0" />
|
||||||
|
<span>{{ senders.length }} "Send signal" parts use this name: they all drive it, like a short.</span>
|
||||||
|
</p>
|
||||||
|
<p class="hint">{{ uses.length ? `Used in ${uses.length} place${uses.length === 1 ? '' : 's'}.` : 'Not used anywhere yet.' }}</p>
|
||||||
|
<div class="mb-2 grid grid-cols-2 gap-2">
|
||||||
|
<button class="btn" :disabled="!signal" title="A 'Use signal' for it, placed next to it" @click="ed.useSignal(n)"><Icon name="lucide:tag" class="size-4" /> Use it</button>
|
||||||
|
<button class="btn" :disabled="!uses.length" @click="ed.selectSignal(signal)"><Icon name="lucide:scan-search" class="size-4" /> Select all</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template v-if="n.kind === 'ref'">
|
||||||
|
<p v-if="!senders.length" class="result fail">
|
||||||
|
<Icon name="lucide:triangle-alert" class="size-4 shrink-0" />
|
||||||
|
<span>{{ signal ? `Nothing sends "${signal}" in this circuit, so it reads 0.` : 'Pick the signal it carries.' }}</span>
|
||||||
|
</p>
|
||||||
|
<div v-else class="mb-2 grid grid-cols-2 gap-2">
|
||||||
|
<button class="btn" @click="ed.focusNode(senders[0]!.id)"><Icon name="lucide:locate-fixed" class="size-4" /> Go to source</button>
|
||||||
|
<button class="btn" @click="ed.selectSignal(signal)"><Icon name="lucide:scan-search" class="size-4" /> Select all</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Panel rows: switches, buttons and clocks, or lamps -->
|
||||||
|
<template v-if="n.kind === 'panel' || n.kind === 'outpanel'">
|
||||||
|
<p v-if="dock" class="result pass">
|
||||||
|
<Icon name="lucide:link" class="size-4 shrink-0" />
|
||||||
|
<span class="grow">Attached to {{ dock }}. It moves with it and gets a row for each new {{ outPanel ? 'output' : 'input' }}.</span>
|
||||||
|
<button class="btn-sm" title="Keep the panel and its wires, but stop following the component" @click="ed.undock(n)">Detach</button>
|
||||||
|
</p>
|
||||||
|
<div class="field">
|
||||||
|
<span>Rows</span>
|
||||||
|
<ul class="panel-rows">
|
||||||
|
<li v-for="(r, i) in n.rows ?? []" :key="r.id" :class="{ open: openRows.has(r.id) }">
|
||||||
|
<button
|
||||||
|
class="icon-btn"
|
||||||
|
:class="{ active: openRows.has(r.id) }"
|
||||||
|
:title="openRows.has(r.id) ? 'Fewer settings' : 'Key, colour, spacing and order'"
|
||||||
|
@click="toggleRow(r.id)"
|
||||||
|
>
|
||||||
|
<Icon :name="openRows.has(r.id) ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-3.5" />
|
||||||
|
</button>
|
||||||
|
<input :value="r.label ?? ''" :placeholder="rowLabel({ ...r, label: undefined }, i)" title="Name" @change="setRowLabel(r, $event)" />
|
||||||
|
<select v-if="!outPanel" :value="r.type" title="Kind" @change="ed.setRowType(r, ($event.target as HTMLSelectElement).value as PanelControl)">
|
||||||
|
<option v-for="c in CONTROLS" :key="c.value" :value="c.value">{{ c.label }}</option>
|
||||||
|
</select>
|
||||||
|
<input
|
||||||
|
v-if="r.type === 'clock'"
|
||||||
|
type="number"
|
||||||
|
min="0.1"
|
||||||
|
max="1000"
|
||||||
|
step="any"
|
||||||
|
class="hz"
|
||||||
|
:value="r.hz ?? ''"
|
||||||
|
placeholder="Hz"
|
||||||
|
title="Frequency in Hz; empty follows the top bar"
|
||||||
|
@change="setRowHz(r, $event)"
|
||||||
|
/>
|
||||||
|
<button class="icon-btn" title="Remove this row" @click="ed.dropRow(n, r.id)"><Icon name="lucide:x" class="size-3.5" /></button>
|
||||||
|
<div v-if="openRows.has(r.id)" class="row-more">
|
||||||
|
<label v-if="r.type !== 'clock' && !outPanel" title="Keyboard key that flips the switch or holds the button">
|
||||||
|
<span>Key</span>
|
||||||
|
<input :value="r.key?.toUpperCase() ?? ''" readonly placeholder="–" class="key-input" @keydown="setRowKey(r, $event)" />
|
||||||
|
</label>
|
||||||
|
<label v-if="!n.attach && i > 0" title="Empty rows above this one">
|
||||||
|
<span>Space</span>
|
||||||
|
<input type="number" min="0" max="20" :value="rowGaps[i]" @change="ed.setRowGap(n, i, Number(($event.target as HTMLInputElement).value))" />
|
||||||
|
</label>
|
||||||
|
<span v-if="!n.attach" class="flex gap-0.5">
|
||||||
|
<button class="icon-btn" title="Move up" :disabled="i === 0" @click="ed.moveRow(n, i, -1)"><Icon name="lucide:arrow-up" class="size-3.5" /></button>
|
||||||
|
<button class="icon-btn" title="Move down" :disabled="i === (n.rows?.length ?? 0) - 1" @click="ed.moveRow(n, i, 1)"><Icon name="lucide:arrow-down" class="size-3.5" /></button>
|
||||||
|
</span>
|
||||||
|
<div v-if="r.type !== 'clock' || outPanel" class="swatches mini" title="Colour while on">
|
||||||
|
<button
|
||||||
|
class="swatch lamp-swatch"
|
||||||
|
:class="[outPanel ? 'default' : 'default-on', { active: !r.color, button: r.type === 'button' && !outPanel }]"
|
||||||
|
title="Default"
|
||||||
|
@click="ed.setRowColor(r, undefined)"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
v-for="c in LAMP_COLORS"
|
||||||
|
:key="c"
|
||||||
|
class="swatch lamp-swatch"
|
||||||
|
:class="[`l-${c}`, { active: r.color === c }]"
|
||||||
|
:title="c"
|
||||||
|
@click="ed.setRowColor(r, c)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<div class="flex flex-wrap items-center gap-1">
|
||||||
|
<button v-if="!n.attach" class="btn-sm" @click="ed.addRow(n)"><Icon name="lucide:plus" class="size-3.5" /> Add row</button>
|
||||||
|
<template v-if="!outPanel && (n.rows?.length ?? 0) > 1">
|
||||||
|
<span class="hint ml-auto">All rows:</span>
|
||||||
|
<button v-for="c in CONTROLS" :key="c.value" class="btn-sm" :title="`Make every row a ${c.label.toLowerCase()}`" @click="ed.setRowsType(n, c.value)">{{ c.label }}</button>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button class="btn w-full" :disabled="!n.rows?.length" @click="ed.startLinking([n.id], outPanel ? 'in' : 'out')">
|
||||||
|
<Icon name="lucide:cable" class="size-4" /> Wire rows one by one
|
||||||
|
</button>
|
||||||
|
<label
|
||||||
|
class="check mt-2"
|
||||||
|
:title="outPanel ? 'Used as a component, its rows are output pins (top to bottom, with the other outputs).' : 'Used as a component, its switch and button rows are its input pins (top to bottom, with the other inputs). Clock rows stay inside.'"
|
||||||
|
>
|
||||||
|
<input type="checkbox" :checked="!n.inner" @change="setInner(!($event.target as HTMLInputElement).checked)" />
|
||||||
|
Rows are component {{ outPanel ? 'outputs' : 'inputs' }}
|
||||||
|
</label>
|
||||||
|
<p v-if="n.inner" class="hint">{{ outPanel ? 'Kept inside: the lamps only show in here.' : 'Kept inside: in a component the switches stay as set here, buttons read 0.' }}</p>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div v-if="cables.out.length || cables.in.length" class="field cable-choices">
|
||||||
|
<span>Plug a cable onto its pins</span>
|
||||||
|
<div v-if="cables.out.length" class="cable-row">
|
||||||
|
<span class="hint">From outputs</span>
|
||||||
|
<button v-for="g in cables.out" :key="g.label" class="btn-sm" :title="`A cable with ${g.pins.length} wires out of these pins`" @click="ed.cableOut(n.id, g.pins)">{{ g.label }}</button>
|
||||||
|
</div>
|
||||||
|
<div v-if="cables.in.length" class="cable-row">
|
||||||
|
<span class="hint">Into inputs</span>
|
||||||
|
<button v-for="g in cables.in" :key="g.label" class="btn-sm" :title="`A cable with ${g.pins.length} wires into these pins`" @click="ed.cableIn(n.id, g.pins)">{{ g.label }}</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Kind-specific settings -->
|
||||||
|
<template v-if="n.kind === 'input'">
|
||||||
|
<div class="field">
|
||||||
<span>Value</span>
|
<span>Value</span>
|
||||||
<div class="seg">
|
<div class="seg">
|
||||||
<button :class="{ active: !n.on }" @click="setOn(false)">0</button>
|
<button :class="{ active: !n.on }" @click="setOn(false)">0</button>
|
||||||
<button :class="{ active: n.on }" @click="setOn(true)">1</button>
|
<button :class="{ active: n.on }" @click="setOn(true)">1</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<label v-if="n.kind === 'input' || n.kind === 'button'" class="field">
|
||||||
|
<span>Keyboard key</span>
|
||||||
|
<input :value="n.key ?? ''" readonly placeholder="Click, then press a key" class="key-input" @keydown="setKey" />
|
||||||
|
</label>
|
||||||
|
|
||||||
<template v-if="n.kind === 'clock'">
|
<template v-if="n.kind === 'clock'">
|
||||||
<label class="check">
|
<label class="check">
|
||||||
|
|
@ -470,14 +472,20 @@ function setChannelBits(i: number, v: string) {
|
||||||
</label>
|
</label>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<div v-if="n.kind === 'pixel'" class="field">
|
<label v-if="n.kind === 'pixel'" class="field" title="Pixels with the same screen name make one screen on the component's box; without a name, the main screen">
|
||||||
<span>Colours</span>
|
<span>Screen on the box</span>
|
||||||
<div class="seg">
|
<input
|
||||||
<button :class="{ active: !n.rgb }" title="One input: lit in one colour at 1" @click="ed.setRgb([n.id], false)">One</button>
|
:value="n.screen ?? ''"
|
||||||
<button :class="{ active: n.rgb }" title="Three inputs, red, green and blue: eight colours" @click="ed.setRgb([n.id], true)">RGB</button>
|
list="screen-names"
|
||||||
</div>
|
placeholder="Main screen"
|
||||||
</div>
|
@change="ed.setScreen([n.id], ($event.target as HTMLInputElement).value)"
|
||||||
<div v-if="n.kind === 'lamp' || n.kind === 'hex' || (n.kind === 'pixel' && !n.rgb)" class="field">
|
@keydown.enter="($event.target as HTMLInputElement).blur()"
|
||||||
|
/>
|
||||||
|
<datalist id="screen-names">
|
||||||
|
<option v-for="name in screenNames" :key="name" :value="name" />
|
||||||
|
</datalist>
|
||||||
|
</label>
|
||||||
|
<div v-if="n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel'" class="field">
|
||||||
<span>Colour</span>
|
<span>Colour</span>
|
||||||
<div class="swatches">
|
<div class="swatches">
|
||||||
<button class="swatch lamp-swatch default" :class="{ active: !n.color, hex: n.kind === 'hex' }" title="Default" @click="setColor(undefined)" />
|
<button class="swatch lamp-swatch default" :class="{ active: !n.color, hex: n.kind === 'hex' }" title="Default" @click="setColor(undefined)" />
|
||||||
|
|
@ -501,174 +509,34 @@ function setChannelBits(i: number, v: string) {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Signals -->
|
|
||||||
<template v-if="n.kind === 'tag'">
|
|
||||||
<p v-if="senders.length > 1" class="result fail">
|
|
||||||
<Icon name="lucide:triangle-alert" class="size-4 shrink-0" />
|
|
||||||
<span>{{ senders.length }} "Send signal" parts use this name: they all drive it, like a short.</span>
|
|
||||||
</p>
|
|
||||||
<div class="sel-row">
|
|
||||||
<button class="btn grow" :disabled="!signal" title="A 'Use signal' for it, placed next to it" @click="ed.useSignal(n)"><Icon name="lucide:tag" class="size-4" /> Use it</button>
|
|
||||||
<button class="btn grow" :disabled="!uses.length" :title="uses.length ? `Used in ${uses.length} place${uses.length === 1 ? '' : 's'}` : 'Not used anywhere yet'" @click="ed.selectSignal(signal)">
|
|
||||||
<Icon name="lucide:scan-search" class="size-4" /> {{ uses.length }} uses
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
<template v-if="n.kind === 'ref'">
|
|
||||||
<p v-if="!senders.length" class="result fail">
|
|
||||||
<Icon name="lucide:triangle-alert" class="size-4 shrink-0" />
|
|
||||||
<span>{{ signal ? `Nothing sends "${signal}" in this circuit, so it reads 0.` : 'Pick the signal it carries.' }}</span>
|
|
||||||
</p>
|
|
||||||
<div v-else class="sel-row">
|
|
||||||
<button class="btn grow" @click="ed.focusNode(senders[0]!.id)"><Icon name="lucide:locate-fixed" class="size-4" /> Go to source</button>
|
|
||||||
<button class="btn grow" @click="ed.selectSignal(signal)"><Icon name="lucide:scan-search" class="size-4" /> Select all</button>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<!-- Panel rows: switches, buttons and clocks, or lamps -->
|
|
||||||
<template v-if="n.kind === 'panel' || n.kind === 'outpanel'">
|
|
||||||
<p v-if="dock" class="result pass">
|
|
||||||
<Icon name="lucide:link" class="size-4 shrink-0" />
|
|
||||||
<span class="grow">Attached to {{ dock }}. It moves with it and gets a row for each new {{ outPanel ? 'output' : 'input' }}.</span>
|
|
||||||
<button class="btn-sm" title="Keep the panel and its wires, but stop following the component" @click="ed.undock(n)">Detach</button>
|
|
||||||
</p>
|
|
||||||
<div class="field">
|
|
||||||
<div class="rows-head">
|
|
||||||
<span>Rows</span>
|
|
||||||
<span v-if="!outPanel && (n.rows?.length ?? 0) > 1" class="rows-all">
|
|
||||||
all
|
|
||||||
<button v-for="c in CONTROLS" :key="c.value" class="kind-btn" :title="`Every row a ${c.label.toLowerCase()}`" @click="ed.setRowsType(n, c.value)">
|
|
||||||
<Icon :name="c.icon" class="size-3.5" />
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<ul ref="rowList" class="panel-rows" :class="{ dragging: !!rowDrag }">
|
|
||||||
<template v-for="(r, i) in n.rows ?? []" :key="r.id">
|
|
||||||
<!-- Between two rows: add one here, or more or less empty space -->
|
|
||||||
<li
|
|
||||||
v-if="!n.attach"
|
|
||||||
class="row-between"
|
|
||||||
:class="{ spaced: i > 0 && rowGaps[i]! > 0 }"
|
|
||||||
:style="i > 0 && rowGaps[i] ? { '--gap': Math.min(rowGaps[i]!, 5) } : undefined"
|
|
||||||
>
|
|
||||||
<span v-if="i > 0 && rowGaps[i]" class="gap-label">{{ rowGaps[i] }} empty</span>
|
|
||||||
<span class="between-tools">
|
|
||||||
<button :title="i === 0 ? 'Add a row above the first' : 'Add a row here'" @click="addAt(i)"><Icon name="lucide:plus" class="size-3" /> Row</button>
|
|
||||||
<template v-if="i > 0">
|
|
||||||
<button title="One empty row more here" @click="ed.setRowGap(n, i, rowGaps[i]! + 1)"><Icon name="lucide:plus" class="size-3" /> Space</button>
|
|
||||||
<button v-if="rowGaps[i]" title="One empty row less here" @click="ed.setRowGap(n, i, rowGaps[i]! - 1)"><Icon name="lucide:minus" class="size-3" /> Space</button>
|
|
||||||
</template>
|
|
||||||
</span>
|
|
||||||
</li>
|
|
||||||
<li class="row" :data-row-id="r.id" :class="{ lifted: rowDrag?.from === i, 'drop-above': dropAt === i, 'drop-below': dropAt === (n.rows?.length ?? 0) && i === (n.rows?.length ?? 0) - 1 }">
|
|
||||||
<span v-if="!n.attach" class="row-grip" title="Drag to move (or Alt + ↑ ↓ in the name)" @pointerdown="startRowDrag(i, $event)">
|
|
||||||
<Icon name="lucide:grip-vertical" class="size-3.5" />
|
|
||||||
</span>
|
|
||||||
<button
|
|
||||||
v-if="r.type !== 'clock' || outPanel"
|
|
||||||
class="row-color lamp-swatch"
|
|
||||||
:class="r.color ? `l-${r.color}` : [outPanel ? 'default' : 'default-on', { button: r.type === 'button' && !outPanel }]"
|
|
||||||
:title="`Colour while on: ${r.color ?? 'default'}. Click for the next, Shift + click for the one before`"
|
|
||||||
@click="nextColor(r, $event)"
|
|
||||||
/>
|
|
||||||
<span v-else class="row-color none" />
|
|
||||||
<input
|
|
||||||
class="row-name"
|
|
||||||
:value="r.label ?? ''"
|
|
||||||
:placeholder="rowLabel({ ...r, label: undefined }, i)"
|
|
||||||
title="Name"
|
|
||||||
@change="setRowLabel(r, $event)"
|
|
||||||
@keydown.tab="tabOn(r, i, $event)"
|
|
||||||
@keydown.up="moveByKey(i, $event)"
|
|
||||||
@keydown.down="moveByKey(i, $event)"
|
|
||||||
/>
|
|
||||||
<span v-if="!outPanel" class="kind-toggle" role="radiogroup" aria-label="Kind">
|
|
||||||
<button
|
|
||||||
v-for="c in CONTROLS"
|
|
||||||
:key="c.value"
|
|
||||||
role="radio"
|
|
||||||
:aria-checked="r.type === c.value"
|
|
||||||
:class="{ on: r.type === c.value }"
|
|
||||||
:title="c.label"
|
|
||||||
@click="ed.setRowType(r, c.value)"
|
|
||||||
>
|
|
||||||
<Icon :name="c.icon" class="size-3.5" />
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
<input
|
|
||||||
v-if="r.type === 'clock' && !outPanel"
|
|
||||||
type="number"
|
|
||||||
min="0.1"
|
|
||||||
max="1000"
|
|
||||||
step="any"
|
|
||||||
class="row-side hz"
|
|
||||||
:value="r.hz ?? ''"
|
|
||||||
placeholder="Hz"
|
|
||||||
title="Frequency in Hz; empty follows the top bar"
|
|
||||||
@change="setRowHz(r, $event)"
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
v-else-if="!outPanel"
|
|
||||||
class="row-side key-input"
|
|
||||||
:value="r.key?.toUpperCase() ?? ''"
|
|
||||||
readonly
|
|
||||||
placeholder="key"
|
|
||||||
title="Keyboard key: click, then press it (Backspace clears)"
|
|
||||||
@keydown="setRowKey(r, $event)"
|
|
||||||
/>
|
|
||||||
<button class="icon-btn" title="Remove this row" @click="ed.dropRow(n, r.id)"><Icon name="lucide:x" class="size-3.5" /></button>
|
|
||||||
</li>
|
|
||||||
</template>
|
|
||||||
<li v-if="!n.attach" class="row-between end">
|
|
||||||
<button class="add-row" title="Add a row below the last (or Tab in the last name)" @click="addAt(n.rows?.length ?? 0)">
|
|
||||||
<Icon name="lucide:plus" class="size-3.5" /> Add row
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
<EditorFold id="panel-options" title="Panel options">
|
|
||||||
<button class="btn w-full" :disabled="!n.rows?.length" @click="ed.startLinking([n.id], outPanel ? 'in' : 'out')">
|
|
||||||
<Icon name="lucide:cable" class="size-4" /> Wire rows one by one
|
|
||||||
</button>
|
|
||||||
<label
|
|
||||||
class="check mt-2"
|
|
||||||
:title="outPanel ? 'Used as a component, its rows are output pins (top to bottom, with the other outputs).' : 'Used as a component, its switch and button rows are its input pins (top to bottom, with the other inputs). Clock rows stay inside.'"
|
|
||||||
>
|
|
||||||
<input type="checkbox" :checked="!n.inner" @change="setInner(!($event.target as HTMLInputElement).checked)" />
|
|
||||||
Rows are component {{ outPanel ? 'outputs' : 'inputs' }}
|
|
||||||
</label>
|
|
||||||
</EditorFold>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<!-- Latched straight onto another part, or able to -->
|
|
||||||
<p v-if="n.latch" class="result pass">
|
|
||||||
<Icon name="lucide:link" class="size-4 shrink-0" />
|
|
||||||
<span class="grow">Latched onto {{ partName(n.latch) }}: it moves with it</span>
|
|
||||||
<button class="btn-sm" title="Let go: it steps aside and its wires show again" @click="ed.unlatch(n)">Unlatch</button>
|
|
||||||
</p>
|
|
||||||
<button v-else-if="latchHost" class="btn mb-2 w-full" :title="`Sit straight on the pins of ${partName(latchHost.id)}, without wires in between, and move along with it`" @click="ed.latchPart(n)">
|
|
||||||
<Icon name="lucide:link" class="size-4" /> Latch onto {{ partName(latchHost.id) }}
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<!-- Cable ends -->
|
|
||||||
<template v-if="n.kind === 'bundle' || n.kind === 'split'">
|
<template v-if="n.kind === 'bundle' || n.kind === 'split'">
|
||||||
<p v-if="n.plug" class="result pass">
|
<p v-if="n.plug" class="result pass">
|
||||||
<Icon name="lucide:plug-zap" class="size-4 shrink-0" />
|
<Icon name="lucide:plug-zap" class="size-4 shrink-0" />
|
||||||
<span class="grow">Plugged into {{ partName(n.plug) }}</span>
|
<span class="grow">Plugged into {{ partName(n.plug) }}. It moves with it; drag it away to pull it out.</span>
|
||||||
<button class="btn-sm" title="Pull it out: it steps aside and its wires show again" @click="ed.unplugEnd(n)">Unplug</button>
|
<button class="btn-sm" title="Pull it out: it steps aside and its wires show again" @click="ed.unplugEnd(n)">Unplug</button>
|
||||||
</p>
|
</p>
|
||||||
<button v-else-if="plugPart" class="btn mb-2 w-full" :title="`Sit straight on the pins of ${partName(plugPart.id)}, without wires in between`" @click="ed.plugEnd(n)">
|
<button
|
||||||
|
v-else-if="plugPart"
|
||||||
|
class="btn mb-2 w-full"
|
||||||
|
:title="`Sit straight on the pins of ${partName(plugPart.id)}, without wires in between`"
|
||||||
|
@click="ed.plugEnd(n)"
|
||||||
|
>
|
||||||
<Icon name="lucide:plug" class="size-4" /> Plug into {{ partName(plugPart.id) }}
|
<Icon name="lucide:plug" class="size-4" /> Plug into {{ partName(plugPart.id) }}
|
||||||
</button>
|
</button>
|
||||||
<button v-if="!cableBundle" class="btn btn-primary mb-2 w-full" title="Click where its other end goes, or drag the cable out of its pin" @click="pullOut">
|
<button
|
||||||
<Icon name="lucide:cable" class="size-4" /> Pull the cable out
|
v-if="n.kind === 'bundle' && undriven && !n.plug"
|
||||||
|
class="btn mb-2 w-full"
|
||||||
|
title="A switch for every wire nothing drives yet; the cable plugs into it. Make each row a button or clock, give it a key or colour."
|
||||||
|
@click="ed.addCablePanel(n.id)"
|
||||||
|
>
|
||||||
|
<Icon name="lucide:sliders-vertical" class="size-4" /> Attach input panel
|
||||||
</button>
|
</button>
|
||||||
<div class="sel-row">
|
<div class="grid grid-cols-2 gap-2">
|
||||||
<label class="field grow">
|
<label class="field">
|
||||||
<span>Wires</span>
|
<span>Wires</span>
|
||||||
<input type="number" min="2" :max="MAX_BITS" step="1" :value="cableBits(n)" @change="ed.setBits(n, Number(($event.target as HTMLInputElement).value))" />
|
<input type="number" min="2" :max="MAX_BITS" step="1" :value="cableBits(n)" @change="ed.setBits(n, Number(($event.target as HTMLInputElement).value))" />
|
||||||
</label>
|
</label>
|
||||||
<label class="field grow" :title="n.plug ? 'Set by the pins it is plugged into' : 'Rows from one wire to the next, to line up with pins further apart'">
|
<label class="field" :title="n.plug ? 'Set by the pins it is plugged into' : 'Rows from one wire to the next, to line up with pins further apart'">
|
||||||
<span>Spacing</span>
|
<span>Spacing</span>
|
||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
|
|
@ -682,9 +550,9 @@ function setChannelBits(i: number, v: string) {
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<EditorFold id="cable-more" title="Cable" :note="n.names?.some(Boolean) ? n.names.map((x, i) => x || i).join(', ') : ''">
|
<p v-if="n.names?.some(Boolean)" class="hint -mt-1">Wires: {{ n.names.map((x, i) => x || i).join(', ') }}</p>
|
||||||
<div v-if="cableBundle" class="field">
|
<div v-if="cableBundle" class="field">
|
||||||
<span>Sleeve colour</span>
|
<span>Sleeve colour (the wires inside keep theirs)</span>
|
||||||
<div class="swatches">
|
<div class="swatches">
|
||||||
<button class="swatch none" :class="{ active: !sleeveColor }" title="Default: grey" @click="ed.setCableColor(cableBundle.id, undefined)" />
|
<button class="swatch none" :class="{ active: !sleeveColor }" title="Default: grey" @click="ed.setCableColor(cableBundle.id, undefined)" />
|
||||||
<button
|
<button
|
||||||
|
|
@ -697,145 +565,73 @@ function setChannelBits(i: number, v: string) {
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<button
|
<p class="hint">Drag the bundle and the split to decide where the cable starts and ends. Drop an end with its pins on a part's pins to plug it in.</p>
|
||||||
v-if="n.kind === 'bundle' && undriven && !n.plug"
|
<button v-if="cableBundle" class="btn mb-2 w-full" title="Take the cable apart again into single wires" @click="ed.removeCable(cableBundle.id)">
|
||||||
class="btn mb-2 w-full"
|
|
||||||
title="A switch for every wire nothing drives yet; the cable plugs into it"
|
|
||||||
@click="ed.addCablePanel(n.id)"
|
|
||||||
>
|
|
||||||
<Icon name="lucide:sliders-vertical" class="size-4" /> Attach input panel
|
|
||||||
</button>
|
|
||||||
<button v-if="cableBundle" class="btn w-full" title="Take the cable apart again into single wires" @click="ed.removeCable(cableBundle.id)">
|
|
||||||
<Icon name="lucide:split" class="size-4" /> Remove cable
|
<Icon name="lucide:split" class="size-4" /> Remove cable
|
||||||
</button>
|
</button>
|
||||||
</EditorFold>
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<!-- Less used, folded away -->
|
<p v-if="HINTS[n.kind]" class="hint">{{ HINTS[n.kind] }}</p>
|
||||||
<EditorFold v-if="n.kind === 'input' || n.kind === 'button'" id="keyboard" title="Keyboard key" :note="n.key?.toUpperCase() ?? ''">
|
|
||||||
<input :value="n.key ?? ''" readonly placeholder="Click, then press a key" class="key-input field-input" @keydown="setKey" />
|
|
||||||
</EditorFold>
|
|
||||||
|
|
||||||
<div v-if="isDisplay(n.kind)" class="field">
|
<template v-if="n.kind === 'chip' && chipDef">
|
||||||
<span>Size in {{ DISPLAY_SIZES[n.kind as DisplayKind].unit }}<template v-if="n.kind !== 'terminal'"> · {{ ratioText(...displaySize(n)) }}</template></span>
|
|
||||||
<div class="size-row">
|
|
||||||
<input class="field-input" type="number" :min="DISPLAY_SIZES[n.kind as DisplayKind].min[0]" :max="DISPLAY_SIZES[n.kind as DisplayKind].max[0]" :value="displaySize(n)[0]" title="Wide" @change="ed.setDims(n.id, Number(($event.target as HTMLInputElement).value), displaySize(n)[1])" />
|
|
||||||
<span>×</span>
|
|
||||||
<input class="field-input" type="number" :min="DISPLAY_SIZES[n.kind as DisplayKind].min[1]" :max="DISPLAY_SIZES[n.kind as DisplayKind].max[1]" :value="displaySize(n)[1]" title="High" @change="ed.setDims(n.id, displaySize(n)[0], Number(($event.target as HTMLInputElement).value))" />
|
|
||||||
<button class="btn-sm" title="Turn a quarter: width and height swap" @click="ed.turnDisplay(n.id)"><Icon name="lucide:rotate-cw-square" class="size-3.5" /> Turn</button>
|
|
||||||
</div>
|
|
||||||
<div v-if="n.kind !== 'terminal'" class="size-presets">
|
|
||||||
<button v-for="p in SIZE_PRESETS" :key="p.join('x')" class="btn-sm" @click="ed.setDims(n.id, p[0], p[1])">{{ p[0] }}×{{ p[1] }}</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div v-if="n.kind === 'scope'" class="field">
|
|
||||||
<span>Channels: wire to their pins on the left</span>
|
|
||||||
<div v-for="(c, i) in n.scope?.cols ?? []" :key="c.id" class="scope-chan">
|
|
||||||
<input class="field-input" :value="c.name" spellcheck="false" @change="renameChannel(i, ($event.target as HTMLInputElement).value)" />
|
|
||||||
<input class="field-input scope-bits" type="number" min="1" max="32" :value="c.bits" title="Bits: one pin each, read as one number" @change="setChannelBits(i, ($event.target as HTMLInputElement).value)" />
|
|
||||||
<button class="icon-btn" title="Remove the channel" @click="ed.setScope(n.id, cols => cols.splice(i, 1))"><Icon name="lucide:trash-2" class="size-3.5" /></button>
|
|
||||||
</div>
|
|
||||||
<div class="flex gap-2">
|
|
||||||
<button class="btn-sm" @click="addChannel(1)"><Icon name="lucide:plus" class="size-3.5" /> Wire</button>
|
|
||||||
<button class="btn-sm" @click="addChannel(8)"><Icon name="lucide:plus" class="size-3.5" /> 8-bit bus</button>
|
|
||||||
<button class="btn-sm" @click="ed.clearScope(n.id)"><Icon name="lucide:eraser" class="size-3.5" /> Start over</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<EditorFold v-if="n.kind === 'pixel'" id="pixel-screen" title="Screen on the box" :note="n.screen ?? ''">
|
|
||||||
<input
|
|
||||||
class="field-input"
|
|
||||||
:value="n.screen ?? ''"
|
|
||||||
list="screen-names"
|
|
||||||
placeholder="Main screen"
|
|
||||||
title="Pixels with the same screen name make one screen on the component's box"
|
|
||||||
@change="ed.setScreen([n.id], ($event.target as HTMLInputElement).value)"
|
|
||||||
@keydown.enter="($event.target as HTMLInputElement).blur()"
|
|
||||||
/>
|
|
||||||
<datalist id="screen-names">
|
|
||||||
<option v-for="name in screenNames" :key="name" :value="name" />
|
|
||||||
</datalist>
|
|
||||||
</EditorFold>
|
|
||||||
|
|
||||||
<EditorFold v-if="invertible.length || cables.out.length || cables.in.length || chipInputs || chipOutputs" id="pins" title="Pins" :note="inverted ? `${inverted} inverted` : ''">
|
|
||||||
<div v-if="invertible.length" class="field">
|
|
||||||
<span>Inverted inputs (Alt + click a pin)</span>
|
|
||||||
<div class="invert-pins">
|
|
||||||
<button
|
|
||||||
v-for="p in invertible"
|
|
||||||
:key="p.key"
|
|
||||||
class="invert-pin"
|
|
||||||
:class="{ on: p.on }"
|
|
||||||
:title="p.on ? 'Inverted: one NAND, 4 transistors. Click to take the bubble off.' : 'Invert this input'"
|
|
||||||
@click="ed.toggleInvert(n, p.key)"
|
|
||||||
>
|
|
||||||
<span class="dot" />{{ p.label }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div v-if="cables.out.length || cables.in.length" class="field cable-choices">
|
|
||||||
<span>Plug a cable onto its pins</span>
|
|
||||||
<div v-if="cables.out.length" class="cable-row">
|
|
||||||
<span class="hint">From outputs</span>
|
|
||||||
<button v-for="g in cables.out" :key="g.label" class="btn-sm" :title="`A plug for a cable with ${g.pins.length} wires on these pins`" @click="ed.cableOut(n.id, g.pins)">{{ g.label }}</button>
|
|
||||||
</div>
|
|
||||||
<div v-if="cables.in.length" class="cable-row">
|
|
||||||
<span class="hint">Into inputs</span>
|
|
||||||
<button v-for="g in cables.in" :key="g.label" class="btn-sm" :title="`A plug for a cable with ${g.pins.length} wires on these pins`" @click="ed.cableIn(n.id, g.pins)">{{ g.label }}</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div v-if="chipInputs || chipOutputs" class="field mb-0">
|
|
||||||
<span>Wire one by one</span>
|
|
||||||
<div class="sel-row">
|
|
||||||
<button class="btn grow" :disabled="!chipInputs" title="Click the source for each input in turn" @click="ed.startLinking([n.id], 'in')">
|
|
||||||
<Icon name="lucide:cable" class="size-4" /> Inputs
|
|
||||||
</button>
|
|
||||||
<button class="btn grow" :disabled="!chipOutputs" title="Click the target for each output in turn" @click="ed.startLinking([n.id], 'out')">
|
|
||||||
<Icon name="lucide:cable" class="size-4" /> Outputs
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</EditorFold>
|
|
||||||
|
|
||||||
<EditorFold v-if="n.kind === 'chip' && chipDef" id="component" title="Component">
|
|
||||||
<p v-if="chipDef.description" class="hint">{{ chipDef.description }}</p>
|
<p v-if="chipDef.description" class="hint">{{ chipDef.description }}</p>
|
||||||
<dl v-if="chipStats" class="stats">
|
<dl v-if="chipStats" class="stats">
|
||||||
<dt>{{ chipStats.sequential ? 'Memory' : 'Delay' }}</dt>
|
<dt>{{ chipStats.sequential ? 'Memory' : 'Delay' }}</dt>
|
||||||
<dd>{{ chipStats.sequential ? 'yes (feedback)' : `${chipStats.delay} gates` }}</dd>
|
<dd>{{ chipStats.sequential ? 'yes (feedback)' : `${chipStats.delay} gates` }}</dd>
|
||||||
</dl>
|
</dl>
|
||||||
<div class="grid gap-2">
|
<div class="grid gap-2">
|
||||||
|
<button class="btn w-full" @click="ed.open(chipDef.id)"><Icon name="lucide:log-in" class="size-4" /> Open component</button>
|
||||||
<button class="btn w-full" title="Move its lamps and displays, draw on it, size it: for every copy" @click="ed.designFace(chipDef.id)">
|
<button class="btn w-full" title="Move its lamps and displays, draw on it, size it: for every copy" @click="ed.designFace(chipDef.id)">
|
||||||
<Icon name="lucide:pen-tool" class="size-4" /> Design its box
|
<Icon name="lucide:pen-tool" class="size-4" /> Design its box
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
v-for="p in boxPorts"
|
v-if="chipInputs && !hasPanel"
|
||||||
:key="p.key"
|
|
||||||
class="btn w-full"
|
class="btn w-full"
|
||||||
:title="p.split ? 'Only the socket again; wires on its lines are removed' : 'A pin per line below the socket, to wire lines by hand; a cable still plugs into the socket'"
|
title="A switch for every free input, docked to the left; each one can become a button or clock"
|
||||||
@click="ed.toggleSplit(n, p.key)"
|
@click="ed.addPanel(n.id)"
|
||||||
>
|
>
|
||||||
<Icon :name="p.split ? 'lucide:merge' : 'lucide:split'" class="size-4" /> {{ p.split ? `Join ${p.name} lines` : `Split ${p.name} into lines` }}
|
<Icon name="lucide:sliders-vertical" class="size-4" /> Attach input panel
|
||||||
</button>
|
</button>
|
||||||
<div v-if="(chipInputs && !hasPanel) || (chipOutputs && !hasOutPanel)" class="sel-row">
|
<button v-if="chipOutputs && !hasOutPanel" class="btn w-full" title="A lamp for every output, docked to the right" @click="ed.addPanel(n.id, 'out')">
|
||||||
<button v-if="chipInputs && !hasPanel" class="btn grow" title="A switch for every free input, docked to the left" @click="ed.addPanel(n.id)">
|
<Icon name="lucide:list-checks" class="size-4" /> Attach output panel
|
||||||
<Icon name="lucide:sliders-vertical" class="size-4" /> Input panel
|
|
||||||
</button>
|
</button>
|
||||||
<button v-if="chipOutputs && !hasOutPanel" class="btn grow" title="A lamp for every output, docked to the right" @click="ed.addPanel(n.id, 'out')">
|
<div v-if="chipInputs || chipOutputs" class="field mb-0">
|
||||||
<Icon name="lucide:list-checks" class="size-4" /> Output panel
|
<span>Wire one by one</span>
|
||||||
|
<div class="grid grid-cols-2 gap-2">
|
||||||
|
<button class="btn" :disabled="!chipInputs" title="Click the source for each input in turn" @click="ed.startLinking([n.id], 'in')">
|
||||||
|
<Icon name="lucide:cable" class="size-4" /> Inputs
|
||||||
</button>
|
</button>
|
||||||
</div>
|
<button class="btn" :disabled="!chipOutputs" title="Click the target for each output in turn" @click="ed.startLinking([n.id], 'out')">
|
||||||
<div class="sel-row">
|
<Icon name="lucide:cable" class="size-4" /> Outputs
|
||||||
<button class="btn grow" title="Replace it with the parts inside; outside wires join them directly" @click="ed.unpack(n.id)">
|
|
||||||
<Icon name="lucide:ungroup" class="size-4" /> Unpack
|
|
||||||
</button>
|
|
||||||
<button class="btn grow" title="Give this one its own copy, so changing it leaves the others alone" @click="ed.makeIndependent(n.id)">
|
|
||||||
<Icon name="lucide:copy-plus" class="size-4" /> Own copy
|
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</EditorFold>
|
<button class="btn w-full" title="Replace it with the parts inside; outside wires join them directly" @click="ed.unpack(n.id)">
|
||||||
|
<Icon name="lucide:ungroup" class="size-4" /> Unpack into parts
|
||||||
|
</button>
|
||||||
|
<button class="btn w-full" title="Give this one its own copy, so changing it leaves the others alone" @click="ed.makeIndependent(n.id)">
|
||||||
|
<Icon name="lucide:copy-plus" class="size-4" /> Make independent copy
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
<EditorContextMenu v-if="more" :x="more.x" :y="more.y" :entries="more.entries" @close="more = null" />
|
<div class="mt-3 grid grid-cols-2 gap-2">
|
||||||
|
<label class="field mb-0">
|
||||||
|
<span>X</span>
|
||||||
|
<input type="number" step="1" :value="n.x" @change="setPos('x', $event)" />
|
||||||
|
</label>
|
||||||
|
<label class="field mb-0">
|
||||||
|
<span>Y</span>
|
||||||
|
<input type="number" step="1" :value="n.y" @change="setPos('y', $event)" />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-3 grid grid-cols-2 gap-2">
|
||||||
|
<button class="btn" :disabled="!wired" title="Remove every wire attached to it" @click="ed.unlink([n.id])">
|
||||||
|
<Icon name="lucide:unlink" class="size-4" /> Unlink all
|
||||||
|
</button>
|
||||||
|
<button class="btn" @click="ed.duplicate()"><Icon name="lucide:copy" class="size-4" /> Duplicate</button>
|
||||||
|
</div>
|
||||||
|
<button class="btn btn-ghost mt-2 w-full" @click="ed.deleteSelected()"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
|
|
|
||||||
|
|
@ -2,11 +2,7 @@
|
||||||
import { gateDrawing, sevenSegment } from '~/lib/draw'
|
import { gateDrawing, sevenSegment } from '~/lib/draw'
|
||||||
import { LANE, nameTags, RIBBON_MAX } from '~/lib/logic/cables'
|
import { LANE, nameTags, RIBBON_MAX } from '~/lib/logic/cables'
|
||||||
import { baseOf, gateFamily, inputCount, MAX_GATE_INPUTS } from '~/lib/logic/wide'
|
import { baseOf, gateFamily, inputCount, MAX_GATE_INPUTS } from '~/lib/logic/wide'
|
||||||
import { faceTransform, GRID as G, noteLines, noteScale, PANEL_CONTROL_W, portLines, rgbHex, shapeTransform, type Shape } from '~/lib/logic/geometry'
|
import { faceTransform, GRID as G, noteLines, noteScale, PANEL_CONTROL_W, shapeTransform, type Shape } from '~/lib/logic/geometry'
|
||||||
import { benchLayout } from '~/lib/logic/benchLayout'
|
|
||||||
import { SCOPE_CELL, SCOPE_SAMPLES, scopeLayout } from '~/lib/logic/scopeLayout'
|
|
||||||
import { keyLabel } from '~/lib/logic/devices'
|
|
||||||
import { displayLayout, displaySize, isDisplay, MONO_PIXEL, ratioText, RGB_PIXEL, TERM_CHAR } from '~/lib/logic/displays'
|
|
||||||
import type { CircuitNode } from '~/lib/logic/types'
|
import type { CircuitNode } from '~/lib/logic/types'
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
|
|
@ -30,16 +26,6 @@ const style = computed(() => ed.project.value.settings.symbols)
|
||||||
const gate = computed(() => (props.shape.gate ? gateDrawing(props.shape, style.value) : null))
|
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 chipDef = computed(() => (props.node.chip ? ed.getDef.value(props.node.chip) : undefined))
|
||||||
const b = computed(() => props.shape.body)
|
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 ?? [])
|
const rows = computed(() => props.node.rows ?? [])
|
||||||
// A name typed by hand shows as is. Otherwise the name of the pin the part is
|
// 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.
|
// wired to, or its automatic name, shows dimmed.
|
||||||
|
|
@ -128,43 +114,6 @@ const bubbles = computed(() => {
|
||||||
return props.shape.inputs.filter(p => inv.has(p.key)).map(p => ({ key: p.key, x: (p.dx + dx) * G, y: p.dy * G }))
|
return props.shape.inputs.filter(p => inv.has(p.key)).map(p => ({ key: p.key, x: (p.dx + dx) * G, y: p.dy * G }))
|
||||||
})
|
})
|
||||||
|
|
||||||
/** Pin names on a component's box, each on its own edge; the lines of a split port sit in a little from their socket. */
|
|
||||||
const boxLabels = computed(() =>
|
|
||||||
[...props.shape.inputs, ...props.shape.outputs].map(p => {
|
|
||||||
const left = p.dx === 0
|
|
||||||
const inset = p.port ? 11 : 5
|
|
||||||
return { key: p.key, label: p.label, y: p.dy * G + 3.5, x: left ? inset : p.dx * G - inset, anchor: left ? 'start' : 'end' }
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Split ports on a component's box, in the type's colour: a bar from the
|
|
||||||
* socket down along its lines, and a line above and below them that marks
|
|
||||||
* off which pins are its wires, from the pin tips to past their names.
|
|
||||||
*/
|
|
||||||
const portBars = computed(() => {
|
|
||||||
const pins = [...props.shape.inputs, ...props.shape.outputs]
|
|
||||||
return pins.flatMap(p => {
|
|
||||||
const lines = p.conn ? pins.filter(l => l.port === p.key) : []
|
|
||||||
if (!lines.length) return []
|
|
||||||
const inward = p.dx === 0 ? 1 : -1
|
|
||||||
const x = p.dx * G
|
|
||||||
const top = (Math.min(...lines.map(l => l.dy)) - 0.5) * G
|
|
||||||
const bottom = (Math.max(...lines.map(l => l.dy)) + 0.5) * G
|
|
||||||
const outer = x - inward * 9
|
|
||||||
const inner = x + inward * Math.min(15 + Math.max(...lines.map(l => l.label.length)) * 5.6, (props.shape.body.w * G) / 2)
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
key: p.key,
|
|
||||||
conn: p.conn,
|
|
||||||
// From the socket's inner corner, down between the line pins and their names.
|
|
||||||
bar: `M${x + inward * 4} ${p.dy * G + 5}H${x + inward * 7}V${bottom}`,
|
|
||||||
bounds: `M${outer} ${top}H${inner}M${outer} ${bottom}H${inner}`,
|
|
||||||
},
|
|
||||||
]
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
/** The edge a plugged cable end touches its part with. */
|
/** The edge a plugged cable end touches its part with. */
|
||||||
const seam = computed(() => (props.node.kind === 'bundle' ? 0 : G))
|
const seam = computed(() => (props.node.kind === 'bundle' ? 0 : G))
|
||||||
|
|
||||||
|
|
@ -172,139 +121,6 @@ const v = (pin: string) => (props.ghost ? 0 : ed.val(props.node.id, pin))
|
||||||
/** Value inside this chip, for its lamps and displays. */
|
/** Value inside this chip, for its lamps and displays. */
|
||||||
const fv = (inner: string, pin: string) => (props.ghost ? 0 : ed.faceVal(props.node.id, inner, pin))
|
const fv = (inner: string, pin: string) => (props.ghost ? 0 : ed.faceVal(props.node.id, inner, pin))
|
||||||
const faceHex = (inner: string) => sevenSegment([0, 1, 2, 3].reduce((n, i) => n + (fv(inner, `b${i}`) << i), 0))
|
const faceHex = (inner: string) => sevenSegment([0, 1, 2, 3].reduce((n, i) => n + (fv(inner, `b${i}`) << i), 0))
|
||||||
/** The colour of an RGB pixel inside this chip ('' while off). */
|
|
||||||
const facePx = (inner: string) => rgbHex(fv(inner, 'r'), fv(inner, 'g'), fv(inner, 'b'))
|
|
||||||
const rgbNow = computed(() => (props.node.rgb ? rgbHex(v('r'), v('g'), v('b')) : ''))
|
|
||||||
// Logic analyzer: its lanes from what the store recorded.
|
|
||||||
const sl = computed(() => scopeLayout(props.node))
|
|
||||||
const scopeView = computed(() => {
|
|
||||||
const n = props.node
|
|
||||||
if (n.kind !== 'scope' || props.ghost) return { lanes: [], marks: [] as number[] }
|
|
||||||
void ed.scopeVersion.value
|
|
||||||
const all = ed.scopeTraces.value.get(n.id) ?? []
|
|
||||||
const list = all.slice(-SCOPE_SAMPLES)
|
|
||||||
const x0 = sl.value.waveX * G
|
|
||||||
const marks: number[] = []
|
|
||||||
list.forEach((s, k) => k && s.cycle !== list[k - 1]!.cycle && marks.push(x0 + k * SCOPE_CELL))
|
|
||||||
const lanes = sl.value.lanes.map((l, i) => {
|
|
||||||
const top = (l.row - 0.5) * G + 3
|
|
||||||
const bottom = (l.row - 0.5 + l.bits) * G - 3
|
|
||||||
const hex = (v: number) => `0x${v.toString(16).toUpperCase().padStart(Math.ceil(l.bits / 4), '0')}`
|
|
||||||
const now = list[list.length - 1]?.vals[i]
|
|
||||||
const value = now === undefined ? '' : l.bits === 1 ? String(now) : `${now} ${hex(now)}`
|
|
||||||
let wave = ''
|
|
||||||
const runs: { d: string; mid: number; label: string }[] = []
|
|
||||||
if (l.bits === 1) {
|
|
||||||
list.forEach((s, k) => {
|
|
||||||
const y = s.vals[i] ? top : bottom
|
|
||||||
wave += k ? `V${y}H${x0 + (k + 1) * SCOPE_CELL}` : `M${x0} ${y}H${x0 + SCOPE_CELL}`
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
let start = 0
|
|
||||||
for (let k = 1; k <= list.length; k++) {
|
|
||||||
if (k < list.length && list[k]!.vals[i] === list[start]!.vals[i]) continue
|
|
||||||
const a = x0 + start * SCOPE_CELL
|
|
||||||
const z = x0 + k * SCOPE_CELL
|
|
||||||
const m = Math.min(3, (z - a) / 3)
|
|
||||||
const c = (top + bottom) / 2
|
|
||||||
const v = list[start]!.vals[i]!
|
|
||||||
const label = l.bits <= 4 ? hex(v).slice(2) : hex(v)
|
|
||||||
runs.push({ d: `M${a} ${c}L${a + m} ${top}H${z - m}L${z} ${c}L${z - m} ${bottom}H${a + m}Z`, mid: (a + z) / 2, label: z - a >= label.length * 6 + 6 ? label : '' })
|
|
||||||
start = k
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { id: l.col.id, row: l.row, bits: l.bits, value, wave, runs }
|
|
||||||
})
|
|
||||||
return { lanes, marks }
|
|
||||||
})
|
|
||||||
|
|
||||||
// Test bench: the layout of its box, its rows and how they went.
|
|
||||||
interface BenchRowView {
|
|
||||||
i: number
|
|
||||||
state: string
|
|
||||||
live: boolean
|
|
||||||
cells: { key: string; x: number; text: string; cls: string }[]
|
|
||||||
title: string
|
|
||||||
}
|
|
||||||
const bl = computed(() => benchLayout(props.node))
|
|
||||||
const benchTitleW = computed(() => ((props.node.label?.trim() || 'Test bench').length * 6.4 + 10))
|
|
||||||
const bench = computed(() => {
|
|
||||||
const n = props.node
|
|
||||||
const empty = { state: 'idle', line: '', cols: false, rows: [] as BenchRowView[], right: 0 }
|
|
||||||
if (n.kind !== 'bench') return empty
|
|
||||||
const l = bl.value
|
|
||||||
const right = l.x + Math.max(l.tableW, 9)
|
|
||||||
const cols = !!n.bench?.cols?.length
|
|
||||||
if (!cols) return { ...empty, right }
|
|
||||||
const r = props.ghost ? undefined : ed.benchResults.value.get(n.id)
|
|
||||||
const live = props.ghost ? undefined : ed.benchLive.value.get(n.id)
|
|
||||||
const rows: BenchRowView[] = (n.bench?.rows ?? []).slice(0, l.shown).map((row, i) => {
|
|
||||||
const res = r?.rows[i]
|
|
||||||
const state = res?.ok === false ? 'fail' : res?.ok ? 'pass' : ''
|
|
||||||
const cells = l.cols.map(c => {
|
|
||||||
if (c.col === '#') return { key: c.key, x: c.x, text: String(i + 1), cls: 'num' }
|
|
||||||
if (c.col === 'ticks') return { key: c.key, x: c.x, text: row.ticks ?? '', cls: 'num' }
|
|
||||||
if (c.col === 'state') return { key: c.key, x: c.x, text: res?.ok === false ? '✗' : res?.ok ? '✓' : '', cls: state }
|
|
||||||
if (c.drive) return { key: c.key, x: c.x, text: row.set?.[c.col] ?? '', cls: 'drive' }
|
|
||||||
const want = row.expect?.[c.col] ?? ''
|
|
||||||
const got = res?.got[c.col]
|
|
||||||
const wrong = res?.ok === false && want !== '' && got !== undefined && Number(want) !== got
|
|
||||||
return { key: c.key, x: c.x, text: want || (got !== undefined ? String(got) : ''), cls: wrong ? 'wrong' : want ? '' : 'got' }
|
|
||||||
})
|
|
||||||
const gotText = res ? Object.entries(res.got).map(([id, v]) => `${n.bench?.cols?.find(c => c.id === id)?.name ?? id} = ${v}`).join(', ') : ''
|
|
||||||
return { i, state, live: live === i, cells, title: [res?.error, gotText && `Reads ${gotText}`, 'Click: put this row on the circuit'].filter(Boolean).join('\n') }
|
|
||||||
})
|
|
||||||
const line = !n.bench?.rows.length ? 'no rows yet: double-click' : !r ? '' : r.error && !r.fail ? r.error : r.fail ? `✗ ${r.fail} failing` : r.pass ? `✓ ${r.pass} pass` : ''
|
|
||||||
return { state: r?.fail || (r?.error && !r.pass) ? 'fail' : r?.pass ? 'pass' : 'idle', line, cols, rows, right }
|
|
||||||
})
|
|
||||||
|
|
||||||
// Terminal and monitors: what the store keeps for this part, and its size.
|
|
||||||
const display = computed(() => isDisplay(props.node.kind))
|
|
||||||
const dl = computed(() => (display.value ? displayLayout(props.node) : { w: 0, h: 0, sx: 0, sy: 0, sw: 0, sh: 0, cw: 0, ch: 0 }))
|
|
||||||
const TERM_PX = TERM_CHAR * G
|
|
||||||
const sizeText = computed(() => {
|
|
||||||
if (!display.value) return ''
|
|
||||||
const [w, h] = displaySize(props.node)
|
|
||||||
return props.node.kind === 'terminal' ? `${w} × ${h} characters` : `${w} × ${h} · ${ratioText(w, h)}`
|
|
||||||
})
|
|
||||||
const termLines = computed(() => {
|
|
||||||
if (props.node.kind !== 'terminal' || props.ghost) return []
|
|
||||||
void ed.devVersion.value
|
|
||||||
return (ed.screens.value.get(props.node.id) ?? ['']).slice(-displaySize(props.node)[1])
|
|
||||||
})
|
|
||||||
const termCursor = computed(() => {
|
|
||||||
const lines = termLines.value.length ? termLines.value : ['']
|
|
||||||
return { x: Math.min(displaySize(props.node)[0] - 1, lines[lines.length - 1]!.length), y: lines.length - 1 }
|
|
||||||
})
|
|
||||||
/** A monitor's pixels as an image, made again when they change. */
|
|
||||||
const frameUrl = computed(() => {
|
|
||||||
const n = props.node
|
|
||||||
if ((n.kind !== 'monitor' && n.kind !== 'rgbmonitor') || props.ghost || typeof document === 'undefined') return ''
|
|
||||||
void ed.devVersion.value
|
|
||||||
const f = ed.frames.value.get(n.id)
|
|
||||||
if (!f) return ''
|
|
||||||
const c = document.createElement('canvas')
|
|
||||||
c.width = f.w
|
|
||||||
c.height = f.h
|
|
||||||
const ctx = c.getContext('2d')
|
|
||||||
if (!ctx) return ''
|
|
||||||
const img = ctx.createImageData(f.w, f.h)
|
|
||||||
const palette = (n.kind === 'rgbmonitor' ? RGB_PIXEL : ['#000000', MONO_PIXEL]).map(h => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)])
|
|
||||||
for (let i = 0; i < f.px.length; i++) {
|
|
||||||
const [r, g, bl] = palette[f.px[i]!] ?? palette[0]!
|
|
||||||
img.data.set([r!, g!, bl!, f.px[i] ? 255 : 0], i * 4)
|
|
||||||
}
|
|
||||||
ctx.putImageData(img, 0, 0)
|
|
||||||
return c.toDataURL()
|
|
||||||
})
|
|
||||||
const kbTyping = computed(() => ed.typingInto.value === props.node.id)
|
|
||||||
const kbWaiting = computed(() => {
|
|
||||||
if (props.node.kind !== 'keyboard' || props.ghost) return []
|
|
||||||
void ed.devVersion.value
|
|
||||||
return [...(ed.keyQueues.value.get(props.node.id) ?? [])]
|
|
||||||
})
|
|
||||||
const kbQueue = computed(() => kbWaiting.value.slice(0, 6).map(keyLabel).join(''))
|
|
||||||
const kbCount = computed(() => (kbWaiting.value.length ? `${kbWaiting.value.length} waiting` : ''))
|
|
||||||
const FACE_SCALE = 0.6
|
const FACE_SCALE = 0.6
|
||||||
const hexValue = computed(() => [0, 1, 2, 3].reduce((n, i) => n + (v(`b${i}`) << i), 0))
|
const hexValue = computed(() => [0, 1, 2, 3].reduce((n, i) => n + (v(`b${i}`) << i), 0))
|
||||||
const segments = computed(() => sevenSegment(hexValue.value))
|
const segments = computed(() => sevenSegment(hexValue.value))
|
||||||
|
|
@ -377,7 +193,6 @@ const title = computed(() => {
|
||||||
class="chip-name"
|
class="chip-name"
|
||||||
>{{ chipDef?.name ?? 'Missing' }}</text>
|
>{{ chipDef?.name ?? 'Missing' }}</text>
|
||||||
<g v-for="f in shape.face" :key="f.id" :transform="faceTransform(f)">
|
<g v-for="f in shape.face" :key="f.id" :transform="faceTransform(f)">
|
||||||
<title v-if="f.from">{{ f.label || (f.kind === 'screen' ? 'Screen' : f.kind === 'hex' ? 'Display' : 'Lamp') }} from {{ f.from }}</title>
|
|
||||||
<template v-if="f.kind === 'screen'">
|
<template v-if="f.kind === 'screen'">
|
||||||
<rect :x="f.x * G - 2" :y="f.y * G - 2" :width="f.w * G + 4" :height="f.h * G + 4" rx="2" class="screen-bg" />
|
<rect :x="f.x * G - 2" :y="f.y * G - 2" :width="f.w * G + 4" :height="f.h * G + 4" rx="2" class="screen-bg" />
|
||||||
<rect
|
<rect
|
||||||
|
|
@ -388,8 +203,7 @@ const title = computed(() => {
|
||||||
:width="f.px! * G - 0.5"
|
:width="f.px! * G - 0.5"
|
||||||
:height="f.px! * G - 0.5"
|
:height="f.px! * G - 0.5"
|
||||||
class="screen-px"
|
class="screen-px"
|
||||||
:class="p.rgb ? { on: !!facePx(p.id) } : [p.color ? `px-${p.color}` : '', { on: fv(p.id, 'a') === 1 }]"
|
:class="[p.color ? `px-${p.color}` : '', { on: fv(p.id, 'a') === 1 }]"
|
||||||
:style="p.rgb && facePx(p.id) ? { '--px': facePx(p.id) } : undefined"
|
|
||||||
/>
|
/>
|
||||||
</template>
|
</template>
|
||||||
<template v-else-if="f.kind === 'lamp'">
|
<template v-else-if="f.kind === 'lamp'">
|
||||||
|
|
@ -403,11 +217,8 @@ const title = computed(() => {
|
||||||
</template>
|
</template>
|
||||||
<text v-if="f.label" :x="(f.x + f.w / 2) * G" :y="(f.y + f.h - 0.15) * G" text-anchor="middle" class="face-label">{{ f.label }}</text>
|
<text v-if="f.label" :x="(f.x + f.w / 2) * G" :y="(f.y + f.h - 0.15) * G" text-anchor="middle" class="face-label">{{ f.label }}</text>
|
||||||
</g>
|
</g>
|
||||||
<template v-for="g in portBars" :key="`bar-${g.key}`">
|
<text v-for="p in shape.inputs" :key="p.key" :x="5" :y="p.dy * G + 3.5" class="pin-label">{{ p.label }}</text>
|
||||||
<path :d="g.bar" class="port-bar" :style="{ stroke: connColor(g.conn) }" />
|
<text v-for="p in shape.outputs" :key="p.key" :x="b.w * G - 5" :y="p.dy * G + 3.5" text-anchor="end" class="pin-label">{{ p.label }}</text>
|
||||||
<path :d="g.bounds" class="port-bounds" :style="{ stroke: connColor(g.conn) }" />
|
|
||||||
</template>
|
|
||||||
<text v-for="p in boxLabels" :key="p.key" :x="p.x" :y="p.y" :text-anchor="p.anchor" class="pin-label">{{ p.label }}</text>
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<!-- Switch (input pin) -->
|
<!-- Switch (input pin) -->
|
||||||
|
|
@ -514,109 +325,9 @@ const title = computed(() => {
|
||||||
<path :d="`M${b.w * G} 0H${(b.w + 0.5) * G}`" class="stub" />
|
<path :d="`M${b.w * G} 0H${(b.w + 0.5) * G}`" class="stub" />
|
||||||
</template>
|
</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>
|
|
||||||
|
|
||||||
<!-- Logic analyzer: a lane per channel, its value now and its wave -->
|
|
||||||
<template v-else-if="node.kind === 'scope'">
|
|
||||||
<rect x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="4" class="body scope-body" />
|
|
||||||
<text :x="0.4 * G" :y="0.1 * G" class="bench-title">{{ node.label?.trim() || 'Logic analyzer' }}</text>
|
|
||||||
<text v-if="!sl.lanes.length" :x="0.4 * G" :y="1.3 * G" class="bench-line">Drop on a component</text>
|
|
||||||
<g v-for="(m, k) in scopeView.marks" :key="`m${k}`">
|
|
||||||
<line :x1="m" :x2="m" :y1="0.5 * G" :y2="(b.y + b.h) * G - 2" class="scope-mark" />
|
|
||||||
</g>
|
|
||||||
<g v-for="l in scopeView.lanes" :key="l.id">
|
|
||||||
<rect :x="sl.waveX * G" :y="(l.row - 0.5) * G + 1" :width="SCOPE_SAMPLES * SCOPE_CELL" :height="l.bits * G - 2" rx="2" class="scope-lane" />
|
|
||||||
<text :x="sl.valueX * G + 2" :y="(l.row - 0.5 + l.bits / 2) * G + 3.5" class="scope-value">{{ l.value }}</text>
|
|
||||||
<path v-if="l.bits === 1" :d="l.wave" class="scope-wave" />
|
|
||||||
<template v-else>
|
|
||||||
<path v-for="(r, k) in l.runs" :key="k" :d="r.d" class="scope-bus" />
|
|
||||||
<text v-for="(r, k) in l.runs.filter(x => x.label)" :key="`t${k}`" :x="r.mid" :y="(l.row - 0.5 + l.bits / 2) * G + 3.5" text-anchor="middle" class="scope-bus-text">{{ r.label }}</text>
|
|
||||||
</template>
|
|
||||||
</g>
|
|
||||||
<text v-for="p in shape.inputs" :key="p.key" :x="4" :y="p.dy * G + 3" class="pin-label tiny">{{ p.label }}</text>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<!-- Test bench: its table on the box, run button in the title bar -->
|
|
||||||
<template v-else-if="node.kind === 'bench'">
|
|
||||||
<rect x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="4" class="body bench-body" :class="bench.state" />
|
|
||||||
<text :x="bl.x * G + 2" :y="0.45 * G" class="bench-title">{{ node.label?.trim() || 'Test bench' }}</text>
|
|
||||||
<text :x="bl.x * G + 2 + benchTitleW" :y="0.45 * G" class="bench-line" :class="bench.state">{{ bench.line }}</text>
|
|
||||||
<g v-if="bench.cols" data-bench-run class="bench-run" :transform="`translate(${(bench.right - 0.75) * G} ${0.2 * G})`">
|
|
||||||
<title>Run the tests</title>
|
|
||||||
<circle r="7" />
|
|
||||||
<path d="M-2.2 -3.6 L3.8 0 L-2.2 3.6 Z" />
|
|
||||||
</g>
|
|
||||||
<template v-if="bench.cols">
|
|
||||||
<text v-for="c in bl.cols" :key="c.key" :x="(c.x + 0.25) * G" :y="(bl.top + 0.72) * G" class="bench-head" :class="{ drive: c.drive }">{{ c.head }}</text>
|
|
||||||
<g v-for="r in bench.rows" :key="r.i" :data-bench-row="r.i" class="bench-row" :class="[r.state, { live: r.live }]">
|
|
||||||
<title>{{ r.title }}</title>
|
|
||||||
<rect :x="bl.x * G" :y="(bl.top + 1 + r.i) * G + 0.5" :width="bl.tableW * G" :height="G - 1" rx="2" class="bench-row-bg" />
|
|
||||||
<text v-for="c in r.cells" :key="c.key" :x="(c.x + 0.25) * G" :y="(bl.top + 1.72 + r.i) * G" class="bench-cell-text" :class="c.cls">{{ c.text }}</text>
|
|
||||||
</g>
|
|
||||||
<text v-if="bl.more" :x="bl.x * G + 4" :y="(bl.top + 1.72 + bl.shown) * G" class="bench-line">+ {{ bl.more }} more rows (double-click)</text>
|
|
||||||
</template>
|
|
||||||
<text v-else :x="bl.x * G + 2" :y="(bl.top + 0.8) * G" class="bench-line">Drop on a component, or double-click to set up</text>
|
|
||||||
<text v-for="p in shape.inputs" :key="p.key" :x="4" :y="p.dy * G + 3" class="pin-label tiny">{{ p.label }}</text>
|
|
||||||
<text v-for="p in shape.outputs" :key="p.key" :x="b.w * G - 4" :y="p.dy * G + 3" text-anchor="end" class="pin-label tiny">{{ p.label }}</text>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<!-- Terminal and monitors: screens the circuit writes to, sized by hand -->
|
|
||||||
<template v-else-if="display">
|
|
||||||
<rect x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="3" class="body display" />
|
|
||||||
<rect :x="dl.sx * G - 1" :y="dl.sy * G - 1" :width="dl.sw * G + 2" :height="dl.sh * G + 2" rx="2" class="term-screen" />
|
|
||||||
<template v-if="node.kind === 'terminal'">
|
|
||||||
<text v-for="(line, i) in termLines" :key="i" :x="(dl.sx + 0.15) * G" :y="i * G + 4" class="term-text">{{ line }}</text>
|
|
||||||
<rect :x="(dl.sx + 0.15) * G + termCursor.x * TERM_PX" :y="termCursor.y * G - 5" :width="TERM_PX" height="10" class="term-cursor" />
|
|
||||||
</template>
|
|
||||||
<image v-else-if="frameUrl" :href="frameUrl" :x="dl.sx * G" :y="dl.sy * G" :width="dl.sw * G" :height="dl.sh * G" preserveAspectRatio="none" class="frame" />
|
|
||||||
<text v-for="p in shape.inputs" :key="p.key" :x="4" :y="p.dy * G + 3" class="pin-label tiny">{{ p.label }}</text>
|
|
||||||
<text v-if="node.label" :x="(b.w * G) / 2" :y="(b.y + b.h) * G + 12" text-anchor="middle" class="face-label">{{ node.label }}</text>
|
|
||||||
<template v-if="selected && !ghost">
|
|
||||||
<text :x="(dl.sx + dl.sw) * G" :y="(dl.sy + dl.sh) * G + 11" text-anchor="end" class="size-badge">{{ sizeText }}</text>
|
|
||||||
<rect data-resize :x="(dl.sx + dl.sw) * G - 5" :y="(dl.sy + dl.sh) * G - 5" width="10" height="10" rx="2" class="resize-grip"><title>Drag to resize</title></rect>
|
|
||||||
</template>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<!-- Keyboard: the keys you type, one at a time -->
|
|
||||||
<template v-else-if="node.kind === 'keyboard'">
|
|
||||||
<rect x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="3" class="body kb-body" :class="{ typing: kbTyping }" />
|
|
||||||
<g :transform="`translate(${1.85 * G} ${0.4 * G})`" class="kb-keys">
|
|
||||||
<rect v-for="k in 9" :key="k" :x="((k - 1) % 3) * 0.75 * G" :y="Math.floor((k - 1) / 3) * 0.75 * G" :width="0.6 * G" :height="0.6 * G" rx="1.5" />
|
|
||||||
</g>
|
|
||||||
<text :x="2.9 * G" :y="3.4 * G" text-anchor="middle" class="kb-state">{{ kbTyping ? 'typing' : 'click, type' }}</text>
|
|
||||||
<text :x="2.9 * G" :y="4.6 * G" text-anchor="middle" class="kb-queue">{{ kbQueue }}</text>
|
|
||||||
<text :x="2.9 * G" :y="5.6 * G" text-anchor="middle" class="pin-label tiny">{{ kbCount }}</text>
|
|
||||||
<text v-for="p in shape.outputs" :key="p.key" :x="b.w * G - 4" :y="p.dy * G + 3" text-anchor="end" class="pin-label tiny">{{ p.label }}</text>
|
|
||||||
<text v-for="p in shape.inputs" :key="p.key" :x="4" :y="p.dy * G + 3" class="pin-label tiny">{{ p.label }}</text>
|
|
||||||
<text v-if="node.label" :x="(b.w * G) / 2" :y="(b.y + b.h) * G + 12" text-anchor="middle" class="face-label">{{ node.label }}</text>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<!-- Pixel: one square of a screen -->
|
<!-- Pixel: one square of a screen -->
|
||||||
<template v-else-if="node.kind === 'pixel'">
|
<template v-else-if="node.kind === 'pixel'">
|
||||||
<template v-if="node.rgb">
|
<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 }]" />
|
||||||
<rect x="1" :y="b.y * G + 1" :width="G - 2" :height="b.h * G - 2" rx="1" class="pixel" :class="{ on: !!rgbNow }" :style="rgbNow ? { '--px': rgbNow } : undefined" />
|
|
||||||
<text v-for="(c, i) in 'RGB'" :key="c" :x="G / 2" :y="i * G + 3" class="pixel-rgb" :class="{ dark: !!rgbNow }">{{ c }}</text>
|
|
||||||
</template>
|
|
||||||
<rect v-else 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 }]" />
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<!-- Input panel: a switch, button or clock per row -->
|
<!-- Input panel: a switch, button or clock per row -->
|
||||||
|
|
@ -701,13 +412,11 @@ const title = computed(() => {
|
||||||
<g v-for="p in shape.inputs" :key="`i-${p.key}`">
|
<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" />
|
<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 :cx="p.dx * G" :cy="p.dy * G" r="7" class="pin-hit" :data-node="node.id" :data-pin="p.key" data-dir="in" />
|
||||||
<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-if="dot(p.key)" :cx="p.dx * G" :cy="p.dy * G" r="2.6" class="pin" :class="{ on: v(p.key) === 1 }" />
|
||||||
<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>
|
||||||
<g v-for="p in shape.outputs" :key="`o-${p.key}`">
|
<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 :cx="p.dx * G" :cy="p.dy * G" r="7" class="pin-hit" :data-node="node.id" :data-pin="p.key" data-dir="out" />
|
||||||
<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-if="dot(p.key)" :cx="p.dx * G" :cy="p.dy * G" r="2.6" class="pin" :class="{ on: v(p.key) === 1 }" />
|
||||||
<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>
|
||||||
</template>
|
</template>
|
||||||
</g>
|
</g>
|
||||||
|
|
|
||||||
|
|
@ -1,88 +0,0 @@
|
||||||
<script setup lang="ts">
|
|
||||||
// The in-game menu, like pausing a game: resume, save, load, settings, back
|
|
||||||
// to the title screen. Esc opens it from the editor and closes it again.
|
|
||||||
const ed = useEditor()
|
|
||||||
const nav = ref<HTMLElement>()
|
|
||||||
const saving = ref(false)
|
|
||||||
|
|
||||||
const resume = () => (ed.paused.value = null)
|
|
||||||
|
|
||||||
async function save() {
|
|
||||||
saving.value = true
|
|
||||||
try {
|
|
||||||
await ed.saveNow()
|
|
||||||
} finally {
|
|
||||||
saving.value = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function saveCopy() {
|
|
||||||
ed.duplicateProject(ed.meta.value.id)
|
|
||||||
resume()
|
|
||||||
}
|
|
||||||
|
|
||||||
const where = computed(() =>
|
|
||||||
ed.account.value
|
|
||||||
? ed.cloudState.value === 'synced'
|
|
||||||
? 'Saved in your account'
|
|
||||||
: ed.cloudState.value === 'syncing'
|
|
||||||
? 'Saving to your account…'
|
|
||||||
: 'Saved in this browser; the account follows when it can be reached'
|
|
||||||
: 'Saved in this browser as you work',
|
|
||||||
)
|
|
||||||
|
|
||||||
function onKey(e: KeyboardEvent) {
|
|
||||||
if (ed.dialog.value || ed.showHelp.value) return
|
|
||||||
if (e.key === 'Escape') {
|
|
||||||
e.preventDefault()
|
|
||||||
e.stopPropagation()
|
|
||||||
if (ed.paused.value === 'load') ed.paused.value = 'main'
|
|
||||||
else resume()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if ((e.target as HTMLElement).closest('input, textarea, select')) return
|
|
||||||
if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return
|
|
||||||
const list = [...(nav.value?.querySelectorAll<HTMLButtonElement>('button') ?? [])]
|
|
||||||
const at = list.indexOf(document.activeElement as HTMLButtonElement)
|
|
||||||
const next = at < 0 ? 0 : (at + (e.key === 'ArrowDown' ? 1 : -1) + list.length) % list.length
|
|
||||||
list[next]?.focus()
|
|
||||||
e.preventDefault()
|
|
||||||
}
|
|
||||||
|
|
||||||
onMounted(() => {
|
|
||||||
window.addEventListener('keydown', onKey, true)
|
|
||||||
nextTick(() => nav.value?.querySelector('button')?.focus())
|
|
||||||
})
|
|
||||||
onBeforeUnmount(() => window.removeEventListener('keydown', onKey, true))
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div class="pause-backdrop" @click.self="resume">
|
|
||||||
<div class="pause" :class="{ wide: ed.paused.value === 'load' }" role="dialog" aria-label="Paused">
|
|
||||||
<template v-if="ed.paused.value === 'main'">
|
|
||||||
<p class="pause-kicker">Paused</p>
|
|
||||||
<h2>{{ ed.project.value.name }}</h2>
|
|
||||||
<p class="pause-where">
|
|
||||||
<Icon :name="ed.account.value ? 'lucide:cloud-check' : 'lucide:laptop'" class="size-3.5" />
|
|
||||||
{{ where }}
|
|
||||||
</p>
|
|
||||||
<nav ref="nav" class="pause-nav">
|
|
||||||
<button class="pause-item primary" @click="resume"><Icon name="lucide:play" class="size-4" /> Resume <kbd>Esc</kbd></button>
|
|
||||||
<button class="pause-item" :disabled="saving" @click="save"><Icon name="lucide:save" class="size-4" /> {{ saving ? 'Saving…' : 'Save' }}</button>
|
|
||||||
<button class="pause-item" title="Keep going in a copy; this one stays as it is" @click="saveCopy"><Icon name="lucide:copy" class="size-4" /> Save as copy</button>
|
|
||||||
<button class="pause-item" @click="ed.paused.value = 'load'"><Icon name="lucide:folder-open" class="size-4" /> Load</button>
|
|
||||||
<button class="pause-item" @click="ed.dialog.value = 'settings'"><Icon name="lucide:settings" class="size-4" /> Settings</button>
|
|
||||||
<button class="pause-item" @click="ed.showHelp.value = true"><Icon name="lucide:circle-help" class="size-4" /> How to play</button>
|
|
||||||
<button class="pause-item" @click="ed.showMenu()"><Icon name="lucide:house" class="size-4" /> Main menu</button>
|
|
||||||
</nav>
|
|
||||||
</template>
|
|
||||||
<template v-else>
|
|
||||||
<header class="pause-head">
|
|
||||||
<button class="tb-btn" title="Back (Esc)" @click="ed.paused.value = 'main'"><Icon name="lucide:arrow-left" class="size-4" /></button>
|
|
||||||
<h2>Load</h2>
|
|
||||||
</header>
|
|
||||||
<EditorProjectList @done="resume" />
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
@ -55,7 +55,7 @@ function onFile(e: Event) {
|
||||||
<a v-else href="#" @click.prevent="ed.dialog.value = 'account'">Sign in to have them on every computer.</a>
|
<a v-else href="#" @click.prevent="ed.dialog.value = 'account'">Sign in to have them on every computer.</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p v-if="!list.length" class="hint mt-3">Nothing saved yet. What you build is saved as soon as you change something; or start something new below.</p>
|
<p v-if="!list.length" class="hint mt-3">No projects yet. Start one below.</p>
|
||||||
<ul class="project-list">
|
<ul class="project-list">
|
||||||
<li v-for="m in list" :key="m.id" :class="{ current: m.id === ed.meta.value.id }">
|
<li v-for="m in list" :key="m.id" :class="{ current: m.id === ed.meta.value.id }">
|
||||||
<input
|
<input
|
||||||
|
|
@ -70,7 +70,6 @@ function onFile(e: Event) {
|
||||||
<span class="name">
|
<span class="name">
|
||||||
{{ m.name }}
|
{{ m.name }}
|
||||||
<span v-if="m.id === ed.meta.value.id" class="badge">open</span>
|
<span v-if="m.id === ed.meta.value.id" class="badge">open</span>
|
||||||
<span v-if="!freeOnly && ed.projectMode(m)" class="badge mode">{{ ed.projectMode(m) === 'campaign' ? 'Campaign' : 'Challenges' }}</span>
|
|
||||||
</span>
|
</span>
|
||||||
<span class="meta">
|
<span class="meta">
|
||||||
{{ when(m.updated) }}
|
{{ when(m.updated) }}
|
||||||
|
|
@ -118,7 +117,7 @@ function onFile(e: Event) {
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<div class="mt-4 flex flex-wrap gap-2">
|
<div class="mt-4 flex flex-wrap gap-2">
|
||||||
<button v-if="!freeOnly" class="btn btn-primary" title="Start with NAND only and earn every other part by solving challenges" @click="ed.newProject(false, true); close()">
|
<button v-if="!freeOnly" class="btn btn-primary" title="Start with NAND only and earn every other part by solving challenges" @click="ed.startCampaign(); close()">
|
||||||
<Icon name="lucide:trophy" class="size-4" /> New campaign
|
<Icon name="lucide:trophy" class="size-4" /> New campaign
|
||||||
</button>
|
</button>
|
||||||
<button class="btn" @click="ed.newProject(false); close()"><Icon name="lucide:file" class="size-4" /> New (NAND only)</button>
|
<button class="btn" @click="ed.newProject(false); close()"><Icon name="lucide:file" class="size-4" /> New (NAND only)</button>
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,16 @@
|
||||||
|
<script setup lang="ts">
|
||||||
|
const ed = useEditor()
|
||||||
|
const close = () => (ed.dialog.value = null)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="modal-backdrop" @click.self="close">
|
||||||
|
<div class="modal" role="dialog" aria-labelledby="projects-title">
|
||||||
|
<div class="flex items-start justify-between gap-4">
|
||||||
|
<h2 id="projects-title">Projects</h2>
|
||||||
|
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
|
||||||
|
</div>
|
||||||
|
<EditorProjectList @done="close" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
@ -1,157 +1,24 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
// The search box at the mouse (Space, /, Shift+A or Ctrl+K): parts to place
|
// Adding a part from the keyboard (Shift+A or Ctrl+K): a search box at the
|
||||||
// right there, and things to do. Empty, it shows the parts used lately and
|
// mouse; type a few letters, arrows to choose, Enter puts it right there.
|
||||||
// the common actions; typing narrows both and offers to open the circuits
|
import type { NodeKind } from '~/lib/logic/types'
|
||||||
// of that name. Arrows choose, Enter takes it, Shift+Enter opens a component.
|
|
||||||
import { matchScore } from '~/lib/match'
|
|
||||||
import { circuitsNamed, wayTo } from '~/lib/nav'
|
|
||||||
import type { ComponentDef, NodeKind } from '~/lib/logic/types'
|
|
||||||
|
|
||||||
const props = defineProps<{ x: number; y: number }>()
|
const props = defineProps<{ x: number; y: number }>()
|
||||||
const emit = defineEmits<{ pick: [p: { kind: NodeKind; chip?: string }]; fit: []; close: [] }>()
|
const emit = defineEmits<{ pick: [p: { kind: NodeKind; chip?: string }]; close: [] }>()
|
||||||
|
|
||||||
const ed = useEditor()
|
const { search } = useParts()
|
||||||
const { search, recentParts } = useParts()
|
|
||||||
const query = ref('')
|
const query = ref('')
|
||||||
const at = ref(0)
|
const at = ref(0)
|
||||||
const input = ref<HTMLInputElement>()
|
const input = ref<HTMLInputElement>()
|
||||||
const el = ref<HTMLElement>()
|
const el = ref<HTMLElement>()
|
||||||
const list = ref<HTMLElement>()
|
const hits = computed(() => search(query.value, 10))
|
||||||
|
|
||||||
interface Action {
|
|
||||||
id: string
|
|
||||||
label: string
|
|
||||||
icon: string
|
|
||||||
keys?: string
|
|
||||||
/** Other words it is found by. */
|
|
||||||
aka?: string
|
|
||||||
/** Only offered when this holds. */
|
|
||||||
when?: () => boolean
|
|
||||||
run: () => void
|
|
||||||
}
|
|
||||||
|
|
||||||
const ACTIONS: Action[] = [
|
|
||||||
{ id: 'new-comp', label: 'Create a new component', icon: 'lucide:square-plus', aka: 'new part chip block', run: () => ed.createComponent() },
|
|
||||||
{
|
|
||||||
id: 'package',
|
|
||||||
label: 'Make a component from the selection',
|
|
||||||
icon: 'lucide:package',
|
|
||||||
aka: 'group package extract',
|
|
||||||
when: () => ed.selection.value.length > 1,
|
|
||||||
run: () => ed.packageSelected('Part'),
|
|
||||||
},
|
|
||||||
{ id: 'find', label: 'Find anything in the project', icon: 'lucide:search', keys: 'Ctrl+F', aka: 'search where used', run: () => (ed.dialog.value = 'search') },
|
|
||||||
{ id: 'convert', label: 'Converter: text, hex, binary, decimal', icon: 'lucide:arrow-left-right', aka: 'ascii utf8 unicode base64 octal encode decode', run: () => (ed.dialog.value = 'convert') },
|
|
||||||
{ id: 'asm', label: 'Assembler: program to memory words', icon: 'lucide:file-code-2', aka: 'assembly opcode instruction rom program cpu machine code', run: () => (ed.dialog.value = 'asm') },
|
|
||||||
{ id: 'table', label: 'Truth table', icon: 'lucide:table', aka: 'test outputs', run: () => (ed.dialog.value = 'table') },
|
|
||||||
{ id: 'fit', label: 'Fit the circuit to the screen', icon: 'lucide:scan', keys: 'F', aka: 'zoom view', run: () => emit('fit') },
|
|
||||||
{ id: 'tidy', label: 'Tidy this circuit', icon: 'lucide:wand-sparkles', aka: 'wires clean route layout', when: () => ed.def.value.wires.length > 0, run: () => ed.tidyAll() },
|
|
||||||
{ id: 'tidy-all', label: 'Tidy every circuit', icon: 'lucide:sparkles', aka: 'wires clean route layout all components', run: () => ed.tidyEverything() },
|
|
||||||
{ id: 'examples', label: 'Add example parts', icon: 'lucide:book-open', aka: 'library not and or adder counter', run: () => ed.loadExamples() },
|
|
||||||
{ id: 'library', label: 'Library: components everyone published', icon: 'lucide:library-big', aka: 'public shared community download import browse', run: () => (ed.dialog.value = 'library') },
|
|
||||||
{
|
|
||||||
id: 'lib-publish',
|
|
||||||
label: 'Publish to the library',
|
|
||||||
icon: 'lucide:book-up',
|
|
||||||
aka: 'share upload public community',
|
|
||||||
when: () => !ed.libraryProblem.value && !ed.ownEntry(ed.def.value),
|
|
||||||
run: () => (ed.dialog.value = 'library-publish'),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: 'lib-update',
|
|
||||||
label: 'Update in the library',
|
|
||||||
icon: 'lucide:book-up',
|
|
||||||
aka: 'publish share upload new version public',
|
|
||||||
when: () => !ed.libraryProblem.value && !!ed.ownEntry(ed.def.value),
|
|
||||||
run: () => (ed.dialog.value = 'library-publish'),
|
|
||||||
},
|
|
||||||
{ id: 'connector', label: 'New connector type', icon: 'lucide:plug', aka: 'cable hdmi rj45 bus port', when: () => ed.canPlaceKind('portin'), run: () => ed.addConnector() },
|
|
||||||
{ id: 'power', label: 'Power off and on', icon: 'lucide:power', aka: 'reset state memory bits clear zero restart', when: () => ed.circuitStats.value.sequential, run: () => ed.resetState() },
|
|
||||||
{ id: 'undo', label: 'Undo', icon: 'lucide:undo-2', keys: 'Ctrl+Z', when: () => ed.canUndo.value, run: () => ed.undo() },
|
|
||||||
{ id: 'print', label: 'Print or save as PDF', icon: 'lucide:printer', keys: 'Ctrl+P', aka: 'sheet export', run: () => ed.exportSheet('print') },
|
|
||||||
{ id: 'settings', label: 'Settings', icon: 'lucide:settings', aka: 'symbols sound wires options', run: () => (ed.dialog.value = 'settings') },
|
|
||||||
{ id: 'help', label: 'How to play', icon: 'lucide:circle-help', keys: '?', aka: 'help shortcuts keys', run: () => (ed.showHelp.value = true) },
|
|
||||||
{ id: 'menu', label: 'Menu: save, load, main menu', icon: 'lucide:menu', keys: 'Esc', aka: 'pause quit', run: () => ed.pause() },
|
|
||||||
]
|
|
||||||
|
|
||||||
type Item =
|
|
||||||
| { type: 'part'; id: string; kind: NodeKind; chip?: string; label: string; icon: string; note?: string }
|
|
||||||
| { type: 'action'; id: string; act: Action; label: string; icon: string; note?: string }
|
|
||||||
| { type: 'open'; id: string; def: string; label: string; icon: string; note?: string; here?: boolean }
|
|
||||||
|
|
||||||
const partItem = (p: { kind: NodeKind; chip?: string; name: string; icon: string }, note?: string): Item => ({
|
|
||||||
type: 'part',
|
|
||||||
id: `p:${p.chip ?? p.kind}`,
|
|
||||||
kind: p.kind,
|
|
||||||
chip: p.chip,
|
|
||||||
label: p.name,
|
|
||||||
icon: p.icon,
|
|
||||||
note,
|
|
||||||
})
|
|
||||||
const actItem = (a: Action): Item => ({ type: 'action', id: `a:${a.id}`, act: a, label: a.label, icon: a.icon, note: a.keys })
|
|
||||||
// Any circuit can be opened, placeable here or not; the one you are in is only shown.
|
|
||||||
const openItem = (d: ComponentDef): Item =>
|
|
||||||
d.id === ed.def.value.id
|
|
||||||
? { type: 'open', id: `o:${d.id}`, def: d.id, label: d.name, icon: 'lucide:map-pin', note: 'you are here', here: true }
|
|
||||||
: { type: 'open', id: `o:${d.id}`, def: d.id, label: `Open ${d.name}`, icon: 'lucide:log-in' }
|
|
||||||
const offered = () => ACTIONS.filter(a => !a.when || a.when())
|
|
||||||
|
|
||||||
/** Sections to show: parts first, then circuits to open, then actions. */
|
|
||||||
const sections = computed(() => {
|
|
||||||
const q = query.value.trim()
|
|
||||||
if (!q) {
|
|
||||||
const recent = recentParts.value.map(r => partItem(r, 'recent'))
|
|
||||||
const parts = recent.length ? recent : search('', 6).map(h => partItem(h, h.group))
|
|
||||||
return [
|
|
||||||
{ title: recent.length ? 'Recent parts' : 'Parts', items: parts },
|
|
||||||
{ title: 'Actions', items: offered().slice(0, 7).map(actItem) },
|
|
||||||
]
|
|
||||||
}
|
|
||||||
const parts = search(q, 8).map(h => partItem(h, h.group))
|
|
||||||
const acts = offered()
|
|
||||||
.map(a => ({ a, s: Math.max(matchScore(a.label, q.toLowerCase()), matchScore(a.aka ?? '', q.toLowerCase()) * 0.8) }))
|
|
||||||
.filter(x => x.s > 0)
|
|
||||||
.sort((x, y) => y.s - x.s)
|
|
||||||
.slice(0, 5)
|
|
||||||
.map(x => actItem(x.a))
|
|
||||||
const circuits = circuitsNamed(ed.project.value.components, q).map(openItem)
|
|
||||||
return [
|
|
||||||
{ title: 'Parts', items: parts },
|
|
||||||
{ title: 'Circuits', items: circuits },
|
|
||||||
{ title: 'Actions', items: acts },
|
|
||||||
].filter(s => s.items.length)
|
|
||||||
})
|
|
||||||
/** What the arrows walk through: everything but the circuit you are in. */
|
|
||||||
const flat = computed(() => sections.value.flatMap(s => s.items).filter(it => !(it.type === 'open' && it.here)))
|
|
||||||
const indexOf = (it: Item) => flat.value.indexOf(it)
|
|
||||||
watch(query, () => (at.value = 0))
|
watch(query, () => (at.value = 0))
|
||||||
|
|
||||||
/** Takes what was chosen; `edit` opens a component instead of placing it. */
|
|
||||||
function take(it: Item | undefined, edit = false) {
|
|
||||||
if (!it || (it.type === 'open' && it.here)) return
|
|
||||||
if (it.type === 'open') return go(it.def)
|
|
||||||
if (it.type === 'part' && it.chip && edit) return go(it.chip)
|
|
||||||
if (it.type === 'part') return emit('pick', { kind: it.kind, chip: it.chip })
|
|
||||||
emit('close')
|
|
||||||
it.act.run()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Into a circuit: back along the way when it is on it, else one step further in. */
|
|
||||||
function go(id: string) {
|
|
||||||
emit('close')
|
|
||||||
const way = wayTo(ed.nav.value, ed.mainId.value, id)
|
|
||||||
if (way === 'main') ed.goMain()
|
|
||||||
else if (way === 'open') ed.open(id)
|
|
||||||
else ed.goTo(way)
|
|
||||||
}
|
|
||||||
|
|
||||||
const pos = ref({ left: props.x, top: props.y })
|
const pos = ref({ left: props.x, top: props.y })
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
input.value?.focus()
|
input.value?.focus()
|
||||||
const r = el.value!.getBoundingClientRect()
|
const r = el.value!.getBoundingClientRect()
|
||||||
// Room below for the list at its longest, so typing never pushes the box off the window.
|
pos.value = { left: Math.max(8, Math.min(props.x, window.innerWidth - r.width - 8)), top: Math.max(8, Math.min(props.y, window.innerHeight - 380)) }
|
||||||
const tall = r.height - list.value!.offsetHeight + Math.min(420, window.innerHeight * 0.6)
|
|
||||||
pos.value = { left: Math.max(8, Math.min(props.x, window.innerWidth - r.width - 8)), top: Math.max(8, Math.min(props.y, window.innerHeight - tall - 8)) }
|
|
||||||
window.addEventListener('pointerdown', outside, true)
|
window.addEventListener('pointerdown', outside, true)
|
||||||
})
|
})
|
||||||
onBeforeUnmount(() => window.removeEventListener('pointerdown', outside, true))
|
onBeforeUnmount(() => window.removeEventListener('pointerdown', outside, true))
|
||||||
|
|
@ -162,14 +29,14 @@ function outside(e: Event) {
|
||||||
|
|
||||||
function onKey(e: KeyboardEvent) {
|
function onKey(e: KeyboardEvent) {
|
||||||
e.stopPropagation()
|
e.stopPropagation()
|
||||||
const n = flat.value.length
|
const n = hits.value.length
|
||||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
if (n) at.value = (at.value + (e.key === 'ArrowDown' ? 1 : -1) + n) % n
|
if (n) at.value = (at.value + (e.key === 'ArrowDown' ? 1 : -1) + n) % n
|
||||||
nextTick(() => el.value?.querySelector('.item.active')?.scrollIntoView({ block: 'nearest' }))
|
|
||||||
} else if (e.key === 'Enter') {
|
} else if (e.key === 'Enter') {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
take(flat.value[at.value], e.shiftKey || e.ctrlKey || e.metaKey)
|
const h = hits.value[at.value]
|
||||||
|
if (h) emit('pick', { kind: h.kind, chip: h.chip })
|
||||||
} else if (e.key === 'Escape') {
|
} else if (e.key === 'Escape') {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
emit('close')
|
emit('close')
|
||||||
|
|
@ -181,36 +48,20 @@ function onKey(e: KeyboardEvent) {
|
||||||
<Teleport to="body">
|
<Teleport to="body">
|
||||||
<div ref="el" class="quick-add" :style="{ left: `${pos.left}px`, top: `${pos.top}px` }" @keydown="onKey">
|
<div ref="el" class="quick-add" :style="{ left: `${pos.left}px`, top: `${pos.top}px` }" @keydown="onKey">
|
||||||
<div class="search part-search">
|
<div class="search part-search">
|
||||||
<Icon name="lucide:search" class="size-3.5 text-(--muted)" />
|
<Icon name="lucide:plus" class="size-3.5 text-(--muted)" />
|
||||||
<input ref="input" v-model="query" placeholder="Find a part, a circuit or an action…" />
|
<input ref="input" v-model="query" placeholder="Add a part here…" />
|
||||||
</div>
|
</div>
|
||||||
<div ref="list" class="quick-list">
|
|
||||||
<template v-for="s in sections" :key="s.title">
|
|
||||||
<p class="quick-head">{{ s.title }}</p>
|
|
||||||
<ul class="items">
|
<ul class="items">
|
||||||
<li v-for="it in s.items" :key="it.id" class="comp-row">
|
<li v-for="(h, i) in hits" :key="h.chip ?? h.kind">
|
||||||
<button
|
<button class="item" :class="{ active: i === at }" @pointerenter="at = i" @click="emit('pick', { kind: h.kind, chip: h.chip })">
|
||||||
class="item"
|
<span v-if="h.kind === 'nand'" class="nand-badge">&</span>
|
||||||
:class="{ active: indexOf(it) === at }"
|
<Icon v-else :name="h.icon" class="size-4 shrink-0 text-(--muted)" />
|
||||||
:disabled="it.type === 'open' && it.here"
|
<span class="grow truncate">{{ h.name }}</span>
|
||||||
@pointerenter="indexOf(it) >= 0 && (at = indexOf(it))"
|
<span class="group-tag">{{ h.group }}</span>
|
||||||
@click="take(it)"
|
|
||||||
>
|
|
||||||
<span v-if="it.type === 'part' && it.kind === 'nand'" class="nand-badge">&</span>
|
|
||||||
<Icon v-else :name="it.icon" class="size-4 shrink-0" :class="it.type === 'part' ? 'text-(--muted)' : 'text-(--accent)'" />
|
|
||||||
<span class="grow truncate">{{ it.label }}</span>
|
|
||||||
<kbd v-if="it.type === 'action' && it.note">{{ it.note }}</kbd>
|
|
||||||
<span v-else-if="it.note" class="group-tag">{{ it.note }}</span>
|
|
||||||
</button>
|
|
||||||
<button v-if="it.type === 'part' && it.chip" class="open" title="Open it and edit inside (Shift+Enter)" @click="take(it, true)">
|
|
||||||
<Icon name="lucide:pencil" class="size-3.5" />
|
|
||||||
</button>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</template>
|
<p v-if="!hits.length" class="hint px-3 pb-2">Nothing called "{{ query.trim() }}" fits here.</p>
|
||||||
<p v-if="!sections.length" class="hint px-3 pb-2">Nothing called "{{ query.trim() }}" here.</p>
|
|
||||||
</div>
|
|
||||||
<p class="quick-foot"><kbd>Enter</kbd> takes it, <kbd>Shift+Enter</kbd> opens a component to edit it.</p>
|
|
||||||
</div>
|
</div>
|
||||||
</Teleport>
|
</Teleport>
|
||||||
</template>
|
</template>
|
||||||
|
|
|
||||||
|
|
@ -1,25 +0,0 @@
|
||||||
<script setup lang="ts">
|
|
||||||
// The panel on the left, hidden, shrinks to this strip; its buttons bring it back.
|
|
||||||
const ed = useEditor()
|
|
||||||
|
|
||||||
const TABS = [
|
|
||||||
{ id: 'circuit', label: 'This', icon: 'lucide:cpu' },
|
|
||||||
{ id: 'pins', label: 'Pins', icon: 'lucide:list' },
|
|
||||||
] as const
|
|
||||||
|
|
||||||
function openTab(id: (typeof TABS)[number]['id']) {
|
|
||||||
ed.panelTab.value = id
|
|
||||||
ed.togglePanel(true)
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<aside class="rail">
|
|
||||||
<button class="rail-btn" title="Show the panel ([)" @click="ed.togglePanel(true)">
|
|
||||||
<Icon name="lucide:panel-left-open" class="size-4" />
|
|
||||||
</button>
|
|
||||||
<button v-for="t in TABS" :key="t.id" class="rail-btn" :title="t.label" @click="openTab(t.id)">
|
|
||||||
<Icon :name="t.icon" class="size-4" />
|
|
||||||
</button>
|
|
||||||
</aside>
|
|
||||||
</template>
|
|
||||||
|
|
@ -1,24 +0,0 @@
|
||||||
<script setup lang="ts">
|
|
||||||
// The panel on the right: only there while something is selected, with its
|
|
||||||
// settings and what can be done with it (swap, wire up, make a component).
|
|
||||||
const ed = useEditor()
|
|
||||||
|
|
||||||
const single = computed(() =>
|
|
||||||
ed.selection.value.length === 1 && !ed.wireSel.value.length ? ed.def.value.nodes.find(n => n.id === ed.selection.value[0]) : undefined,
|
|
||||||
)
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<aside class="inspector selection-panel">
|
|
||||||
<div class="sel-panel-head">
|
|
||||||
<Icon name="lucide:mouse-pointer-2" class="size-4 shrink-0 text-(--accent)" />
|
|
||||||
<span class="grow">Selection</span>
|
|
||||||
<button class="icon-btn" title="Deselect (Esc)" @click="ed.selection.value = [], (ed.wireSel.value = [])"><Icon name="lucide:x" class="size-4" /></button>
|
|
||||||
</div>
|
|
||||||
<div class="scroll">
|
|
||||||
<EditorNodeSettings v-if="single" :key="single.id" :node="single" />
|
|
||||||
<EditorBulkSettings v-else-if="ed.selection.value.length" />
|
|
||||||
<EditorWireSettings v-else />
|
|
||||||
</div>
|
|
||||||
</aside>
|
|
||||||
</template>
|
|
||||||
|
|
@ -63,7 +63,7 @@ function selectAll(e: Event) {
|
||||||
<button class="btn" title="Adds the components from a project file to this project" @click="fileInput?.click()">
|
<button class="btn" title="Adds the components from a project file to this project" @click="fileInput?.click()">
|
||||||
<Icon name="lucide:upload" class="size-4" /> Add components from file
|
<Icon name="lucide:upload" class="size-4" /> Add components from file
|
||||||
</button>
|
</button>
|
||||||
<button class="btn btn-ghost" @click="ed.dialog.value = null; ed.pause('load')"><Icon name="lucide:folder-open" class="size-4" /> Open file as project</button>
|
<button class="btn btn-ghost" @click="ed.dialog.value = 'projects'"><Icon name="lucide:folder-open" class="size-4" /> Open file as project</button>
|
||||||
<input ref="fileInput" type="file" accept="application/json,.json" class="hidden" @change="onFile" />
|
<input ref="fileInput" type="file" accept="application/json,.json" class="hidden" @change="onFile" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,8 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
// The challenge or puzzle being built (part "task", at the top of This) and the
|
|
||||||
// truth table of the open circuit (part "table", folded further down).
|
|
||||||
import type { ChallengeCheck } from '~/composables/useEditor'
|
import type { ChallengeCheck } from '~/composables/useEditor'
|
||||||
import { tableMarkdown, type TruthTable } from '~/lib/logic/analyze'
|
import { tableMarkdown, type TruthTable } from '~/lib/logic/analyze'
|
||||||
import { apiId, isTable } from '~/lib/logic/puzzles'
|
import { apiId, isTable } from '~/lib/logic/puzzles'
|
||||||
|
|
||||||
const props = defineProps<{ part: 'task' | 'table' }>()
|
|
||||||
const ed = useEditor()
|
const ed = useEditor()
|
||||||
const def = ed.def
|
const def = ed.def
|
||||||
|
|
||||||
|
|
@ -34,7 +31,7 @@ const showTarget = ref(true)
|
||||||
const puzzleLink = computed(() => (challenge.value?.puzzle ? `${location.origin}/puzzle/${apiId(challenge.value.puzzle.id)}` : ''))
|
const puzzleLink = computed(() => (challenge.value?.puzzle ? `${location.origin}/puzzle/${apiId(challenge.value.puzzle.id)}` : ''))
|
||||||
|
|
||||||
const table = ref<TruthTable | { error: string } | null>(null)
|
const table = ref<TruthTable | { error: string } | null>(null)
|
||||||
watch([() => ed.sim.value, () => def.value.id], () => (table.value = props.part === 'table' ? ed.table() : null), { immediate: true })
|
watch([() => ed.sim.value, () => def.value.id], () => (table.value = ed.table()), { immediate: true })
|
||||||
|
|
||||||
const check = ref<ChallengeCheck | null>(null)
|
const check = ref<ChallengeCheck | null>(null)
|
||||||
const bestHere = computed(() => (challenge.value ? ed.project.value.best?.[challenge.value.id] : undefined))
|
const bestHere = computed(() => (challenge.value ? ed.project.value.best?.[challenge.value.id] : undefined))
|
||||||
|
|
@ -46,7 +43,7 @@ function runCheck() {
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<section v-if="props.part === 'task' && challenge" class="challenge" :class="{ solved }">
|
<section v-if="challenge" class="challenge" :class="{ solved }">
|
||||||
<h3>
|
<h3>
|
||||||
<Icon :name="solved ? 'lucide:badge-check' : 'lucide:flag'" class="size-4" />
|
<Icon :name="solved ? 'lucide:badge-check' : 'lucide:flag'" class="size-4" />
|
||||||
{{ challenge.puzzle ? 'Puzzle' : 'Challenge' }}: {{ challenge.name }}
|
{{ challenge.puzzle ? 'Puzzle' : 'Challenge' }}: {{ challenge.name }}
|
||||||
|
|
@ -94,8 +91,9 @@ function runCheck() {
|
||||||
</template>
|
</template>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<div v-if="props.part === 'table'" class="table-pane">
|
<section>
|
||||||
<div class="flex items-center justify-end gap-1">
|
<div class="flex items-center gap-1">
|
||||||
|
<h3 class="grow">Truth table</h3>
|
||||||
<template v-if="table && !('error' in table)">
|
<template v-if="table && !('error' in table)">
|
||||||
<button class="icon-btn" title="Download as CSV" @click="ed.exportTable(table)"><Icon name="lucide:download" class="size-3.5" /></button>
|
<button class="icon-btn" title="Download as CSV" @click="ed.exportTable(table)"><Icon name="lucide:download" class="size-3.5" /></button>
|
||||||
<button class="icon-btn" title="Copy as a Markdown table" @click="ed.copyText(tableMarkdown(table), 'Truth table copied')">
|
<button class="icon-btn" title="Copy as a Markdown table" @click="ed.copyText(tableMarkdown(table), 'Truth table copied')">
|
||||||
|
|
@ -111,5 +109,5 @@ function runCheck() {
|
||||||
<EditorTruthTable :table="table" />
|
<EditorTruthTable :table="table" />
|
||||||
</template>
|
</template>
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,7 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
// The bar along the top, floating like the parts bar below: menu and where
|
// The top of the editor: three small floating groups over the canvas.
|
||||||
// you are on the left, the clock in the middle, the rest on the right. On a
|
// Left, where you are (menu, project, circuit); middle, the clock; right,
|
||||||
// narrow bar the names on the way fold into "…" and the buttons used least
|
// the few things used all the time, and everything else in the ⋯ menu.
|
||||||
// move into a "⋯" menu, so Main always stays in reach.
|
|
||||||
import { CHALLENGES } from '~/lib/logic/challenges'
|
|
||||||
import { foldCrumbs } from '~/lib/nav'
|
|
||||||
import type { MenuEntry } from '~/composables/useMenu'
|
import type { MenuEntry } from '~/composables/useMenu'
|
||||||
|
|
||||||
const ed = useEditor()
|
const ed = useEditor()
|
||||||
|
|
@ -21,108 +18,9 @@ const SPEEDS = [
|
||||||
|
|
||||||
const hasClock = computed(() => (ed.sim.value?.nl.clocks.length ?? 0) > 0)
|
const hasClock = computed(() => (ed.sim.value?.nl.clocks.length ?? 0) > 0)
|
||||||
const statusText = computed(() => ({ stable: 'Stable', busy: 'Settling', oscillating: 'Oscillating' })[ed.status.value])
|
const statusText = computed(() => ({ stable: 'Stable', busy: 'Settling', oscillating: 'Oscillating' })[ed.status.value])
|
||||||
// The way into the open circuit: Main, then each component entered on the way.
|
const backName = computed(() => {
|
||||||
const path = computed(() =>
|
const id = ed.nav.value.at(-1)
|
||||||
[...ed.nav.value.map((id, i) => ({ id, i })), { id: ed.def.value.id, i: -1 }]
|
return id ? ed.getDef.value(id)?.name : undefined
|
||||||
.filter(p => p.id !== ed.mainId.value)
|
|
||||||
.map(p => ({ ...p, name: ed.getDef.value(p.id)?.name ?? '?' })),
|
|
||||||
)
|
|
||||||
const atMain = computed(() => ed.def.value.id === ed.mainId.value)
|
|
||||||
|
|
||||||
// How wide the bar is decides what fits in it.
|
|
||||||
const dock = ref<HTMLElement>()
|
|
||||||
const width = ref(Infinity)
|
|
||||||
let sizer: ResizeObserver | undefined
|
|
||||||
/** Buttons moved into the "⋯" menu: none; sound, settings and help; also undo, redo and share; also challenges and search. */
|
|
||||||
const tucked = computed(() => (width.value > 640 ? 0 : width.value > 520 ? 1 : width.value > 420 ? 2 : 3))
|
|
||||||
/** The names on the way here, the last ones in the bar and those before them under "…". */
|
|
||||||
const crumbs = computed(() => foldCrumbs(path.value, width.value > 1180 ? 3 : width.value > 900 ? 2 : 1))
|
|
||||||
|
|
||||||
/** Where a menu opens: under the button that opened it. */
|
|
||||||
function below(e: MouseEvent) {
|
|
||||||
const r = (e.currentTarget as HTMLElement).getBoundingClientRect()
|
|
||||||
return { x: r.left, y: r.bottom + 6 }
|
|
||||||
}
|
|
||||||
|
|
||||||
// The circuit you are in: its name opens what can be done with all of it.
|
|
||||||
const circuitMenu = ref<{ x: number; y: number } | null>(null)
|
|
||||||
function openCircuitMenu(e: MouseEvent) {
|
|
||||||
circuitMenu.value = circuitMenu.value ? null : below(e)
|
|
||||||
}
|
|
||||||
const circuitEntries = computed<MenuEntry[]>(() => {
|
|
||||||
const d = ed.def.value
|
|
||||||
const empty = !d.nodes.length
|
|
||||||
return [
|
|
||||||
{ head: 'Wires' },
|
|
||||||
{ label: 'Tidy this circuit', icon: 'lucide:wand-sparkles', disabled: !d.wires.length, run: () => ed.tidyAll() },
|
|
||||||
{ label: 'Tidy every circuit', icon: 'lucide:sparkles', run: () => ed.tidyEverything() },
|
|
||||||
'sep',
|
|
||||||
{ head: 'Memory' },
|
|
||||||
{
|
|
||||||
label: 'Power off and on',
|
|
||||||
icon: 'lucide:power',
|
|
||||||
disabled: !ed.circuitStats.value.sequential,
|
|
||||||
note: ed.circuitStats.value.sequential ? 'every bit back to 0' : 'no memory here',
|
|
||||||
run: () => ed.resetState(),
|
|
||||||
},
|
|
||||||
'sep',
|
|
||||||
{ head: 'As a part' },
|
|
||||||
{ label: 'Design its box…', icon: 'lucide:pen-tool', run: () => ed.designFace(d.id) },
|
|
||||||
{ label: 'Duplicate', icon: 'lucide:copy', run: () => ed.copyComponent(d.id) },
|
|
||||||
{
|
|
||||||
label: 'Delete this circuit',
|
|
||||||
icon: 'lucide:trash-2',
|
|
||||||
danger: true,
|
|
||||||
disabled: atMain.value,
|
|
||||||
note: atMain.value ? 'the main circuit stays' : undefined,
|
|
||||||
run: () => {
|
|
||||||
const name = d.name
|
|
||||||
ed.removeComponent(d.id)
|
|
||||||
ed.notify(`Deleted "${name}" (Ctrl+Z brings it back)`)
|
|
||||||
},
|
|
||||||
},
|
|
||||||
'sep',
|
|
||||||
{ head: 'Share' },
|
|
||||||
{ label: 'Print or save as PDF', icon: 'lucide:printer', keys: 'Ctrl+P', disabled: empty, run: () => ed.exportSheet('print') },
|
|
||||||
{ label: 'Export as SVG', icon: 'lucide:file-image', disabled: empty, run: () => ed.exportSheet('svg') },
|
|
||||||
{ label: 'Publish as a puzzle…', icon: 'lucide:puzzle', disabled: !!ed.task.value || empty, run: () => (ed.dialog.value = 'publish') },
|
|
||||||
{
|
|
||||||
label: ed.ownEntry(d) ? 'Update in the library…' : 'Publish to the library…',
|
|
||||||
icon: 'lucide:book-up',
|
|
||||||
disabled: !!ed.task.value || empty,
|
|
||||||
note: ed.task.value ? 'challenges stay private' : undefined,
|
|
||||||
run: () => (ed.dialog.value = 'library-publish'),
|
|
||||||
},
|
|
||||||
]
|
|
||||||
})
|
|
||||||
|
|
||||||
// Challenges and puzzles open below their button.
|
|
||||||
const showChallenges = ed.challengesOpen
|
|
||||||
const challengesEl = ref<HTMLElement>()
|
|
||||||
const solvedCount = computed(() => CHALLENGES.filter(c => ed.project.value.solved.includes(c.id)).length)
|
|
||||||
function outside(e: PointerEvent) {
|
|
||||||
if (showChallenges.value && !challengesEl.value?.contains(e.target as Node)) showChallenges.value = false
|
|
||||||
}
|
|
||||||
/** The drop-down is centred under its button, moved sideways as far as it takes to stay on screen. */
|
|
||||||
const popShift = ref(0)
|
|
||||||
function placePop() {
|
|
||||||
const r = challengesEl.value?.getBoundingClientRect()
|
|
||||||
if (!showChallenges.value || !r) return
|
|
||||||
const w = Math.min(340, window.innerWidth - 16)
|
|
||||||
const left = r.left + r.width / 2 - w / 2
|
|
||||||
popShift.value = Math.max(8, Math.min(left, window.innerWidth - 8 - w)) - left
|
|
||||||
}
|
|
||||||
watch(showChallenges, placePop)
|
|
||||||
onMounted(() => {
|
|
||||||
window.addEventListener('pointerdown', outside, true)
|
|
||||||
window.addEventListener('resize', placePop)
|
|
||||||
sizer = new ResizeObserver(([e]) => (width.value = e!.contentRect.width))
|
|
||||||
sizer.observe(dock.value!)
|
|
||||||
})
|
|
||||||
onBeforeUnmount(() => {
|
|
||||||
window.removeEventListener('pointerdown', outside, true)
|
|
||||||
window.removeEventListener('resize', placePop)
|
|
||||||
sizer?.disconnect()
|
|
||||||
})
|
})
|
||||||
const cloudText = computed(() => ({ off: '', syncing: 'syncing', synced: 'all saved', offline: 'offline', error: 'sync failed' })[ed.cloudState.value])
|
const cloudText = computed(() => ({ off: '', syncing: 'syncing', synced: 'all saved', offline: 'offline', error: 'sync failed' })[ed.cloudState.value])
|
||||||
const linkIcon = computed(() => {
|
const linkIcon = computed(() => {
|
||||||
|
|
@ -139,176 +37,94 @@ const linkIcon = computed(() => {
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
// Tools that work beside the circuit.
|
/** The panel on the right: open on its own while something is selected; this keeps it open. */
|
||||||
const toolsMenu = ref<{ x: number; y: number } | null>(null)
|
const panelOpen = computed(() => ed.sidebars.right)
|
||||||
const toolEntries = computed<MenuEntry[]>(() => [
|
|
||||||
{ label: 'Converter…', icon: 'lucide:arrow-left-right', note: 'text, hex, binary', run: () => (ed.dialog.value = 'convert') },
|
|
||||||
{ label: 'Assembler…', icon: 'lucide:file-code-2', note: 'program to memory', run: () => (ed.dialog.value = 'asm') },
|
|
||||||
])
|
|
||||||
|
|
||||||
// The names folded into "…": each leads back to it.
|
const more = ref<{ x: number; y: number } | null>(null)
|
||||||
const foldMenu = ref<{ x: number; y: number } | null>(null)
|
function openMore(e: MouseEvent) {
|
||||||
const foldEntries = computed<MenuEntry[]>(() => crumbs.value.folded.map(p => ({ label: p.name, icon: 'lucide:box', run: () => ed.goTo(p.i) })))
|
const r = (e.currentTarget as HTMLElement).getBoundingClientRect()
|
||||||
|
more.value = more.value ? null : { x: r.right - 240, y: r.bottom + 6 }
|
||||||
// The buttons that did not fit, in the order they have in the bar.
|
|
||||||
const moreMenu = ref<{ x: number; y: number } | null>(null)
|
|
||||||
const moreEntries = computed<MenuEntry[]>(() => {
|
|
||||||
const list: MenuEntry[] = []
|
|
||||||
if (tucked.value > 2) {
|
|
||||||
list.push(
|
|
||||||
{ label: 'Challenges and puzzles', icon: 'lucide:flag', note: `${solvedCount.value}/${CHALLENGES.length}`, run: () => (showChallenges.value = true) },
|
|
||||||
{ label: 'Find anything in the project', icon: 'lucide:search', keys: 'Ctrl+F', run: () => (ed.dialog.value = 'search') },
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
if (tucked.value > 1) {
|
const moreEntries = computed<MenuEntry[]>(() => [
|
||||||
list.push(
|
{ label: 'Your projects', icon: 'lucide:folder', run: () => (ed.dialog.value = 'projects') },
|
||||||
{ label: 'Undo', icon: 'lucide:undo-2', keys: 'Ctrl+Z', disabled: !ed.canUndo.value, run: () => ed.undo() },
|
{ label: 'Main menu', icon: 'lucide:house', run: () => ed.showMenu() },
|
||||||
{ label: 'Redo', icon: 'lucide:redo-2', keys: 'Ctrl+Shift+Z', disabled: !ed.canRedo.value, run: () => ed.redo() },
|
'sep',
|
||||||
)
|
{ label: 'Settings', icon: 'lucide:settings', note: 'symbols, wires, sound', run: () => (ed.dialog.value = 'settings') },
|
||||||
}
|
{ label: ed.sound.value.on ? 'Sound on' : 'Sound off', icon: ed.sound.value.on ? 'lucide:volume-2' : 'lucide:volume-x', checked: ed.sound.value.on, run: () => ed.setSound({ on: !ed.sound.value.on }) },
|
||||||
list.push(
|
{ label: ed.sidebars.left ? 'Hide the parts dock' : 'Show the parts dock', icon: 'lucide:panel-bottom', keys: '[', run: () => ed.toggleSidebar('left') },
|
||||||
{ label: 'Sound', icon: 'lucide:volume-x', checked: ed.sound.value.on, run: () => ed.setSound({ on: !ed.sound.value.on }) },
|
{ label: 'Print or save as PDF', icon: 'lucide:printer', keys: 'Ctrl+P', run: () => ed.exportSheet('print') },
|
||||||
{ label: 'Settings', icon: 'lucide:settings', run: () => (ed.dialog.value = 'settings') },
|
'sep',
|
||||||
{ label: 'How to play', icon: 'lucide:circle-help', keys: '?', run: () => (ed.showHelp.value = true) },
|
{ label: 'How to play', icon: 'lucide:circle-help', keys: '?', run: () => (ed.showHelp.value = true) },
|
||||||
)
|
{ label: ed.account.value ? `${ed.account.value.email}` : 'Sign in', icon: ed.account.value ? 'lucide:user-check' : 'lucide:user', note: ed.account.value ? cloudText.value : 'keep projects everywhere', run: () => (ed.dialog.value = 'account') },
|
||||||
if (tucked.value > 1) list.push('sep', { label: 'Share', icon: linkIcon.value, run: () => (ed.dialog.value = 'share') })
|
])
|
||||||
return list
|
|
||||||
})
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div ref="dock" class="top-dock">
|
<header class="hud">
|
||||||
<header class="top-bar">
|
<div class="hud-group">
|
||||||
<div class="tb-group min-w-0">
|
<button class="hud-btn brand" title="Main menu (your work is saved)" @click="ed.showMenu()">
|
||||||
<button class="bar-btn brand-btn" title="Menu: save, load, settings, main menu (Esc)" @click="ed.pause()">
|
<svg viewBox="0 0 32 32" class="size-5" aria-hidden="true">
|
||||||
<svg viewBox="0 0 32 32" class="size-5 shrink-0" aria-hidden="true">
|
<path d="M6 7h10a9 9 0 0 1 0 18H6Z" fill="none" stroke="currentColor" stroke-width="2.8" />
|
||||||
<path d="M6 7h10a9 9 0 0 1 0 18H6Z" fill="none" stroke="currentColor" stroke-width="2.5" />
|
<circle cx="27" cy="16" r="2.6" fill="none" stroke="currentColor" stroke-width="2.4" />
|
||||||
<circle cx="27" cy="16" r="2.6" fill="none" stroke="currentColor" stroke-width="2.2" />
|
|
||||||
</svg>
|
</svg>
|
||||||
<span class="project-name truncate">{{ ed.project.value.name }}</span>
|
|
||||||
</button>
|
</button>
|
||||||
<span class="bar-sep" />
|
<span class="hud-sep" />
|
||||||
<nav class="crumbs" aria-label="Where you are">
|
<button class="hud-btn hud-project" title="Your projects" @click="ed.dialog.value = 'projects'">
|
||||||
<button
|
<span class="truncate">{{ ed.project.value.name }}</span>
|
||||||
class="bar-btn"
|
|
||||||
:class="{ here: atMain, open: atMain && !!circuitMenu }"
|
|
||||||
:title="atMain ? 'This circuit: tidy its wires, print, publish, duplicate' : 'Go to Main (components open with a double-click)'"
|
|
||||||
@click="atMain ? openCircuitMenu($event) : ed.goMain()"
|
|
||||||
>
|
|
||||||
<Icon name="lucide:house" class="size-4" />
|
|
||||||
<span class="main-label">Main</span>
|
|
||||||
<Icon v-if="atMain" name="lucide:chevron-down" class="size-3.5 text-(--muted)" />
|
|
||||||
</button>
|
</button>
|
||||||
<template v-if="crumbs.folded.length">
|
<Icon name="lucide:chevron-right" class="size-3.5 shrink-0 text-(--muted)" />
|
||||||
<Icon name="lucide:chevron-right" class="crumb-sep size-3.5" />
|
<button v-if="backName" class="hud-btn" :title="`Back to ${backName}`" @click="ed.back()">
|
||||||
<button
|
<Icon name="lucide:arrow-left" class="size-4" />
|
||||||
class="bar-btn"
|
|
||||||
:class="{ open: !!foldMenu }"
|
|
||||||
:title="`${crumbs.folded.length} more on the way here: ${crumbs.folded.map(p => p.name).join(', ')}`"
|
|
||||||
@click="foldMenu = foldMenu ? null : below($event)"
|
|
||||||
>
|
|
||||||
<Icon name="lucide:ellipsis" class="size-4" />
|
|
||||||
</button>
|
</button>
|
||||||
</template>
|
<label class="hud-circuit" title="Circuit you are editing">
|
||||||
<template v-for="p in crumbs.shown" :key="`${p.id}-${p.i}`">
|
<select :value="ed.def.value.id" @change="ed.open(($event.target as HTMLSelectElement).value)">
|
||||||
<Icon name="lucide:chevron-right" class="crumb-sep size-3.5" />
|
<option v-for="d in ed.project.value.components" :key="d.id" :value="d.id">{{ d.name }}</option>
|
||||||
<button
|
</select>
|
||||||
class="bar-btn crumb"
|
<Icon name="lucide:chevron-down" class="size-3.5 text-(--muted)" />
|
||||||
:class="{ here: p.i < 0, open: p.i < 0 && !!circuitMenu }"
|
</label>
|
||||||
:title="p.i < 0 ? 'This circuit: tidy its wires, design its box, print, publish, duplicate, delete' : `Back to ${p.name}`"
|
|
||||||
@click="p.i < 0 ? openCircuitMenu($event) : ed.goTo(p.i)"
|
|
||||||
>
|
|
||||||
<span class="truncate">{{ p.name }}</span>
|
|
||||||
<Icon v-if="p.i < 0" name="lucide:chevron-down" class="size-3.5 shrink-0 text-(--muted)" />
|
|
||||||
</button>
|
|
||||||
</template>
|
|
||||||
</nav>
|
|
||||||
<EditorContextMenu v-if="circuitMenu" :x="circuitMenu.x" :y="circuitMenu.y" :entries="circuitEntries" @close="circuitMenu = null" />
|
|
||||||
<EditorContextMenu v-if="foldMenu" :x="foldMenu.x" :y="foldMenu.y" :entries="foldEntries" @close="foldMenu = null" />
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="tb-group">
|
<div class="hud-group hud-sim">
|
||||||
<div ref="challengesEl" class="relative">
|
<span class="status" :class="ed.status.value" :title="ed.status.value === 'oscillating' ? 'A loop keeps flipping and never settles (e.g. a NOT feeding itself)' : 'Simulation state'">
|
||||||
<button v-if="tucked < 3" class="bar-btn" :class="{ open: showChallenges }" title="Challenges, puzzles and the puzzle of the week" @click="showChallenges = !showChallenges">
|
<span class="dot" /><span class="hidden lg:inline">{{ statusText }}</span>
|
||||||
<Icon name="lucide:flag" class="size-4" />
|
</span>
|
||||||
<span class="bar-text">Challenges</span>
|
<template v-if="hasClock">
|
||||||
<span class="bar-count">{{ solvedCount }}/{{ CHALLENGES.length }}</span>
|
<span class="hud-sep" />
|
||||||
</button>
|
<button class="hud-btn" :class="{ active: ed.running.value }" :title="ed.running.value ? 'Pause the clock' : 'Run the clock'" @click="ed.running.value = !ed.running.value">
|
||||||
<Transition name="drop">
|
|
||||||
<div v-if="showChallenges" class="top-pop" :style="{ marginLeft: `${popShift}px` }">
|
|
||||||
<EditorChallengesPanel @close="showChallenges = false" />
|
|
||||||
</div>
|
|
||||||
</Transition>
|
|
||||||
</div>
|
|
||||||
<!-- On the narrowest bar Challenges is in "⋯" and the clock buttons are there only for a circuit with a clock. -->
|
|
||||||
<template v-if="hasClock || tucked < 3">
|
|
||||||
<span v-if="tucked < 3" class="bar-sep" />
|
|
||||||
<button
|
|
||||||
class="bar-btn"
|
|
||||||
:class="{ active: ed.running.value && hasClock }"
|
|
||||||
:title="ed.running.value ? 'Pause the clock' : 'Run the clock'"
|
|
||||||
:disabled="!hasClock"
|
|
||||||
@click="ed.running.value = !ed.running.value"
|
|
||||||
>
|
|
||||||
<Icon :name="ed.running.value ? 'lucide:pause' : 'lucide:play'" class="size-4" />
|
<Icon :name="ed.running.value ? 'lucide:pause' : 'lucide:play'" class="size-4" />
|
||||||
</button>
|
</button>
|
||||||
<button class="bar-btn" title="One clock cycle" :disabled="!hasClock" @click="ed.running.value = false; ed.step()">
|
<button class="hud-btn" title="One clock cycle" @click="ed.running.value = false; ed.step()">
|
||||||
<Icon name="lucide:step-forward" class="size-4" />
|
<Icon name="lucide:step-forward" class="size-4" />
|
||||||
</button>
|
</button>
|
||||||
</template>
|
<select v-model.number="ed.hz.value" class="hud-select" title="Clock speed">
|
||||||
<select v-model.number="ed.hz.value" class="tb-select" title="Clock speed" :disabled="!hasClock">
|
|
||||||
<option v-for="s in SPEEDS" :key="s.value" :value="s.value">{{ s.label }}</option>
|
<option v-for="s in SPEEDS" :key="s.value" :value="s.value">{{ s.label }}</option>
|
||||||
</select>
|
</select>
|
||||||
<button class="bar-btn" :class="{ open: !!toolsMenu }" title="Tools: converter, assembler" @click="toolsMenu = toolsMenu ? null : below($event)">
|
<span class="cycles tabular-nums" title="Clock cycles since this circuit was opened">{{ ed.cycles.value.toLocaleString() }}</span>
|
||||||
<Icon name="lucide:wrench" class="size-4" />
|
</template>
|
||||||
</button>
|
|
||||||
<EditorContextMenu v-if="toolsMenu" :x="toolsMenu.x" :y="toolsMenu.y" :entries="toolEntries" @close="toolsMenu = null" />
|
|
||||||
<span v-if="hasClock" class="cycles tabular-nums" title="Clock cycles since this circuit was opened">{{ ed.cycles.value.toLocaleString() }} ticks</span>
|
|
||||||
<span class="status" :class="ed.status.value" :title="ed.status.value === 'oscillating' ? 'A loop keeps flipping and never settles (e.g. a NOT feeding itself)' : 'Simulation state'">
|
|
||||||
<span class="dot" />{{ statusText }}
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="tb-group">
|
<div class="hud-group">
|
||||||
<button v-if="tucked < 3" class="bar-btn" title="Find anything in the project (Ctrl+F)" @click="ed.dialog.value = 'search'"><Icon name="lucide:search" class="size-4" /></button>
|
<button class="hud-btn" title="Find anything in the project (Ctrl+F)" @click="ed.dialog.value = 'search'"><Icon name="lucide:search" class="size-4" /></button>
|
||||||
<template v-if="tucked < 2">
|
<button class="hud-btn" title="Undo (Ctrl+Z)" :disabled="!ed.canUndo.value" @click="ed.undo()"><Icon name="lucide:undo-2" class="size-4" /></button>
|
||||||
<button class="bar-btn" title="Undo (Ctrl+Z)" :disabled="!ed.canUndo.value" @click="ed.undo()"><Icon name="lucide:undo-2" class="size-4" /></button>
|
<button class="hud-btn" title="Redo (Ctrl+Shift+Z)" :disabled="!ed.canRedo.value" @click="ed.redo()"><Icon name="lucide:redo-2" class="size-4" /></button>
|
||||||
<button class="bar-btn" title="Redo (Ctrl+Shift+Z)" :disabled="!ed.canRedo.value" @click="ed.redo()"><Icon name="lucide:redo-2" class="size-4" /></button>
|
<span class="hud-sep" />
|
||||||
</template>
|
<button class="hud-btn share-btn" :class="ed.linkState.value" title="Save online, share a link, export or import a file" @click="ed.dialog.value = 'share'">
|
||||||
<template v-if="!tucked">
|
|
||||||
<button class="bar-btn" :title="ed.sound.value.on ? 'Sound on (volume and clock ticks in Settings)' : 'Sound off'" @click="ed.setSound({ on: !ed.sound.value.on })">
|
|
||||||
<Icon :name="ed.sound.value.on ? 'lucide:volume-2' : 'lucide:volume-x'" class="size-4" />
|
|
||||||
</button>
|
|
||||||
<button class="bar-btn" title="Settings: gate symbols, wire crossings, current flow, tidy wiring, sound" @click="ed.dialog.value = 'settings'">
|
|
||||||
<Icon name="lucide:settings" class="size-4" />
|
|
||||||
</button>
|
|
||||||
<button class="bar-btn" title="Help (?)" @click="ed.showHelp.value = true"><Icon name="lucide:circle-help" class="size-4" /></button>
|
|
||||||
</template>
|
|
||||||
<button v-else class="bar-btn" :class="{ open: !!moreMenu }" title="More: sound, settings, help, …" @click="moreMenu = moreMenu ? null : below($event)">
|
|
||||||
<Icon name="lucide:ellipsis" class="size-4" />
|
|
||||||
</button>
|
|
||||||
<EditorContextMenu v-if="moreMenu" :x="moreMenu.x" :y="moreMenu.y" :entries="moreEntries" @close="moreMenu = null" />
|
|
||||||
<span class="bar-sep" />
|
|
||||||
<button v-if="tucked < 2" class="bar-btn share-btn" :class="ed.linkState.value" title="Save online, share a link, export or import a file" @click="ed.dialog.value = 'share'">
|
|
||||||
<Icon :name="linkIcon" class="size-4" />
|
<Icon :name="linkIcon" class="size-4" />
|
||||||
<span class="bar-text">Share</span>
|
<span class="hidden md:inline">Share</span>
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
class="bar-btn account-btn"
|
class="hud-btn"
|
||||||
:class="ed.cloudState.value"
|
:class="{ active: panelOpen }"
|
||||||
:title="ed.account.value ? `${ed.account.value.email}: ${cloudText}` : 'Sign in to keep your projects on every computer'"
|
:title="panelOpen ? 'Hide the side panel (])' : 'Circuit, pins and tests (])'"
|
||||||
@click="ed.dialog.value = 'account'"
|
@click="ed.toggleSidebar('right')"
|
||||||
>
|
>
|
||||||
<template v-if="ed.account.value">
|
<Icon name="lucide:panel-right" class="size-4" />
|
||||||
<span class="avatar">{{ ed.account.value.email[0]!.toUpperCase() }}</span>
|
</button>
|
||||||
<span class="sync-dot" />
|
<button class="hud-btn account-btn" :class="[ed.cloudState.value, { active: !!more }]" title="More: projects, settings, sound, help, account" @click="openMore">
|
||||||
</template>
|
<template v-if="ed.account.value"><span class="avatar">{{ ed.account.value.email[0]!.toUpperCase() }}</span><span class="sync-dot" /></template>
|
||||||
<template v-else>
|
<Icon v-else name="lucide:ellipsis" class="size-4" />
|
||||||
<Icon name="lucide:user" class="size-4" />
|
|
||||||
<span class="bar-text">Sign in</span>
|
|
||||||
</template>
|
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
<EditorContextMenu v-if="more" :x="more.x" :y="more.y" :entries="moreEntries" @close="more = null" />
|
||||||
</header>
|
</header>
|
||||||
</div>
|
|
||||||
</template>
|
</template>
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
const ed = useEditor()
|
const ed = useEditor()
|
||||||
const close = () => {
|
const close = () => {
|
||||||
ed.dialog.value = null
|
ed.dialog.value = 'projects'
|
||||||
ed.versionsFor.value = null
|
ed.versionsFor.value = null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -3,9 +3,9 @@
|
||||||
// as the matching button in the side panel.
|
// as the matching button in the side panel.
|
||||||
|
|
||||||
import { byPosition, sharedFamily, typeKey, type Arrange } from '~/lib/logic/bulk'
|
import { byPosition, sharedFamily, typeKey, type Arrange } from '~/lib/logic/bulk'
|
||||||
import { cableInUse, cableOf } from '~/lib/logic/cables'
|
import { cableOf } from '~/lib/logic/cables'
|
||||||
import { INVERTIBLE } from '~/lib/logic/compile'
|
import { INVERTIBLE } from '~/lib/logic/compile'
|
||||||
import { cableBits, chipPins, portName, type Pt } from '~/lib/logic/geometry'
|
import { cableBits, chipPins, type Pt } from '~/lib/logic/geometry'
|
||||||
import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
|
import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
|
||||||
import { KIND_NAMES } from '~/lib/logic/progress'
|
import { KIND_NAMES } from '~/lib/logic/progress'
|
||||||
import { LAMP_COLORS, WIRE_COLORS, type CircuitNode, type NodeKind } from '~/lib/logic/types'
|
import { LAMP_COLORS, WIRE_COLORS, type CircuitNode, type NodeKind } from '~/lib/logic/types'
|
||||||
|
|
@ -146,34 +146,10 @@ export function useMenu() {
|
||||||
{ label: 'Design its box', icon: 'lucide:pen-tool', run: () => ed.designFace(n.chip!) },
|
{ label: 'Design its box', icon: 'lucide:pen-tool', run: () => ed.designFace(n.chip!) },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (n.kind === 'scope') out.push({ label: 'Start over', icon: 'lucide:eraser', run: () => ed.clearScope(n.id) })
|
|
||||||
if (n.kind === 'bench') {
|
|
||||||
out.push(
|
|
||||||
{ label: 'Columns and rows', icon: 'lucide:table', keys: 'Double-click', run: () => (ed.benchOpen.value = n.id) },
|
|
||||||
{ label: 'Run the tests', icon: 'lucide:play', run: () => ed.runBenchNow(n.id, true) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (n.kind === 'terminal') out.push({ label: 'Clear the screen', icon: 'lucide:eraser', run: () => ed.clearScreen(n.id) })
|
|
||||||
if (n.kind === 'monitor' || n.kind === 'rgbmonitor') out.push({ label: 'Clear the screen', icon: 'lucide:eraser', run: () => ed.clearFrame(n.id) })
|
|
||||||
if (n.kind === 'terminal' || n.kind === 'monitor' || n.kind === 'rgbmonitor') out.push({ label: 'Turn (width and height swap)', icon: 'lucide:rotate-cw-square', run: () => ed.turnDisplay(n.id) })
|
|
||||||
if (n.kind === 'keyboard') {
|
|
||||||
out.push({ label: ed.typingInto.value === n.id ? 'Stop typing' : 'Type into it', icon: 'lucide:keyboard', keys: 'Click', run: () => ed.typeInto(n.id) })
|
|
||||||
if (ed.keyQueues.value.get(n.id)?.length) out.push({ label: 'Forget the waiting keys', icon: 'lucide:eraser', run: () => ed.clearKeys(n.id) })
|
|
||||||
}
|
|
||||||
if (n.kind === 'input') out.push({ label: n.on ? 'Switch off' : 'Switch on', icon: n.on ? 'lucide:toggle-right' : 'lucide:toggle-left', run: () => ed.toggleInput(n) })
|
if (n.kind === 'input') out.push({ label: n.on ? 'Switch off' : 'Switch on', icon: n.on ? 'lucide:toggle-right' : 'lucide:toggle-left', run: () => ed.toggleInput(n) })
|
||||||
if (NAMED.includes(n.kind)) out.push({ label: n.kind === 'note' ? 'Edit text' : 'Rename', icon: 'lucide:pencil', keys: 'Double-click', run: () => rename(n.id) })
|
if (NAMED.includes(n.kind)) out.push({ label: n.kind === 'note' ? 'Edit text' : 'Rename', icon: 'lucide:pencil', keys: 'Double-click', run: () => rename(n.id) })
|
||||||
const swaps = swapChoices([n])
|
const swaps = swapChoices([n])
|
||||||
if (swaps.length) out.push({ label: 'Change to', icon: 'lucide:replace', children: swaps })
|
if (swaps.length) out.push({ label: 'Change to', icon: 'lucide:replace', children: swaps })
|
||||||
// Latching: straight onto the part it is wired to, when its pins line up with that part's.
|
|
||||||
const host = n.latch ? ed.def.value.nodes.find(x => x.id === n.latch) : ed.latchTargetOf(n)
|
|
||||||
if (host) {
|
|
||||||
const name = host.label?.trim() && !host.autoLabel ? host.label.trim() : partName(host)
|
|
||||||
out.push(
|
|
||||||
n.latch
|
|
||||||
? { label: `Unlatch from ${name}`, icon: 'lucide:unlink', run: () => ed.unlatch(n) }
|
|
||||||
: { label: `Latch onto ${name}`, icon: 'lucide:link', run: () => ed.latchPart(n) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
const base = baseOf(n, get)
|
const base = baseOf(n, get)
|
||||||
if (base && gateFamily(get, base)) {
|
if (base && gateFamily(get, base)) {
|
||||||
const now = inputCount(n, get)
|
const now = inputCount(n, get)
|
||||||
|
|
@ -186,7 +162,7 @@ export function useMenu() {
|
||||||
}
|
}
|
||||||
if (INVERTIBLE.has(n.kind)) {
|
if (INVERTIBLE.has(n.kind)) {
|
||||||
const inv = new Set(n.invert ?? [])
|
const inv = new Set(n.invert ?? [])
|
||||||
const pins = ed.shape(n).inputs.filter(p => !p.bus && !p.port)
|
const pins = ed.shape(n).inputs
|
||||||
if (pins.length) {
|
if (pins.length) {
|
||||||
out.push({
|
out.push({
|
||||||
label: 'Invert input',
|
label: 'Invert input',
|
||||||
|
|
@ -201,8 +177,7 @@ export function useMenu() {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (n.kind === 'pixel') out.push(n.rgb ? { label: 'One colour (one input)', icon: 'lucide:square', run: () => ed.setRgb([n.id], false) } : { label: 'RGB (red, green, blue inputs)', icon: 'lucide:palette', run: () => ed.setRgb([n.id], true) })
|
if (n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel') {
|
||||||
if (n.kind === 'lamp' || n.kind === 'hex' || (n.kind === 'pixel' && !n.rgb)) {
|
|
||||||
out.push({
|
out.push({
|
||||||
label: 'Colour',
|
label: 'Colour',
|
||||||
swatches: [undefined, ...LAMP_COLORS].map(c => ({
|
swatches: [undefined, ...LAMP_COLORS].map(c => ({
|
||||||
|
|
@ -244,12 +219,6 @@ export function useMenu() {
|
||||||
if (pins.outputs.length && !dockedOut) out.push({ label: 'Attach output panel', icon: 'lucide:list-checks', run: () => ed.addPanel(n.id, 'out') })
|
if (pins.outputs.length && !dockedOut) out.push({ label: 'Attach output panel', icon: 'lucide:list-checks', run: () => ed.addPanel(n.id, 'out') })
|
||||||
if (pins.inputs.length) out.push({ label: 'Wire inputs one by one', icon: 'lucide:cable', run: () => ed.startLinking([n.id], 'in') })
|
if (pins.inputs.length) out.push({ label: 'Wire inputs one by one', icon: 'lucide:cable', run: () => ed.startLinking([n.id], 'in') })
|
||||||
if (pins.outputs.length) out.push({ label: 'Wire outputs one by one', icon: 'lucide:cable', run: () => ed.startLinking([n.id], 'out') })
|
if (pins.outputs.length) out.push({ label: 'Wire outputs one by one', icon: 'lucide:cable', run: () => ed.startLinking([n.id], 'out') })
|
||||||
// Ports: split into a pin per line on this box, to wire lines by hand, or joined again.
|
|
||||||
for (const p of pins.ports ?? []) {
|
|
||||||
const split = !!n.splitPorts?.includes(p.key)
|
|
||||||
const name = portName(p, get)
|
|
||||||
out.push({ label: split ? `Join ${name} lines` : `Split ${name} into lines`, icon: split ? 'lucide:merge' : 'lucide:split', run: () => ed.toggleSplit(n, p.key) })
|
|
||||||
}
|
|
||||||
out.push(
|
out.push(
|
||||||
{ label: 'Unpack into parts', icon: 'lucide:ungroup', run: () => ed.unpack(n.id) },
|
{ label: 'Unpack into parts', icon: 'lucide:ungroup', run: () => ed.unpack(n.id) },
|
||||||
{ label: 'Make independent copy', icon: 'lucide:copy-plus', run: () => ed.makeIndependent(n.id) },
|
{ label: 'Make independent copy', icon: 'lucide:copy-plus', run: () => ed.makeIndependent(n.id) },
|
||||||
|
|
@ -259,14 +228,14 @@ export function useMenu() {
|
||||||
if (cables.out.length || cables.in.length) out.push('sep')
|
if (cables.out.length || cables.in.length) out.push('sep')
|
||||||
if (cables.out.length) {
|
if (cables.out.length) {
|
||||||
out.push({
|
out.push({
|
||||||
label: 'Cable plug on outputs',
|
label: 'Cable from outputs',
|
||||||
icon: 'lucide:merge',
|
icon: 'lucide:merge',
|
||||||
children: cables.out.map(g => ({ label: g.label, note: `${g.pins.length} wires`, run: () => ed.cableOut(n.id, g.pins) })),
|
children: cables.out.map(g => ({ label: g.label, note: `${g.pins.length} wires`, run: () => ed.cableOut(n.id, g.pins) })),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
if (cables.in.length) {
|
if (cables.in.length) {
|
||||||
out.push({
|
out.push({
|
||||||
label: 'Cable plug on inputs',
|
label: 'Cable into inputs',
|
||||||
icon: 'lucide:split',
|
icon: 'lucide:split',
|
||||||
children: cables.in.map(g => ({ label: g.label, note: `${g.pins.length} wires`, run: () => ed.cableIn(n.id, g.pins) })),
|
children: cables.in.map(g => ({ label: g.label, note: `${g.pins.length} wires`, run: () => ed.cableIn(n.id, g.pins) })),
|
||||||
})
|
})
|
||||||
|
|
@ -313,10 +282,6 @@ export function useMenu() {
|
||||||
const fed = new Set(ed.def.value.wires.filter(w => w.to.node === n.id).map(w => w.to.pin))
|
const fed = new Set(ed.def.value.wires.filter(w => w.to.node === n.id).map(w => w.to.pin))
|
||||||
if (fed.size < cableBits(n)) out.push({ label: 'Attach input panel', icon: 'lucide:sliders-vertical', run: () => ed.addCablePanel(n.id) })
|
if (fed.size < cableBits(n)) out.push({ label: 'Attach input panel', icon: 'lucide:sliders-vertical', run: () => ed.addCablePanel(n.id) })
|
||||||
}
|
}
|
||||||
const use = cableInUse(ed.def.value, n.id)
|
|
||||||
if (use && use.after < use.before) {
|
|
||||||
out.push({ label: `Drop the ${use.before - use.after} unused wires`, note: `${use.before} → ${use.after}`, icon: 'lucide:scissors', run: () => ed.trimCableEnd(n.id) })
|
|
||||||
}
|
|
||||||
if (bundle) {
|
if (bundle) {
|
||||||
const sleeve = ed.def.value.wires.find(w => w.from.node === bundle.id)?.color
|
const sleeve = ed.def.value.wires.find(w => w.from.node === bundle.id)?.color
|
||||||
out.push(
|
out.push(
|
||||||
|
|
@ -367,12 +332,6 @@ export function useMenu() {
|
||||||
}
|
}
|
||||||
const swaps = swapChoices(nodes)
|
const swaps = swapChoices(nodes)
|
||||||
if (swaps.length) out.push({ label: 'Change all to', icon: 'lucide:replace', children: swaps })
|
if (swaps.length) out.push({ label: 'Change all to', icon: 'lucide:replace', children: swaps })
|
||||||
if (nodes.every(n => n.kind === 'pixel')) {
|
|
||||||
out.push({ label: 'Colours', icon: 'lucide:palette', children: [
|
|
||||||
{ label: 'One colour', checked: nodes.every(n => !n.rgb), run: () => ed.setRgb(ids, false) },
|
|
||||||
{ label: 'RGB', checked: nodes.every(n => n.rgb), run: () => ed.setRgb(ids, true) },
|
|
||||||
] })
|
|
||||||
}
|
|
||||||
if (nodes.every(n => n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel')) {
|
if (nodes.every(n => n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel')) {
|
||||||
const now = new Set(nodes.map(n => n.color))
|
const now = new Set(nodes.map(n => n.color))
|
||||||
out.push({
|
out.push({
|
||||||
|
|
@ -469,8 +428,7 @@ export function useMenu() {
|
||||||
'sep',
|
'sep',
|
||||||
{ label: 'Select all', icon: 'lucide:box-select', keys: 'Ctrl+A', disabled: !ed.def.value.nodes.length, run: () => ed.selectAll() },
|
{ label: 'Select all', icon: 'lucide:box-select', keys: 'Ctrl+A', disabled: !ed.def.value.nodes.length, run: () => ed.selectAll() },
|
||||||
{ label: 'Fit to screen', icon: 'lucide:scan', keys: 'F', run: ops.fit },
|
{ label: 'Fit to screen', icon: 'lucide:scan', keys: 'F', run: ops.fit },
|
||||||
{ label: 'Tidy this circuit', icon: 'lucide:wand-sparkles', disabled: !ed.def.value.wires.length, run: () => ed.tidyAll() },
|
{ label: 'Tidy all wires', icon: 'lucide:wand-sparkles', disabled: !ed.def.value.wires.length, run: () => ed.tidyAll() },
|
||||||
{ label: 'Tidy every circuit', icon: 'lucide:sparkles', run: () => ed.tidyEverything() },
|
|
||||||
{ label: 'Find…', icon: 'lucide:search', keys: 'Ctrl+F', run: () => (ed.dialog.value = 'search') },
|
{ label: 'Find…', icon: 'lucide:search', keys: 'Ctrl+F', run: () => (ed.dialog.value = 'search') },
|
||||||
{ label: 'Print sheet / PDF', icon: 'lucide:printer', keys: 'Ctrl+P', disabled: !ed.def.value.nodes.length, run: () => ed.exportSheet('print') },
|
{ label: 'Print sheet / PDF', icon: 'lucide:printer', keys: 'Ctrl+P', disabled: !ed.def.value.nodes.length, run: () => ed.exportSheet('print') },
|
||||||
'sep',
|
'sep',
|
||||||
|
|
|
||||||
|
|
@ -31,7 +31,6 @@ export const BASIC_GROUPS: { name: string; parts: BasicPart[] }[] = [
|
||||||
{ kind: 'clock', name: 'Clock', icon: 'lucide:audio-waveform', key: 'C', hint: 'Square wave. Speed and pause are in the top bar.', aka: 'oscillator tick' },
|
{ kind: 'clock', name: 'Clock', icon: 'lucide:audio-waveform', key: 'C', hint: 'Square wave. Speed and pause are in the top bar.', aka: 'oscillator tick' },
|
||||||
{ kind: 'panel', name: 'Input panel', icon: 'lucide:sliders-vertical', key: 'P', hint: 'A column of switches, buttons and clocks, each with its own name, key and colour.', aka: 'switches buttons' },
|
{ kind: 'panel', name: 'Input panel', icon: 'lucide:sliders-vertical', key: 'P', hint: 'A column of switches, buttons and clocks, each with its own name, key and colour.', aka: 'switches buttons' },
|
||||||
{ kind: 'high', name: 'Constant 1', icon: 'lucide:plus', hint: 'Always 1, like the supply rail.', aka: 'vcc high one supply' },
|
{ kind: 'high', name: 'Constant 1', icon: 'lucide:plus', hint: 'Always 1, like the supply rail.', aka: 'vcc high one supply' },
|
||||||
{ kind: 'keyboard', name: 'Keyboard', icon: 'lucide:keyboard', hint: 'Click it, then type: the first key waiting is on D0–D7 (its code), RDY is 1 while one waits, a rising NEXT takes it.', aka: 'text input ascii typing keys' },
|
|
||||||
{ kind: 'low', name: 'Ground (0)', icon: 'lucide:arrow-down-to-line', hint: 'Always 0.', aka: 'gnd low zero' },
|
{ kind: 'low', name: 'Ground (0)', icon: 'lucide:arrow-down-to-line', hint: 'Always 0.', aka: 'gnd low zero' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|
@ -42,10 +41,7 @@ export const BASIC_GROUPS: { name: string; parts: BasicPart[] }[] = [
|
||||||
{ kind: 'lamp', name: 'Lamp', icon: 'lucide:lightbulb', key: 'L', hint: 'Lights up at 1.', aka: 'led light' },
|
{ kind: 'lamp', name: 'Lamp', icon: 'lucide:lightbulb', key: 'L', hint: 'Lights up at 1.', aka: 'led light' },
|
||||||
{ kind: 'outpanel', name: 'Output panel', icon: 'lucide:list-checks', hint: 'A column of named lamps. Inside a component its rows are output pins.', aka: 'lamps leds' },
|
{ kind: 'outpanel', name: 'Output panel', icon: 'lucide:list-checks', hint: 'A column of named lamps. Inside a component its rows are output pins.', aka: 'lamps leds' },
|
||||||
{ kind: 'hex', name: 'Hex display', icon: 'lucide:binary', key: 'H', hint: 'Shows 4 bits as 0–F, and passes them on.', aka: 'seven segment 7seg digit' },
|
{ kind: 'hex', name: 'Hex display', icon: 'lucide:binary', key: 'H', hint: 'Shows 4 bits as 0–F, and passes them on.', aka: 'seven segment 7seg digit' },
|
||||||
{ kind: 'terminal', name: 'Terminal', icon: 'lucide:square-terminal', hint: 'A text screen: a rising WR writes the character whose code is on D0–D7 (10 starts a new line, 8 goes back); a rising CLR clears it.', aka: 'text output ascii console screen print' },
|
{ kind: 'pixel', name: 'Pixel', icon: 'lucide:square', key: 'X', hint: 'One square of a screen, lit at 1. Pixels inside a component show on its box as screens.', aka: 'screen lcd' },
|
||||||
{ kind: 'monitor', name: 'Monitor', icon: 'lucide:monitor', hint: 'A screen of pixels, one bit each (like an OLED): a rising WR sets the pixel at X, Y to D, a rising CLR clears it. Its size in pixels is yours to set.', aka: 'oled lcd screen display framebuffer graphics mono binary' },
|
|
||||||
{ kind: 'rgbmonitor', name: 'RGB monitor', icon: 'lucide:monitor-play', hint: 'A screen of pixels in eight colours: a rising WR sets the pixel at X, Y to R G B, a rising CLR clears it. Its size in pixels is yours to set.', aka: 'colour color screen display framebuffer graphics' },
|
|
||||||
{ kind: 'pixel', name: 'Pixel', icon: 'lucide:square', key: 'X', hint: 'One square of a screen, lit at 1, or in colour with red, green and blue inputs. Pixels inside a component show on its box as screens.', aka: 'screen lcd rgb colour color monitor' },
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|
@ -57,25 +53,6 @@ export const BASIC_GROUPS: { name: string; parts: BasicPart[] }[] = [
|
||||||
{ kind: 'ref', name: 'Use signal', icon: 'lucide:tag', hint: 'The signal of the "Send signal" with the same name, anywhere in this circuit.', aka: 'label net reference' },
|
{ kind: 'ref', name: 'Use signal', icon: 'lucide:tag', hint: 'The signal of the "Send signal" with the same name, anywhere in this circuit.', aka: 'label net reference' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
|
||||||
name: 'Testing',
|
|
||||||
parts: [
|
|
||||||
{
|
|
||||||
kind: 'bench',
|
|
||||||
name: 'Test bench',
|
|
||||||
icon: 'lucide:flask-conical',
|
|
||||||
hint: 'A table of tests on its box: its outputs drive what you wire them to, its inputs check what comes back. Drop it on a component to wire it to every pin.',
|
|
||||||
aka: 'test truth table check verify unit',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
kind: 'scope',
|
|
||||||
name: 'Logic analyzer',
|
|
||||||
icon: 'lucide:activity',
|
|
||||||
hint: 'The signals on its inputs over time, on its box. Drop it on a component to watch all its outputs; channels and bits in its settings.',
|
|
||||||
aka: 'scope waveform oscilloscope signals trace timing probe watch',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
name: 'Notes',
|
name: 'Notes',
|
||||||
parts: [{ kind: 'note', name: 'Note', icon: 'lucide:sticky-note', key: 'T', hint: 'Text label for your drawing.', aka: 'text comment' }],
|
parts: [{ kind: 'note', name: 'Note', icon: 'lucide:sticky-note', key: 'T', hint: 'Text label for your drawing.', aka: 'text comment' }],
|
||||||
|
|
|
||||||
|
|
@ -1,103 +0,0 @@
|
||||||
// Placing parts from anywhere (the bottom bar, pinned parts, the circuits
|
|
||||||
// list), and the parts pinned to the bottom bar. Pins are kept in this
|
|
||||||
// browser: built-in parts by kind, components by name, so a pinned "AND"
|
|
||||||
// stays pinned in every project, whether it is the example or your own.
|
|
||||||
|
|
||||||
import { BASIC_PARTS } from '~/composables/useParts'
|
|
||||||
import { challengeName, defUsable, KIND_UNLOCK } from '~/lib/logic/progress'
|
|
||||||
import type { ComponentDef, NodeKind } from '~/lib/logic/types'
|
|
||||||
|
|
||||||
const PIN_KEY = 'logigate:pinned'
|
|
||||||
const DEFAULT_PINS = ['nand', 'name:AND', 'name:OR', 'name:NOT', 'name:XOR', 'input', 'output', 'lamp', 'clock']
|
|
||||||
|
|
||||||
function loadPins(): string[] {
|
|
||||||
try {
|
|
||||||
const raw = JSON.parse(localStorage.getItem(PIN_KEY) ?? 'null')
|
|
||||||
if (Array.isArray(raw)) return raw.filter((k): k is string => typeof k === 'string').slice(0, 40)
|
|
||||||
} catch {}
|
|
||||||
return [...DEFAULT_PINS]
|
|
||||||
}
|
|
||||||
|
|
||||||
const pins = ref<string[]>(import.meta.client ? loadPins() : [...DEFAULT_PINS])
|
|
||||||
|
|
||||||
export interface PinnedPart {
|
|
||||||
pin: string
|
|
||||||
kind: NodeKind
|
|
||||||
chip?: string
|
|
||||||
name: string
|
|
||||||
icon: string
|
|
||||||
key?: string
|
|
||||||
/** Pinned, but not here: the component is not in this project, or not usable yet. */
|
|
||||||
missing?: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export function usePlace() {
|
|
||||||
const ed = useEditor()
|
|
||||||
|
|
||||||
function lockedHint(kind: NodeKind) {
|
|
||||||
const by = KIND_UNLOCK[kind]
|
|
||||||
return by ? `Solve the ${challengeName(by)} challenge to unlock this part` : ''
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Start placing a part: click on the canvas puts it there. */
|
|
||||||
function place(kind: NodeKind, chip?: string, conn?: string) {
|
|
||||||
if (chip && !ed.canPlace(chip)) {
|
|
||||||
ed.play('error')
|
|
||||||
return ed.notify('That component cannot go in here (it is this circuit, contains it, or is not solved yet)', 'error')
|
|
||||||
}
|
|
||||||
if (!ed.canPlaceKind(kind)) {
|
|
||||||
ed.play('error')
|
|
||||||
return ed.notify(lockedHint(kind), 'error')
|
|
||||||
}
|
|
||||||
ed.placing.value = { kind, chip, ...(conn ? { conn } : {}) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Dragging a part onto the canvas places it where it is dropped. */
|
|
||||||
function dragStart(e: DragEvent, kind: NodeKind, chip?: string, conn?: string) {
|
|
||||||
if ((chip && !ed.canPlace(chip)) || !ed.canPlaceKind(kind)) {
|
|
||||||
e.preventDefault()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
e.dataTransfer?.setData('application/x-logigate', JSON.stringify({ kind, chip, conn }))
|
|
||||||
if (e.dataTransfer) e.dataTransfer.effectAllowed = 'copy'
|
|
||||||
ed.dragPart.value = { kind, chip, ...(conn ? { conn } : {}) }
|
|
||||||
}
|
|
||||||
|
|
||||||
function dragEnd() {
|
|
||||||
ed.dragPart.value = null
|
|
||||||
}
|
|
||||||
|
|
||||||
const pinOf = (kind: NodeKind, def?: ComponentDef) => (def ? `name:${def.name}` : kind)
|
|
||||||
const isPinned = (kind: NodeKind, def?: ComponentDef) => pins.value.includes(pinOf(kind, def))
|
|
||||||
|
|
||||||
function togglePin(kind: NodeKind, def?: ComponentDef) {
|
|
||||||
const key = pinOf(kind, def)
|
|
||||||
pins.value = pins.value.includes(key) ? pins.value.filter(k => k !== key) : [...pins.value, key]
|
|
||||||
try {
|
|
||||||
localStorage.setItem(PIN_KEY, JSON.stringify(pins.value))
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
|
|
||||||
function unpin(key: string) {
|
|
||||||
pins.value = pins.value.filter(k => k !== key)
|
|
||||||
try {
|
|
||||||
localStorage.setItem(PIN_KEY, JSON.stringify(pins.value))
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The pinned parts as they stand in this project. */
|
|
||||||
const pinned = computed<PinnedPart[]>(() =>
|
|
||||||
pins.value.flatMap((pin): PinnedPart[] => {
|
|
||||||
if (pin.startsWith('name:')) {
|
|
||||||
const name = pin.slice(5)
|
|
||||||
const d = ed.project.value.components.find(c => c.name === name && c.id !== ed.def.value.id) ?? ed.project.value.components.find(c => c.name === name)
|
|
||||||
const usable = !!d && d.id !== ed.def.value.id && ed.canPlace(d.id) && defUsable(ed.project.value, d)
|
|
||||||
return [{ pin, kind: 'chip' as NodeKind, chip: d?.id, name, icon: 'lucide:box', missing: !usable }]
|
|
||||||
}
|
|
||||||
const p = BASIC_PARTS.find(b => b.kind === pin)
|
|
||||||
return p ? [{ pin, kind: p.kind, name: p.name, icon: p.icon, key: p.key, missing: !ed.canPlaceKind(p.kind) }] : []
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
|
|
||||||
return { place, dragStart, dragEnd, lockedHint, pinned, isPinned, togglePin, unpin }
|
|
||||||
}
|
|
||||||
394
app/lib/asm.ts
394
app/lib/asm.ts
|
|
@ -1,394 +0,0 @@
|
||||||
// The assembler tool: your own instruction set, written as a table, turns a
|
|
||||||
// program into words for the memory you built. One instruction per table
|
|
||||||
// line: its name, its opcode bits, then its operands as name:bits. Opcode and
|
|
||||||
// operands fill a word from its top bit down; bits left over are 0, and an
|
|
||||||
// instruction longer than a word takes as many words as it needs.
|
|
||||||
|
|
||||||
import type { AsmDoc, CircuitNode, ComponentDef } from './logic/types'
|
|
||||||
|
|
||||||
export type { AsmDoc }
|
|
||||||
|
|
||||||
|
|
||||||
export interface AsmError {
|
|
||||||
where: 'table' | 'source'
|
|
||||||
/** 1-based. */
|
|
||||||
line: number
|
|
||||||
text: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface OpDef {
|
|
||||||
name: string
|
|
||||||
/** Opcode as bits, highest first. */
|
|
||||||
bits: string
|
|
||||||
fields: { name: string; bits: number }[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AsmLine {
|
|
||||||
line: number
|
|
||||||
addr: number
|
|
||||||
words: number[]
|
|
||||||
text: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AsmResult {
|
|
||||||
lines: AsmLine[]
|
|
||||||
/** Memory from address 0 to the last word written; words not written are 0. */
|
|
||||||
image: number[]
|
|
||||||
labels: Map<string, number>
|
|
||||||
errors: AsmError[]
|
|
||||||
}
|
|
||||||
|
|
||||||
export const MAX_WIDTH = 32
|
|
||||||
export const MAX_WORDS = 65_536
|
|
||||||
|
|
||||||
export const EXAMPLE: AsmDoc = {
|
|
||||||
width: 8,
|
|
||||||
table: `; One instruction per line: its name, its opcode bits, then its operands as name:bits.
|
|
||||||
; Opcode and operands fill the word from its top bit; bits left over are 0.
|
|
||||||
NOP 0000
|
|
||||||
LDA 0001 addr:4
|
|
||||||
ADD 0010 addr:4
|
|
||||||
SUB 0011 addr:4
|
|
||||||
STA 0100 addr:4
|
|
||||||
LDI 0101 value:4
|
|
||||||
JMP 0110 addr:4
|
|
||||||
JC 0111 addr:4
|
|
||||||
JZ 1000 addr:4
|
|
||||||
OUT 1110
|
|
||||||
HLT 1111`,
|
|
||||||
source: `; Adds 3 again and again and shows it, until it carries past 255.
|
|
||||||
start: LDI 0
|
|
||||||
loop: ADD three
|
|
||||||
OUT
|
|
||||||
JC done
|
|
||||||
JMP loop
|
|
||||||
done: HLT
|
|
||||||
three: .word 3`,
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Removes a comment (; or //), leaving quoted text alone. */
|
|
||||||
function stripComment(line: string): string {
|
|
||||||
let q = ''
|
|
||||||
for (let i = 0; i < line.length; i++) {
|
|
||||||
const c = line[i]!
|
|
||||||
if (q) {
|
|
||||||
if (c === '\\') i++
|
|
||||||
else if (c === q) q = ''
|
|
||||||
} else if (c === '"' || c === "'") q = c
|
|
||||||
else if (c === ';' || (c === '/' && line[i + 1] === '/')) return line.slice(0, i)
|
|
||||||
}
|
|
||||||
return line
|
|
||||||
}
|
|
||||||
|
|
||||||
export function parseTable(text: string): { ops: Map<string, OpDef>; errors: AsmError[] } {
|
|
||||||
const ops = new Map<string, OpDef>()
|
|
||||||
const errors: AsmError[] = []
|
|
||||||
text.split('\n').forEach((raw, i) => {
|
|
||||||
const err = (t: string) => errors.push({ where: 'table', line: i + 1, text: t })
|
|
||||||
const parts = stripComment(raw).trim().split(/[\s,]+/).filter(Boolean)
|
|
||||||
if (!parts.length) return
|
|
||||||
const [name, code, ...rest] = parts
|
|
||||||
if (!/^[A-Za-z_.][\w.]*$/.test(name!)) return err(`"${name}" is not a name for an instruction`)
|
|
||||||
let bits = ''
|
|
||||||
if (code === undefined) return err(`${name}: its opcode bits are missing`)
|
|
||||||
if (/^[01]+$/.test(code)) bits = code
|
|
||||||
else if (/^0x[0-9a-f]+$/i.test(code)) bits = [...code.slice(2)].map(d => parseInt(d, 16).toString(2).padStart(4, '0')).join('')
|
|
||||||
else return err(`${name}: opcode "${code}" is not bits (like 0101, or 0x5 for 4 bits)`)
|
|
||||||
const fields: OpDef['fields'] = []
|
|
||||||
for (const f of rest) {
|
|
||||||
const m = /^([A-Za-z_]\w*):(\d+)$/.exec(f)
|
|
||||||
if (!m || +m[2]! < 1 || +m[2]! > MAX_WIDTH) return err(`${name}: operand "${f}" should be name:bits, like addr:4`)
|
|
||||||
fields.push({ name: m[1]!, bits: +m[2]! })
|
|
||||||
}
|
|
||||||
const key = name!.toUpperCase()
|
|
||||||
if (ops.has(key)) return err(`${name} is in the table twice`)
|
|
||||||
ops.set(key, { name: name!, bits, fields })
|
|
||||||
})
|
|
||||||
return { ops, errors }
|
|
||||||
}
|
|
||||||
|
|
||||||
const DIRECTIVES = {
|
|
||||||
word: ['.word', '.db', '.dw', '.byte', '.data', 'db', 'dw'],
|
|
||||||
org: ['.org', 'org'],
|
|
||||||
fill: ['.fill', '.space'],
|
|
||||||
equ: ['.equ', '.set', 'equ'],
|
|
||||||
}
|
|
||||||
const isDir = (w: string, kind: keyof typeof DIRECTIVES) => DIRECTIVES[kind].includes(w.toLowerCase())
|
|
||||||
|
|
||||||
/** Splits operands at commas outside quotes. */
|
|
||||||
function splitArgs(s: string): string[] {
|
|
||||||
const out: string[] = []
|
|
||||||
let cur = ''
|
|
||||||
let q = ''
|
|
||||||
for (let i = 0; i < s.length; i++) {
|
|
||||||
const c = s[i]!
|
|
||||||
if (q) {
|
|
||||||
cur += c
|
|
||||||
if (c === '\\') cur += s[++i] ?? ''
|
|
||||||
else if (c === q) q = ''
|
|
||||||
} else if (c === '"' || c === "'") {
|
|
||||||
q = c
|
|
||||||
cur += c
|
|
||||||
} else if (c === ',') {
|
|
||||||
out.push(cur.trim())
|
|
||||||
cur = ''
|
|
||||||
} else cur += c
|
|
||||||
}
|
|
||||||
if (cur.trim()) out.push(cur.trim())
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
const ESC: Record<string, string> = { n: '\n', t: '\t', r: '\r', '0': '\0', '\\': '\\', '"': '"', "'": "'" }
|
|
||||||
const unescape = (s: string) => s.replace(/\\(.)/g, (_, c: string) => ESC[c] ?? c)
|
|
||||||
|
|
||||||
/** A number, a character, a name, or several joined by + and -. `$` alone is the address of this line. */
|
|
||||||
function evaluate(expr: string, names: Map<string, number>, here: number): number | string {
|
|
||||||
const tokens = expr.replace(/\s+/g, '').match(/[+-]|'(?:\\.|[^'])'|[^+-]+/g)
|
|
||||||
if (!tokens) return 'nothing to work out'
|
|
||||||
let total = 0
|
|
||||||
let sign = 1
|
|
||||||
let expectTerm = true
|
|
||||||
for (const t of tokens) {
|
|
||||||
if (t === '+' || t === '-') {
|
|
||||||
if (expectTerm) sign *= t === '-' ? -1 : 1
|
|
||||||
else {
|
|
||||||
sign = t === '-' ? -1 : 1
|
|
||||||
expectTerm = true
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
let v: number
|
|
||||||
if (/^\d+$/.test(t)) v = parseInt(t, 10)
|
|
||||||
else if (/^0x[0-9a-f]+$/i.test(t)) v = parseInt(t.slice(2), 16)
|
|
||||||
else if (/^\$[0-9a-f]+$/i.test(t)) v = parseInt(t.slice(1), 16)
|
|
||||||
else if (/^[0-9][0-9a-f]*h$/i.test(t)) v = parseInt(t.slice(0, -1), 16)
|
|
||||||
else if (/^0b[01]+$/i.test(t)) v = parseInt(t.slice(2), 2)
|
|
||||||
else if (/^0o[0-7]+$/i.test(t)) v = parseInt(t.slice(2), 8)
|
|
||||||
else if (/^'(\\.|[^'])'$/.test(t)) v = unescape(t.slice(1, -1)).codePointAt(0)!
|
|
||||||
else if (t === '$') v = here
|
|
||||||
else if (/^[A-Za-z_.][\w.]*$/.test(t)) {
|
|
||||||
const n = names.get(t.toLowerCase())
|
|
||||||
if (n === undefined) return `"${t}" is not a label or name`
|
|
||||||
v = n
|
|
||||||
} else return `"${t}" is not a number or name`
|
|
||||||
if (!expectTerm) return `"${t}" needs a + or - before it`
|
|
||||||
total += sign * v
|
|
||||||
sign = 1
|
|
||||||
expectTerm = false
|
|
||||||
}
|
|
||||||
if (expectTerm) return 'ends with + or -'
|
|
||||||
return total
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A value as bits of a field; fits when it is 0 to 2^bits - 1, or negative down to -2^(bits-1) (two's complement). */
|
|
||||||
function fieldBits(v: number, bits: number): string | null {
|
|
||||||
if (!Number.isInteger(v) || v >= 2 ** bits || v < -(2 ** (bits - 1))) return null
|
|
||||||
return (v < 0 ? v + 2 ** bits : v).toString(2).padStart(bits, '0')
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Stmt {
|
|
||||||
line: number
|
|
||||||
text: string
|
|
||||||
addr: number
|
|
||||||
kind: 'op' | 'word' | 'fill'
|
|
||||||
op?: OpDef
|
|
||||||
args: string[]
|
|
||||||
size: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export function assemble(source: string, table: string, width: number): AsmResult {
|
|
||||||
const errors: AsmError[] = []
|
|
||||||
const t = parseTable(table)
|
|
||||||
errors.push(...t.errors)
|
|
||||||
const w = Math.round(width)
|
|
||||||
if (!(w >= 1 && w <= MAX_WIDTH)) {
|
|
||||||
errors.push({ where: 'source', line: 0, text: `A word is 1 to ${MAX_WIDTH} bits` })
|
|
||||||
return { lines: [], image: [], labels: new Map(), errors }
|
|
||||||
}
|
|
||||||
const names = new Map<string, number>()
|
|
||||||
const labels = new Map<string, number>()
|
|
||||||
const stmts: Stmt[] = []
|
|
||||||
let addr = 0
|
|
||||||
|
|
||||||
// Pass 1: where everything goes.
|
|
||||||
source.split('\n').forEach((raw, i) => {
|
|
||||||
const line = i + 1
|
|
||||||
const err = (text: string) => errors.push({ where: 'source', line, text })
|
|
||||||
let s = stripComment(raw).trim()
|
|
||||||
const text = s
|
|
||||||
// Labels at the start.
|
|
||||||
for (let m = /^([A-Za-z_.][\w.]*):/.exec(s); m; m = /^([A-Za-z_.][\w.]*):/.exec(s)) {
|
|
||||||
const key = m[1]!.toLowerCase()
|
|
||||||
if (names.has(key)) err(`${m[1]} is defined twice`)
|
|
||||||
names.set(key, addr)
|
|
||||||
labels.set(m[1]!, addr)
|
|
||||||
s = s.slice(m[0].length).trim()
|
|
||||||
}
|
|
||||||
if (!s) return
|
|
||||||
// NAME = value, NAME equ value, .equ NAME, value
|
|
||||||
const eq = /^([A-Za-z_][\w]*)\s*(?:=|\s+equ\s+)(.+)$/i.exec(s) ?? (/^\.(?:equ|set)\s+([A-Za-z_]\w*)\s*[,\s]\s*(.+)$/i.exec(s) as RegExpExecArray | null)
|
|
||||||
if (eq) {
|
|
||||||
const v = evaluate(eq[2]!, names, addr)
|
|
||||||
if (typeof v === 'string') return err(v)
|
|
||||||
if (names.has(eq[1]!.toLowerCase())) return err(`${eq[1]} is defined twice`)
|
|
||||||
names.set(eq[1]!.toLowerCase(), v)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const [word] = s.split(/\s+/)
|
|
||||||
const rest = s.slice(word!.length).trim()
|
|
||||||
const args = splitArgs(rest)
|
|
||||||
if (isDir(word!, 'org')) {
|
|
||||||
const v = evaluate(rest, names, addr)
|
|
||||||
if (typeof v === 'string') return err(`.org: ${v}`)
|
|
||||||
if (v < 0 || v >= MAX_WORDS) return err(`.org: address ${v} is outside 0 to ${MAX_WORDS - 1}`)
|
|
||||||
addr = v
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (isDir(word!, 'word')) {
|
|
||||||
let size = 0
|
|
||||||
for (const a of args) size += /^"(.*)"$/.test(a) ? [...unescape(a.slice(1, -1))].length : 1
|
|
||||||
if (!args.length) return err(`${word}: no values`)
|
|
||||||
stmts.push({ line, text, addr, kind: 'word', args, size })
|
|
||||||
addr += size
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (isDir(word!, 'fill')) {
|
|
||||||
const n = evaluate(args[0] ?? '', names, addr)
|
|
||||||
if (typeof n === 'string') return err(`${word}: ${n} (the count must be known by here)`)
|
|
||||||
if (n < 0 || n > MAX_WORDS) return err(`${word}: ${n} words is too many`)
|
|
||||||
stmts.push({ line, text, addr, kind: 'fill', args: args.slice(1), size: n })
|
|
||||||
addr += n
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const op = t.ops.get(word!.toUpperCase())
|
|
||||||
if (!op) return err(`"${word}" is not in the instruction set`)
|
|
||||||
const total = op.bits.length + op.fields.reduce((n, f) => n + f.bits, 0)
|
|
||||||
const size = Math.max(1, Math.ceil(total / w))
|
|
||||||
stmts.push({ line, text, addr, kind: 'op', op, args, size })
|
|
||||||
addr += size
|
|
||||||
})
|
|
||||||
|
|
||||||
// Pass 2: the words.
|
|
||||||
const lines: AsmLine[] = []
|
|
||||||
const used = new Map<number, number>()
|
|
||||||
let top = 0
|
|
||||||
for (const st of stmts) {
|
|
||||||
const err = (text: string) => errors.push({ where: 'source', line: st.line, text })
|
|
||||||
// Its addresses, taken even when it has an error, so a clash still shows.
|
|
||||||
for (let k = 0; k < st.size; k++) {
|
|
||||||
const a = st.addr + k
|
|
||||||
if (a >= MAX_WORDS) {
|
|
||||||
err(`goes past address ${MAX_WORDS - 1}`)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
const before = used.get(a)
|
|
||||||
if (before !== undefined) {
|
|
||||||
err(`address ${a} is also written by line ${before}`)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
used.set(a, st.line)
|
|
||||||
}
|
|
||||||
const words: number[] = []
|
|
||||||
if (st.kind === 'op') {
|
|
||||||
const op = st.op!
|
|
||||||
if (st.args.length !== op.fields.length) {
|
|
||||||
err(`${op.name} takes ${op.fields.length ? op.fields.map(f => f.name).join(', ') : 'no operands'}${st.args.length ? `, not ${st.args.length}` : ''}`)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
let bits = op.bits
|
|
||||||
let ok = true
|
|
||||||
op.fields.forEach((f, k) => {
|
|
||||||
const v = evaluate(st.args[k]!, names, st.addr)
|
|
||||||
if (typeof v === 'string') {
|
|
||||||
ok = false
|
|
||||||
return err(`${op.name} ${f.name}: ${v}`)
|
|
||||||
}
|
|
||||||
const b = fieldBits(v, f.bits)
|
|
||||||
if (b === null) {
|
|
||||||
ok = false
|
|
||||||
return err(`${op.name} ${f.name}: ${v} does not fit in ${f.bits} bits`)
|
|
||||||
}
|
|
||||||
bits += b
|
|
||||||
})
|
|
||||||
if (!ok) continue
|
|
||||||
bits = bits.padEnd(st.size * w, '0')
|
|
||||||
for (let k = 0; k < st.size; k++) words.push(parseInt(bits.slice(k * w, (k + 1) * w), 2))
|
|
||||||
} else if (st.kind === 'word') {
|
|
||||||
for (const a of st.args) {
|
|
||||||
if (/^"(.*)"$/.test(a)) {
|
|
||||||
for (const c of unescape(a.slice(1, -1))) {
|
|
||||||
const v = c.codePointAt(0)!
|
|
||||||
if (fieldBits(v, w) === null) err(`"${c}" (${v}) does not fit in ${w} bits`)
|
|
||||||
words.push(v)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const v = evaluate(a, names, st.addr + words.length)
|
|
||||||
if (typeof v === 'string') {
|
|
||||||
err(v)
|
|
||||||
words.push(0)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const b = fieldBits(v, w)
|
|
||||||
if (b === null) err(`${v} does not fit in ${w} bits`)
|
|
||||||
words.push(b === null ? 0 : parseInt(b, 2))
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const v = st.args[0] ? evaluate(st.args[0], names, st.addr) : 0
|
|
||||||
const b = typeof v === 'string' ? null : fieldBits(v, w)
|
|
||||||
if (typeof v === 'string') err(v)
|
|
||||||
else if (b === null) err(`${v} does not fit in ${w} bits`)
|
|
||||||
for (let k = 0; k < st.size; k++) words.push(b === null ? 0 : parseInt(b, 2))
|
|
||||||
}
|
|
||||||
top = Math.max(top, st.addr + words.length)
|
|
||||||
lines.push({ line: st.line, addr: st.addr, words, text: st.text })
|
|
||||||
}
|
|
||||||
const image = new Array<number>(Math.min(top, MAX_WORDS)).fill(0)
|
|
||||||
for (const l of lines) l.words.forEach((v, k) => l.addr + k < image.length && (image[l.addr + k] = v))
|
|
||||||
errors.sort((a, b) => (a.where === b.where ? a.line - b.line : a.where === 'table' ? -1 : 1))
|
|
||||||
return { lines, image, labels, errors }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A word as hex or binary digits of the word width. */
|
|
||||||
export const hexWord = (v: number, width: number) => v.toString(16).toUpperCase().padStart(Math.ceil(width / 4), '0')
|
|
||||||
export const binWord = (v: number, width: number) => v.toString(2).padStart(width, '0')
|
|
||||||
|
|
||||||
// ── Into memory you built ────────────────────────────────────────────
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The input panels of a circuit that can hold words: all their rows are
|
|
||||||
* switches. In reading order: rows of panels top to bottom (panels whose
|
|
||||||
* tops are within half a panel of each other are one row), each left to right.
|
|
||||||
*/
|
|
||||||
export function memoryPanels(def: ComponentDef): CircuitNode[] {
|
|
||||||
const list = def.nodes.filter(n => n.kind === 'panel' && n.rows?.length && n.rows.every(r => r.type === 'switch')).sort((a, b) => a.y - b.y || a.x - b.x)
|
|
||||||
const rows: CircuitNode[][] = []
|
|
||||||
for (const n of list) {
|
|
||||||
const row = rows[rows.length - 1]
|
|
||||||
const top = row?.[0]
|
|
||||||
if (top && n.y - top.y < Math.max(1, (top.rows!.length) / 2)) row.push(n)
|
|
||||||
else rows.push([n])
|
|
||||||
}
|
|
||||||
return rows.flatMap(r => r.sort((a, b) => a.x - b.x))
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Puts words into a circuit's memory panels, one word a panel; panels left
|
|
||||||
* over go to 0. Row i of a panel is bit i (or, with `msbTop`, the top row is
|
|
||||||
* the highest bit). A panel with fewer rows than a word has bits refuses.
|
|
||||||
*/
|
|
||||||
export function loadIntoPanels(def: ComponentDef, words: number[], width: number, msbTop = false): { ok: true; panels: number; cleared: number } | { ok: false; error: string } {
|
|
||||||
const panels = memoryPanels(def)
|
|
||||||
if (!panels.length) return { ok: false, error: `"${def.name}" has no input panel of switches to hold the words` }
|
|
||||||
if (words.length > panels.length) return { ok: false, error: `${words.length} words, but "${def.name}" has ${panels.length} panel${panels.length === 1 ? '' : 's'} of switches` }
|
|
||||||
const short = panels.find(p => p.rows!.length < width)
|
|
||||||
if (short) return { ok: false, error: `A panel in "${def.name}" has ${short.rows!.length} switches, a word ${width} bits` }
|
|
||||||
panels.forEach((p, i) => {
|
|
||||||
const v = words[i] ?? 0
|
|
||||||
p.rows!.forEach((r, k) => {
|
|
||||||
const bit = msbTop ? width - 1 - k : k
|
|
||||||
r.on = bit >= 0 && bit < width && Math.floor(v / 2 ** bit) % 2 === 1
|
|
||||||
})
|
|
||||||
})
|
|
||||||
return { ok: true, panels: words.length, cleared: panels.length - words.length }
|
|
||||||
}
|
|
||||||
|
|
@ -1,203 +0,0 @@
|
||||||
// The converter tool: text, hex, binary, decimal, octal and Base64 into one
|
|
||||||
// another. Everything goes through bytes: text by its encoding, numbers as
|
|
||||||
// words of 8, 16 or 32 bits (several bytes each in big- or little-endian).
|
|
||||||
|
|
||||||
export const FORMATS = ['text', 'hex', 'bin', 'dec', 'oct', 'base64'] as const
|
|
||||||
export type Format = (typeof FORMATS)[number]
|
|
||||||
export const FORMAT_NAMES: Record<Format, string> = { text: 'Text', hex: 'Hex', bin: 'Binary', dec: 'Decimal', oct: 'Octal', base64: 'Base64' }
|
|
||||||
|
|
||||||
export const ENCODINGS = ['utf8', 'ascii', 'latin1', 'utf16le', 'utf16be', 'utf32be'] as const
|
|
||||||
export type Encoding = (typeof ENCODINGS)[number]
|
|
||||||
export const ENCODING_NAMES: Record<Encoding, string> = {
|
|
||||||
utf8: 'UTF-8',
|
|
||||||
ascii: 'ASCII (7 bits)',
|
|
||||||
latin1: 'Latin-1 (ISO 8859-1)',
|
|
||||||
utf16le: 'UTF-16 little-endian',
|
|
||||||
utf16be: 'UTF-16 big-endian',
|
|
||||||
utf32be: 'UTF-32 big-endian',
|
|
||||||
}
|
|
||||||
|
|
||||||
export type WordBits = 8 | 16 | 32
|
|
||||||
export interface ConvertOptions {
|
|
||||||
enc: Encoding
|
|
||||||
word: WordBits
|
|
||||||
endian: 'big' | 'little'
|
|
||||||
}
|
|
||||||
|
|
||||||
export type Result<T> = { ok: true; value: T; note?: string } | { ok: false; error: string }
|
|
||||||
|
|
||||||
// ── Text ⇄ bytes ─────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export function encodeText(s: string, enc: Encoding): Result<Uint8Array> {
|
|
||||||
const out: number[] = []
|
|
||||||
const cps = [...s].map(c => c.codePointAt(0)!)
|
|
||||||
switch (enc) {
|
|
||||||
case 'utf8':
|
|
||||||
return { ok: true, value: new TextEncoder().encode(s) }
|
|
||||||
case 'ascii':
|
|
||||||
case 'latin1': {
|
|
||||||
const max = enc === 'ascii' ? 0x7f : 0xff
|
|
||||||
const bad = cps.findIndex(c => c > max)
|
|
||||||
if (bad >= 0) return { ok: false, error: `"${String.fromCodePoint(cps[bad]!)}" (character ${bad + 1}) has no code in ${ENCODING_NAMES[enc]}` }
|
|
||||||
return { ok: true, value: Uint8Array.from(cps) }
|
|
||||||
}
|
|
||||||
case 'utf16le':
|
|
||||||
case 'utf16be':
|
|
||||||
for (let i = 0; i < s.length; i++) {
|
|
||||||
const u = s.charCodeAt(i)
|
|
||||||
if (enc === 'utf16le') out.push(u & 0xff, u >> 8)
|
|
||||||
else out.push(u >> 8, u & 0xff)
|
|
||||||
}
|
|
||||||
return { ok: true, value: Uint8Array.from(out) }
|
|
||||||
case 'utf32be':
|
|
||||||
for (const c of cps) out.push((c >>> 24) & 0xff, (c >>> 16) & 0xff, (c >>> 8) & 0xff, c & 0xff)
|
|
||||||
return { ok: true, value: Uint8Array.from(out) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function decodeText(b: Uint8Array, enc: Encoding): Result<string> {
|
|
||||||
switch (enc) {
|
|
||||||
case 'utf8': {
|
|
||||||
const text = new TextDecoder('utf-8').decode(b)
|
|
||||||
return { ok: true, value: text, ...(text.includes('<27>') ? { note: 'Some bytes are not valid UTF-8 (shown as <20>)' } : {}) }
|
|
||||||
}
|
|
||||||
case 'ascii':
|
|
||||||
case 'latin1': {
|
|
||||||
const bad = enc === 'ascii' && b.some(x => x > 0x7f)
|
|
||||||
let text = ''
|
|
||||||
for (const x of b) text += enc === 'ascii' && x > 0x7f ? '<27>' : String.fromCharCode(x)
|
|
||||||
return { ok: true, value: text, ...(bad ? { note: 'Bytes above 7F are not ASCII (shown as <20>)' } : {}) }
|
|
||||||
}
|
|
||||||
case 'utf16le':
|
|
||||||
case 'utf16be': {
|
|
||||||
let text = ''
|
|
||||||
for (let i = 0; i + 1 < b.length; i += 2) text += String.fromCharCode(enc === 'utf16le' ? b[i]! | (b[i + 1]! << 8) : (b[i]! << 8) | b[i + 1]!)
|
|
||||||
return { ok: true, value: text, ...(b.length % 2 ? { note: 'The last byte is half a character' } : {}) }
|
|
||||||
}
|
|
||||||
case 'utf32be': {
|
|
||||||
let text = ''
|
|
||||||
let bad = false
|
|
||||||
for (let i = 0; i + 3 < b.length; i += 4) {
|
|
||||||
const c = ((b[i]! << 24) | (b[i + 1]! << 16) | (b[i + 2]! << 8) | b[i + 3]!) >>> 0
|
|
||||||
if (c > 0x10ffff || (c >= 0xd800 && c <= 0xdfff)) {
|
|
||||||
bad = true
|
|
||||||
text += '<27>'
|
|
||||||
} else text += String.fromCodePoint(c)
|
|
||||||
}
|
|
||||||
return { ok: true, value: text, ...(bad || b.length % 4 ? { note: 'Some bytes are not whole UTF-32 characters' } : {}) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Words ⇄ bytes ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
/** Bytes as words; a last word short of bytes is filled with zeros. */
|
|
||||||
export function toWords(b: Uint8Array, o: Pick<ConvertOptions, 'word' | 'endian'>): number[] {
|
|
||||||
const n = o.word / 8
|
|
||||||
const out: number[] = []
|
|
||||||
for (let i = 0; i < b.length; i += n) {
|
|
||||||
let v = 0
|
|
||||||
for (let k = 0; k < n; k++) {
|
|
||||||
const byte = b[i + k] ?? 0
|
|
||||||
v += byte * 2 ** (8 * (o.endian === 'big' ? n - 1 - k : k))
|
|
||||||
}
|
|
||||||
out.push(v)
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
export function fromWords(words: number[], o: Pick<ConvertOptions, 'word' | 'endian'>): Uint8Array {
|
|
||||||
const n = o.word / 8
|
|
||||||
const out = new Uint8Array(words.length * n)
|
|
||||||
words.forEach((v, i) => {
|
|
||||||
for (let k = 0; k < n; k++) {
|
|
||||||
const byte = Math.floor(v / 2 ** (8 * k)) & 0xff
|
|
||||||
out[i * n + (o.endian === 'big' ? n - 1 - k : k)] = byte
|
|
||||||
}
|
|
||||||
})
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Number formats ───────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const RADIX: Record<'hex' | 'bin' | 'dec' | 'oct', number> = { hex: 16, bin: 2, dec: 10, oct: 8 }
|
|
||||||
const DIGITS: Record<'hex' | 'bin' | 'dec' | 'oct', RegExp> = { hex: /^[0-9a-f]+$/i, bin: /^[01]+$/, dec: /^\d+$/, oct: /^[0-7]+$/ }
|
|
||||||
|
|
||||||
/** Digits one word takes in a format with a fixed width (hex and binary). */
|
|
||||||
const wordDigits = (fmt: 'hex' | 'bin', word: WordBits) => (fmt === 'hex' ? word / 4 : word)
|
|
||||||
|
|
||||||
/** Words written in a number format: separated by spaces, commas or new lines; 0x, 0b, 0o prefixes are fine. A long hex or binary run is several words. */
|
|
||||||
export function parseWords(input: string, fmt: 'hex' | 'bin' | 'dec' | 'oct', word: WordBits): Result<number[]> {
|
|
||||||
const out: number[] = []
|
|
||||||
const max = 2 ** word
|
|
||||||
for (const raw of input.split(/[\s,;]+/).filter(Boolean)) {
|
|
||||||
const t = raw.replace(fmt === 'hex' ? /^(0x|\$|#)|h$/gi : fmt === 'bin' ? /^0b|b$/gi : fmt === 'oct' ? /^0o/i : /^$/, '').replace(/_/g, '')
|
|
||||||
if (!DIGITS[fmt].test(t)) return { ok: false, error: `"${raw}" is not ${fmt === 'hex' ? 'hex' : fmt === 'bin' ? 'binary' : fmt === 'dec' ? 'a decimal number' : 'octal'}` }
|
|
||||||
if ((fmt === 'hex' || fmt === 'bin') && t.length > wordDigits(fmt, word)) {
|
|
||||||
const d = wordDigits(fmt, word)
|
|
||||||
if (t.length % d) return { ok: false, error: `"${raw}" is ${t.length} digits: not a whole number of ${word}-bit words (${d} digits each)` }
|
|
||||||
for (let i = 0; i < t.length; i += d) out.push(parseInt(t.slice(i, i + d), RADIX[fmt]))
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const v = parseInt(t, RADIX[fmt])
|
|
||||||
if (v >= max) return { ok: false, error: `"${raw}" does not fit in ${word} bits (up to ${max - 1})` }
|
|
||||||
out.push(v)
|
|
||||||
}
|
|
||||||
return { ok: true, value: out }
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatWords(words: number[], fmt: 'hex' | 'bin' | 'dec' | 'oct', word: WordBits): string {
|
|
||||||
return words
|
|
||||||
.map(v => {
|
|
||||||
const s = v.toString(RADIX[fmt])
|
|
||||||
return fmt === 'hex' ? s.toUpperCase().padStart(word / 4, '0') : fmt === 'bin' ? s.padStart(word, '0') : s
|
|
||||||
})
|
|
||||||
.join(' ')
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Base64 ───────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export function toBase64(b: Uint8Array): string {
|
|
||||||
let s = ''
|
|
||||||
for (const x of b) s += String.fromCharCode(x)
|
|
||||||
return btoa(s)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function fromBase64(input: string): Result<Uint8Array> {
|
|
||||||
const t = input.replace(/\s+/g, '').replace(/-/g, '+').replace(/_/g, '/')
|
|
||||||
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(t)) return { ok: false, error: 'Not Base64 (A–Z, a–z, 0–9, +, / and = at the end)' }
|
|
||||||
try {
|
|
||||||
const s = atob(t.padEnd(Math.ceil(t.length / 4) * 4, '='))
|
|
||||||
return { ok: true, value: Uint8Array.from(s, c => c.charCodeAt(0)) }
|
|
||||||
} catch {
|
|
||||||
return { ok: false, error: 'Not Base64' }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Any format ⇄ bytes ───────────────────────────────────────────────
|
|
||||||
|
|
||||||
export function parseAs(input: string, fmt: Format, o: ConvertOptions): Result<Uint8Array> {
|
|
||||||
if (fmt === 'text') return encodeText(input, o.enc)
|
|
||||||
if (fmt === 'base64') return fromBase64(input)
|
|
||||||
const w = parseWords(input, fmt, o.word)
|
|
||||||
return w.ok ? { ok: true, value: fromWords(w.value, o) } : w
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatAs(b: Uint8Array, fmt: Format, o: ConvertOptions): Result<string> {
|
|
||||||
if (fmt === 'text') return decodeText(b, o.enc)
|
|
||||||
if (fmt === 'base64') return { ok: true, value: toBase64(b) }
|
|
||||||
const note = b.length % (o.word / 8) ? `The last word is filled up with zero bytes` : undefined
|
|
||||||
return { ok: true, value: formatWords(toWords(b, o), fmt, o.word), ...(note ? { note } : {}) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A word as a signed number (two's complement). */
|
|
||||||
export const signed = (v: number, word: WordBits) => (v >= 2 ** (word - 1) ? v - 2 ** word : v)
|
|
||||||
|
|
||||||
/** How a byte or character shows in a table: control characters by name. */
|
|
||||||
export function charLabel(code: number): string {
|
|
||||||
const NAMES: Record<number, string> = { 0: 'NUL', 7: 'BEL', 8: 'BS', 9: 'TAB', 10: 'LF', 13: 'CR', 27: 'ESC', 32: 'space', 127: 'DEL' }
|
|
||||||
if (NAMES[code]) return NAMES[code]!
|
|
||||||
if (code < 32 || (code >= 0x80 && code < 0xa0)) return `^${code.toString(16).toUpperCase().padStart(2, '0')}`
|
|
||||||
if (code >= 0xd800 && code <= 0xdfff) return '·'
|
|
||||||
return code <= 0x10ffff ? String.fromCodePoint(code) : '·'
|
|
||||||
}
|
|
||||||
|
|
@ -102,47 +102,35 @@ export function sevenSegment(value: number) {
|
||||||
return segs.map((s, i) => ({ d: `M${s[0]} ${s[1]}L${s[2]} ${s[3]}`, on: (bits >> i) & 1 }))
|
return segs.map((s, i) => ({ d: `M${s[0]} ${s[1]}L${s[2]} ${s[3]}`, on: (bits >> i) & 1 }))
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A hop on one segment: from lo to hi along it (grid units), r pixels high. */
|
const HOP = 5
|
||||||
export interface HopSpan {
|
|
||||||
lo: number
|
|
||||||
hi: number
|
|
||||||
r: number
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* SVG path for a wire (points in grid units), with hops where it jumps over
|
* SVG path for a wire (points in grid units), with a hop drawn on its
|
||||||
* other lines (`hops`: segment index to the stretches it jumps). Horizontal
|
* horizontal segments wherever another signal crosses (`hops`: segment
|
||||||
* segments jump upwards, vertical ones to the left. `scale` is pixels per
|
* index to crossing x positions). `scale` is pixels per grid unit.
|
||||||
* grid unit.
|
|
||||||
*/
|
*/
|
||||||
export function wirePath(pts: Pt[], hops: Map<number, HopSpan[]> | undefined, style: CrossingStyle, scale = G): string {
|
export function wirePath(pts: Pt[], hops: Map<number, number[]> | undefined, style: CrossingStyle, scale = G): string {
|
||||||
|
const r = HOP
|
||||||
let d = `M${pts[0]![0] * scale} ${pts[0]![1] * scale}`
|
let d = `M${pts[0]![0] * scale} ${pts[0]![1] * scale}`
|
||||||
for (let i = 0; i < pts.length - 1; i++) {
|
for (let i = 0; i < pts.length - 1; i++) {
|
||||||
const [ax, ay] = pts[i]!
|
const [ax, ay] = pts[i]!
|
||||||
const [bx, by] = pts[i + 1]!
|
const [bx, by] = pts[i + 1]!
|
||||||
const spans = hops?.get(i)
|
const xs = hops?.get(i)
|
||||||
if (spans?.length && style !== 'plain' && (ay === by || ax === bx)) {
|
if (xs && style !== 'plain' && ay === by) {
|
||||||
const horizontal = ay === by
|
const dir = Math.sign(bx - ax)
|
||||||
const from = (horizontal ? ax : ay) * scale
|
const y = ay * scale
|
||||||
const to = (horizontal ? bx : by) * scale
|
let prev = ax * scale
|
||||||
const dir = Math.sign(to - from)
|
for (const hx of xs.map(x => x * scale).sort((p, q) => dir * (p - q))) {
|
||||||
const c = (horizontal ? ay : ax) * scale
|
// Skip hops too close to a corner or to the previous hop.
|
||||||
// A point at `t` along the segment, `off` pixels out to the side the hop bulges.
|
if (Math.abs(hx - prev) < r + 1 || Math.abs(bx * scale - hx) < r + 1) continue
|
||||||
const at = (t: number, off = 0) => (horizontal ? `${t} ${c - off}` : `${c - off} ${t}`)
|
const s = hx - dir * r
|
||||||
const list = spans.map(h => ({ s: (dir > 0 ? h.lo : h.hi) * scale, e: (dir > 0 ? h.hi : h.lo) * scale, r: h.r })).sort((p, q) => dir * (p.s - q.s))
|
const e = hx + dir * r
|
||||||
for (const { s, e, r } of list) {
|
d += `L${s} ${y}`
|
||||||
const half = Math.abs(e - s) / 2
|
if (style === 'bow') d += `A${r} ${r} 0 0 ${dir > 0 ? 1 : 0} ${e} ${y}`
|
||||||
d += `L${at(s)}`
|
else if (style === 'triangle') d += `L${hx} ${y - r * 1.3}L${e} ${y}`
|
||||||
if (style === 'bow') {
|
else if (style === 'bridge') d += `L${s} ${y - r}L${e} ${y - r}L${e} ${y}`
|
||||||
// Up for a horizontal segment, to the left for a vertical one.
|
else d += `M${e} ${y}`
|
||||||
const sweep = horizontal ? (dir > 0 ? 1 : 0) : dir > 0 ? 0 : 1
|
prev = e
|
||||||
d += `A${half} ${r} 0 0 ${sweep} ${at(e)}`
|
|
||||||
} else if (style === 'triangle') {
|
|
||||||
const lift = r * 1.3
|
|
||||||
if (half <= r * 1.2) d += `L${at((s + e) / 2, lift)}L${at(e)}`
|
|
||||||
else d += `L${at(s + dir * r, lift)}L${at(e - dir * r, lift)}L${at(e)}`
|
|
||||||
} else if (style === 'bridge') d += `L${at(s, r)}L${at(e, r)}L${at(e)}`
|
|
||||||
else d += `M${at(e)}`
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
d += `L${bx * scale} ${by * scale}`
|
d += `L${bx * scale} ${by * scale}`
|
||||||
|
|
|
||||||
|
|
@ -1,301 +0,0 @@
|
||||||
// Test benches: a part with a table of tests. Its drive columns are output
|
|
||||||
// pins it sets, its check columns input pins it reads; wire them to whatever
|
|
||||||
// is tested. Each row sets the drive columns, gives the circuit clock ticks
|
|
||||||
// if asked, and checks what comes back. A run takes the whole circuit the
|
|
||||||
// bench is in on its own, from all zeros (switches as they are), so it never
|
|
||||||
// disturbs the circuit running; what the circuit holds carries from row to
|
|
||||||
// row, so a row can test memory, a counter, or a computer running a program.
|
|
||||||
//
|
|
||||||
// A drive cell is a number (12, 0x0C, 0b1100), P for a clock pulse, or empty
|
|
||||||
// to leave it as it was. A check cell is the number it should read, empty
|
|
||||||
// for any. Ticks: N pulses (the P columns and the circuit's own clocks)
|
|
||||||
// before the check; ≤N gives up to N, checking after each, until it matches.
|
|
||||||
|
|
||||||
import { compile, rowSource } from './compile'
|
|
||||||
import { colKeys, colPinNames } from './benchLayout'
|
|
||||||
import { chipPins, type DefLookup } from './geometry'
|
|
||||||
import { uid } from './ops'
|
|
||||||
import { Simulator } from './sim'
|
|
||||||
import type { Bench, BenchCol, BenchRow, CircuitNode, ComponentDef } from './types'
|
|
||||||
|
|
||||||
export interface RowResult {
|
|
||||||
/** True all checks hold, false one does not, null nothing to check. */
|
|
||||||
ok: boolean | null
|
|
||||||
/** What the check columns read after the row, by column id. */
|
|
||||||
got: Record<string, number>
|
|
||||||
/** Ticks the row ran. */
|
|
||||||
ticks: number
|
|
||||||
error?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface BenchResult {
|
|
||||||
rows: RowResult[]
|
|
||||||
pass: number
|
|
||||||
fail: number
|
|
||||||
error?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
const SETTLE = 2_000_000
|
|
||||||
/** Ticks a run gives in all, at most (a run after an edit stays short; by hand it may go longer). */
|
|
||||||
export const AUTO_TICKS = 20_000
|
|
||||||
export const HAND_TICKS = 500_000
|
|
||||||
/** "Every combination" makes rows for this many drive bits at most. */
|
|
||||||
export const MAX_COMBO_BITS = 10
|
|
||||||
|
|
||||||
export { colKeys, colPinNames }
|
|
||||||
|
|
||||||
export const driveCols = (b: Bench | undefined) => (b?.cols ?? []).filter(c => c.dir === 'drive')
|
|
||||||
export const checkCols = (b: Bench | undefined) => (b?.cols ?? []).filter(c => c.dir === 'check')
|
|
||||||
|
|
||||||
/** A cell as a number, P (drive columns only), or null when empty or a don't-care. */
|
|
||||||
export function parseCell(s: string | undefined, bits: number, drive: boolean): number | 'P' | null | { error: string } {
|
|
||||||
const t = (s ?? '').trim()
|
|
||||||
if (!t || t === '-' || t.toLowerCase() === 'x') return null
|
|
||||||
if (drive && /^(p|↑)$/i.test(t)) return 'P'
|
|
||||||
let v: number
|
|
||||||
if (/^\d+$/.test(t)) v = parseInt(t, 10)
|
|
||||||
else if (/^0x[0-9a-f]+$/i.test(t)) v = parseInt(t.slice(2), 16)
|
|
||||||
else if (/^0b[01]+$/i.test(t)) v = parseInt(t.slice(2), 2)
|
|
||||||
else if (/^-\d+$/.test(t)) v = 2 ** bits + parseInt(t, 10)
|
|
||||||
else return { error: `"${t}" is not a number${drive ? ' or P' : ''}` }
|
|
||||||
if (v < 0 || v >= 2 ** bits) return { error: `${t} does not fit in ${bits} bit${bits === 1 ? '' : 's'}` }
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Ticks of a row: N, or ≤N (also <=N) to wait for the checks. Empty: one pulse when the row has a P, else none. */
|
|
||||||
export function parseTicks(s: string | undefined): { n: number; wait: boolean } | null | { error: string } {
|
|
||||||
const t = (s ?? '').trim()
|
|
||||||
if (!t) return null
|
|
||||||
const m = /^(≤|<=|<|max\s*|up\s*to\s*)?\s*(\d+)$/i.exec(t)
|
|
||||||
if (!m) return { error: `Ticks "${t}": a number, or ≤ and a number` }
|
|
||||||
const n = parseInt(m[2]!, 10)
|
|
||||||
if (n > HAND_TICKS) return { error: `Ticks: at most ${HAND_TICKS}` }
|
|
||||||
return { n, wait: !!m[1] }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Sets the circuit's own switches the way they stand (buttons up, keyboards empty). */
|
|
||||||
export function setSwitches(sim: Simulator, def: ComponentDef) {
|
|
||||||
for (const n of def.nodes) {
|
|
||||||
if (n.kind === 'input') sim.setSource(n.id, !!n.on)
|
|
||||||
else if (n.kind === 'panel') for (const r of n.rows ?? []) if (r.type === 'switch') sim.setSource(rowSource(n.id, r.id), !!r.on)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Runs a bench's rows on the circuit it is in. */
|
|
||||||
export function runBench(getDef: DefLookup, circuitId: string, benchId: string, maxTicks = AUTO_TICKS): BenchResult {
|
|
||||||
const def = getDef(circuitId)
|
|
||||||
const bench = def?.nodes.find(n => n.id === benchId)?.bench
|
|
||||||
const res: BenchResult = { rows: [], pass: 0, fail: 0 }
|
|
||||||
if (!def || !bench) return { ...res, error: 'The bench is gone' }
|
|
||||||
const drives = driveCols(bench)
|
|
||||||
const checks = checkCols(bench)
|
|
||||||
if (!drives.length && !checks.length) return { ...res, error: 'No columns yet' }
|
|
||||||
const sim = new Simulator(compile(getDef, circuitId))
|
|
||||||
setSwitches(sim, def)
|
|
||||||
sim.run(SETTLE)
|
|
||||||
const clocks = sim.nl.clocks.length > 0
|
|
||||||
let left = maxTicks
|
|
||||||
const put = (c: BenchCol, v: number) => colKeys(c).forEach((k, i) => sim.setSource(`${benchId}:${k}`, Math.floor(v / 2 ** i) % 2 === 1))
|
|
||||||
const read = (c: BenchCol) => colKeys(c).reduce((v, k, i) => v + (sim.pin(benchId, k) ? 2 ** i : 0), 0)
|
|
||||||
for (const row of bench.rows) {
|
|
||||||
const out: RowResult = { ok: null, got: {}, ticks: 0 }
|
|
||||||
res.rows.push(out)
|
|
||||||
const fail = (error: string) => {
|
|
||||||
out.ok = false
|
|
||||||
out.error = error
|
|
||||||
res.fail++
|
|
||||||
}
|
|
||||||
// Drive columns; pulses held low for now.
|
|
||||||
const pulses: BenchCol[] = []
|
|
||||||
let bad = ''
|
|
||||||
for (const c of drives) {
|
|
||||||
const v = parseCell(row.set?.[c.id], c.bits, true)
|
|
||||||
if (v && typeof v === 'object') bad ||= `${c.name}: ${v.error}`
|
|
||||||
else if (v === 'P') {
|
|
||||||
pulses.push(c)
|
|
||||||
put(c, 0)
|
|
||||||
} else if (v !== null) put(c, v)
|
|
||||||
}
|
|
||||||
const want: { c: BenchCol; v: number }[] = []
|
|
||||||
for (const c of checks) {
|
|
||||||
const v = parseCell(row.expect?.[c.id], c.bits, false)
|
|
||||||
if (v && typeof v === 'object') bad ||= `${c.name}: ${v.error}`
|
|
||||||
else if (typeof v === 'number') want.push({ c, v })
|
|
||||||
}
|
|
||||||
const ticks = parseTicks(row.ticks)
|
|
||||||
if (ticks && 'error' in ticks) bad ||= ticks.error
|
|
||||||
if (bad) {
|
|
||||||
fail(bad)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const spec = (ticks as { n: number; wait: boolean } | null) ?? { n: pulses.length ? 1 : 0, wait: false }
|
|
||||||
if (spec.n && !pulses.length && !clocks) {
|
|
||||||
fail('Ticks, but nothing to tick: a column with P, or a clock in the circuit')
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if (!sim.run(SETTLE)) {
|
|
||||||
fail('It oscillates and never settles')
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const matches = () => want.every(({ c, v }) => read(c) === v)
|
|
||||||
const tick = (): boolean => {
|
|
||||||
for (const c of pulses) put(c, 2 ** c.bits - 1)
|
|
||||||
if (clocks) sim.setClock(1)
|
|
||||||
if (!sim.run(SETTLE)) return false
|
|
||||||
for (const c of pulses) put(c, 0)
|
|
||||||
if (clocks) sim.setClock(0)
|
|
||||||
return sim.run(SETTLE)
|
|
||||||
}
|
|
||||||
let stopped = ''
|
|
||||||
for (let t = 0; t < spec.n; t++) {
|
|
||||||
if (spec.wait && want.length && matches()) break
|
|
||||||
if (left-- <= 0) {
|
|
||||||
stopped = `Stopped after ${maxTicks.toLocaleString('en')} ticks in all`
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if (!tick()) {
|
|
||||||
stopped = 'It oscillates and never settles'
|
|
||||||
break
|
|
||||||
}
|
|
||||||
out.ticks++
|
|
||||||
}
|
|
||||||
for (const c of checks) out.got[c.id] = read(c)
|
|
||||||
if (stopped) {
|
|
||||||
fail(stopped)
|
|
||||||
if (left <= 0) {
|
|
||||||
res.error = stopped
|
|
||||||
break
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if (!want.length) continue
|
|
||||||
out.ok = matches()
|
|
||||||
if (out.ok) res.pass++
|
|
||||||
else {
|
|
||||||
res.fail++
|
|
||||||
if (spec.wait) out.error = `Not within ${spec.n} ticks`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Every combination of the drive columns, counting up (the first column the highest). */
|
|
||||||
export function combinationRows(bench: Bench): BenchRow[] | { error: string } {
|
|
||||||
const drives = driveCols(bench)
|
|
||||||
const bits = drives.reduce((n, c) => n + c.bits, 0)
|
|
||||||
if (!drives.length) return { error: 'Add a drive column first' }
|
|
||||||
if (bits > MAX_COMBO_BITS) return { error: `${bits} drive bits are ${2 ** bits} combinations: at most ${MAX_COMBO_BITS} bits` }
|
|
||||||
const rows: BenchRow[] = []
|
|
||||||
for (let i = 0; i < 2 ** bits; i++) {
|
|
||||||
let rest = i
|
|
||||||
const set: Record<string, string> = {}
|
|
||||||
for (let k = drives.length - 1; k >= 0; k--) {
|
|
||||||
const c = drives[k]!
|
|
||||||
set[c.id] = String(rest % 2 ** c.bits)
|
|
||||||
rest = Math.floor(rest / 2 ** c.bits)
|
|
||||||
}
|
|
||||||
rows.push({ set })
|
|
||||||
}
|
|
||||||
return rows
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The rows with what the circuit reads now in their empty check cells (to
|
|
||||||
* keep it working the same). Cells already filled in stay, so a row that
|
|
||||||
* waits for them waits the same.
|
|
||||||
*/
|
|
||||||
export function recordExpected(r: BenchResult, rows: BenchRow[]): BenchRow[] {
|
|
||||||
return rows.map((row, i) => {
|
|
||||||
const res = r.rows[i]
|
|
||||||
if (!res || (res.error && res.ok !== false)) return row
|
|
||||||
const expect = { ...row.expect }
|
|
||||||
for (const [k, v] of Object.entries(res.got)) if (!expect[k]?.trim()) expect[k] = String(v)
|
|
||||||
return { ...row, expect }
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Columns for a component ──────────────────────────────────────────
|
|
||||||
|
|
||||||
const SERIES = /^(.*?)(\d+)$/
|
|
||||||
|
|
||||||
/** Pins as groups: A0…An (numbered from 0, none missing) make one group A; any other pin is its own. Keys bit 0 first. */
|
|
||||||
export function groupPins(pins: { key: string; label: string }[]): { name: string; keys: string[] }[] {
|
|
||||||
const series = new Map<string, Map<number, string>>()
|
|
||||||
for (const p of pins) {
|
|
||||||
const m = SERIES.exec(p.label.trim())
|
|
||||||
if (!m || !m[1]) continue
|
|
||||||
const s = series.get(m[1]) ?? new Map<number, string>()
|
|
||||||
s.set(Number(m[2]), p.key)
|
|
||||||
series.set(m[1], s)
|
|
||||||
}
|
|
||||||
const whole = new Set([...series.entries()].filter(([, s]) => s.size >= 2 && [...s.keys()].every(i => i < s.size)).map(([name]) => name))
|
|
||||||
const out: { name: string; keys: string[] }[] = []
|
|
||||||
const done = new Set<string>()
|
|
||||||
for (const p of pins) {
|
|
||||||
const name = SERIES.exec(p.label.trim())?.[1]
|
|
||||||
if (name && whole.has(name)) {
|
|
||||||
if (done.has(name)) continue
|
|
||||||
done.add(name)
|
|
||||||
const s = series.get(name)!
|
|
||||||
out.push({ name, keys: [...s.keys()].sort((a, b) => a - b).map(i => s.get(i)!) })
|
|
||||||
} else out.push({ name: p.label.trim() || p.key, keys: [p.key] })
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sets a bench up for a placed component: a drive column per input group, a
|
|
||||||
* check column per output group, wired to them (inputs already wired from
|
|
||||||
* elsewhere stay as they are). Rows keyed by group name are moved to the
|
|
||||||
* new columns. Returns the wires to add.
|
|
||||||
*/
|
|
||||||
export function benchFor(def: ComponentDef, bench: CircuitNode, chip: CircuitNode, chipDef: ComponentDef): { from: { node: string; pin: string }; to: { node: string; pin: string } }[] {
|
|
||||||
const pins = chipPins(chipDef)
|
|
||||||
const ins = groupPins(pins.inputs)
|
|
||||||
const outs = groupPins(pins.outputs)
|
|
||||||
const cols: BenchCol[] = [
|
|
||||||
...ins.map(g => ({ id: uid('c'), name: g.name, bits: g.keys.length, dir: 'drive' as const })),
|
|
||||||
...outs.map(g => ({ id: uid('c'), name: g.name, bits: g.keys.length, dir: 'check' as const })),
|
|
||||||
]
|
|
||||||
const byName = new Map(cols.map(c => [`${c.dir}:${c.name}`, c.id]))
|
|
||||||
const remap = (cells: Record<string, string> | undefined, dir: BenchCol['dir']) => {
|
|
||||||
if (!cells) return undefined
|
|
||||||
const out = Object.fromEntries(Object.entries(cells).map(([k, v]) => [byName.get(`${dir}:${k}`) ?? k, v]))
|
|
||||||
return Object.keys(out).length ? out : undefined
|
|
||||||
}
|
|
||||||
const rows = (bench.bench?.rows ?? []).map(r => {
|
|
||||||
const set = remap(r.set, 'drive')
|
|
||||||
const expect = remap(r.expect, 'check')
|
|
||||||
return { ...(set ? { set } : {}), ...(expect ? { expect } : {}), ...(r.ticks ? { ticks: r.ticks } : {}) }
|
|
||||||
})
|
|
||||||
bench.bench = { cols, rows }
|
|
||||||
const fed = new Set(def.wires.filter(w => w.to.node === chip.id).map(w => w.to.pin))
|
|
||||||
const wires: { from: { node: string; pin: string }; to: { node: string; pin: string } }[] = []
|
|
||||||
ins.forEach((g, gi) => {
|
|
||||||
const keys = colKeys(cols[gi]!)
|
|
||||||
g.keys.forEach((k, i) => !fed.has(k) && wires.push({ from: { node: bench.id, pin: keys[i]! }, to: { node: chip.id, pin: k } }))
|
|
||||||
})
|
|
||||||
outs.forEach((g, gi) => {
|
|
||||||
const keys = colKeys(cols[ins.length + gi]!)
|
|
||||||
g.keys.forEach((k, i) => wires.push({ from: { node: chip.id, pin: k }, to: { node: bench.id, pin: keys[i]! } }))
|
|
||||||
})
|
|
||||||
return wires
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Benches saved by the first version (docked to a component, no pins): columns and wires to that component instead. */
|
|
||||||
export function upgradeBenches(def: ComponentDef, getDef: DefLookup) {
|
|
||||||
for (const n of def.nodes) {
|
|
||||||
const on = n.kind === 'bench' ? n.bench?.on : undefined
|
|
||||||
if (!n.bench || n.bench.cols || !on) {
|
|
||||||
if (n.bench?.on) delete n.bench.on
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const chip = def.nodes.find(x => x.id === on)
|
|
||||||
const chipDef = chip?.kind === 'chip' && chip.chip ? getDef(chip.chip) : undefined
|
|
||||||
if (!chip || !chipDef) {
|
|
||||||
n.bench = { cols: [], rows: [] }
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
for (const w of benchFor(def, n, chip, chipDef)) def.wires.push({ id: uid('w'), ...w })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,75 +0,0 @@
|
||||||
// Where everything on a test bench's box goes: check pins down the left,
|
|
||||||
// drive pins down the right, the title bar with its run button, and the
|
|
||||||
// table between them. The shape (pins) and the drawing both use this.
|
|
||||||
|
|
||||||
import type { BenchCol, CircuitNode } from './types'
|
|
||||||
|
|
||||||
/** Pin keys of a column, bit 0 first. */
|
|
||||||
export const colKeys = (c: Pick<BenchCol, 'id' | 'bits'>) => Array.from({ length: c.bits }, (_, i) => `${c.id}.${i}`)
|
|
||||||
|
|
||||||
/** A column's pin names: its name, numbered when it has several bits. */
|
|
||||||
export const colPinNames = (c: Pick<BenchCol, 'name' | 'bits'>) => (c.bits === 1 ? [c.name] : Array.from({ length: c.bits }, (_, i) => `${c.name}${i}`))
|
|
||||||
|
|
||||||
/** Rows the box shows; more are in the dialog. */
|
|
||||||
export const BENCH_ROWS_SHOWN = 24
|
|
||||||
const CHAR = 0.4 // grid units per character at the table's size
|
|
||||||
const TITLE_H = 1.4
|
|
||||||
|
|
||||||
export interface BenchCell {
|
|
||||||
key: string
|
|
||||||
/** Column id, '#' for the row number, 'ticks', or 'state'. */
|
|
||||||
col: string
|
|
||||||
x: number
|
|
||||||
w: number
|
|
||||||
head: string
|
|
||||||
drive?: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface BenchLayout {
|
|
||||||
w: number
|
|
||||||
h: number
|
|
||||||
/** Pin rows on each side: key and name. */
|
|
||||||
left: { key: string; label: string }[]
|
|
||||||
right: { key: string; label: string }[]
|
|
||||||
/** Table: left edge, top of the header row, its columns, rows shown, rows not shown. */
|
|
||||||
x: number
|
|
||||||
top: number
|
|
||||||
cols: BenchCell[]
|
|
||||||
shown: number
|
|
||||||
more: number
|
|
||||||
tableW: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export function benchLayout(node: CircuitNode): BenchLayout {
|
|
||||||
const b = node.bench
|
|
||||||
const cols = b?.cols ?? []
|
|
||||||
const rows = b?.rows ?? []
|
|
||||||
const checks = cols.filter(c => c.dir === 'check')
|
|
||||||
const drives = cols.filter(c => c.dir === 'drive')
|
|
||||||
const left = checks.flatMap(c => colKeys(c).map((key, i) => ({ key, label: colPinNames(c)[i]! })))
|
|
||||||
const right = drives.flatMap(c => colKeys(c).map((key, i) => ({ key, label: colPinNames(c)[i]! })))
|
|
||||||
const labelW = (list: { label: string }[]) => (list.length ? Math.max(...list.map(p => p.label.length)) * CHAR + 0.7 : 0.3)
|
|
||||||
const lw = labelW(left)
|
|
||||||
const rw = labelW(right)
|
|
||||||
const shown = Math.min(rows.length, BENCH_ROWS_SHOWN)
|
|
||||||
const width = (head: string, cells: string[]) => Math.max(head.length, 1, ...cells.slice(0, shown).map(s => s.length)) * CHAR + 0.6
|
|
||||||
const table: Omit<BenchCell, 'x'>[] = [{ key: '#', col: '#', w: width('#', [String(shown)]), head: '#' }]
|
|
||||||
for (const c of [...drives, ...checks]) {
|
|
||||||
const cells = rows.map(r => (c.dir === 'drive' ? r.set?.[c.id] : r.expect?.[c.id]) ?? '')
|
|
||||||
table.push({ key: c.id, col: c.id, w: width(c.name, cells), head: c.name, drive: c.dir === 'drive' })
|
|
||||||
}
|
|
||||||
if (rows.some(r => r.ticks)) table.push({ key: 'ticks', col: 'ticks', w: width('Ticks', rows.map(r => r.ticks ?? '')), head: 'Ticks' })
|
|
||||||
table.push({ key: 'state', col: 'state', w: 1, head: '' })
|
|
||||||
let x = lw + 0.2
|
|
||||||
const placed = table.map(c => {
|
|
||||||
const out = { ...c, x }
|
|
||||||
x += c.w
|
|
||||||
return out
|
|
||||||
})
|
|
||||||
const tableW = x - lw - 0.2
|
|
||||||
const w = Math.ceil(Math.max(lw + 0.2 + Math.max(tableW, 9) + 0.2 + rw, 10))
|
|
||||||
const more = rows.length - shown
|
|
||||||
const tableH = cols.length ? 1 + shown + (more ? 1 : 0) : 1.2
|
|
||||||
const h = Math.ceil(Math.max(left.length, right.length, TITLE_H + tableH + 0.4))
|
|
||||||
return { w, h, left, right, x: lw + 0.2, top: -0.5 + TITLE_H, cols: placed, shown, more, tableW }
|
|
||||||
}
|
|
||||||
|
|
@ -248,20 +248,7 @@ function syncNames(def: ComponentDef, nodes: Map<string, CircuitNode>, get: DefL
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// A split with no bundle behind it (a plug waiting for its cable) is named after what its wires drive.
|
for (const n of def.nodes) if (n.kind === 'split' && !named.has(n.id)) delete n.names
|
||||||
for (const n of def.nodes) {
|
|
||||||
if (n.kind !== 'split' || named.has(n.id)) continue
|
|
||||||
const names = Array.from({ length: cableBits(n) }, (_, i) => {
|
|
||||||
for (const w of def.wires) {
|
|
||||||
if (w.from.node !== n.id || w.from.pin !== `b${i}`) continue
|
|
||||||
const t = nodes.get(w.to.node)
|
|
||||||
const name = t ? targetName(t, w.to.pin, get) : ''
|
|
||||||
if (name) return name
|
|
||||||
}
|
|
||||||
return ''
|
|
||||||
})
|
|
||||||
setNames(n, names)
|
|
||||||
}
|
|
||||||
// Rows of a free panel that feed a cable show the wire's name until they get their own.
|
// Rows of a free panel that feed a cable show the wire's name until they get their own.
|
||||||
for (const w of def.wires) {
|
for (const w of def.wires) {
|
||||||
const b = nodes.get(w.to.node)
|
const b = nodes.get(w.to.node)
|
||||||
|
|
@ -491,129 +478,64 @@ export function pinGroups(pins: { key: string; label: string }[], usable: (key:
|
||||||
return out.filter(g => g.pins.length <= MAX_BITS)
|
return out.filter(g => g.pins.length <= MAX_BITS)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The first spot along the row from `x` (by `step`) where a cable end of `h` rows fits. */
|
||||||
|
function clearSpot(def: ComponentDef, get: DefLookup, x: number, y: number, h: number, step: 1 | -1): number {
|
||||||
|
const boxes = def.nodes.map(n => {
|
||||||
|
const b = shapeOf(n, get).body
|
||||||
|
return { x: n.x + b.x, y: n.y + b.y, w: b.w, h: b.h }
|
||||||
|
})
|
||||||
|
for (let i = 0; i < 20; i++) {
|
||||||
|
const cx = x + i * step
|
||||||
|
if (!boxes.some(b => cx - 0.5 < b.x + b.w && cx + 1.5 > b.x && y - 1 < b.y + b.h && y + h > b.y)) return cx
|
||||||
|
}
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A plug on some of a part's outputs (wire 0 the top one): a bundle sitting
|
* A new cable plugged onto some of a part's outputs (wire 0 the top one):
|
||||||
* on the pins, without a cable yet. Pulling the cable out of its pin gives
|
* its bundle sits on the pins, the cable runs a few squares on to a free
|
||||||
* it the other end, where it is dropped.
|
* split carrying their names, ready to be dragged to where they go.
|
||||||
*/
|
*/
|
||||||
export function cableFromPins(def: ComponentDef, partId: string, pins: string[], get: DefLookup): { ok: true; bundle: CircuitNode } | { ok: false; error: string } {
|
export function cableFromPins(def: ComponentDef, partId: string, pins: string[], get: DefLookup): { ok: true; bundle: CircuitNode; split: CircuitNode } | { ok: false; error: string } {
|
||||||
const part = def.nodes.find(n => n.id === partId)
|
const part = def.nodes.find(n => n.id === partId)
|
||||||
if (!part) return { ok: false, error: 'Part not found' }
|
if (!part) return { ok: false, error: 'Part not found' }
|
||||||
// Outputs on the right edge only: a cable end on the left would sit inside the box.
|
const outs = shapeOf(part, get).outputs.filter(p => !p.bus && pins.includes(p.key)).sort((a, b) => a.dy - b.dy)
|
||||||
const outs = shapeOf(part, get).outputs.filter(p => !p.bus && p.face !== -1 && pins.includes(p.key)).sort((a, b) => a.dy - b.dy)
|
|
||||||
if (outs.length < 2) return { ok: false, error: 'A cable needs at least two pins' }
|
if (outs.length < 2) return { ok: false, error: 'A cable needs at least two pins' }
|
||||||
if (outs.length > MAX_BITS) return { ok: false, error: `A cable holds at most ${MAX_BITS} wires` }
|
if (outs.length > MAX_BITS) return { ok: false, error: `A cable holds at most ${MAX_BITS} wires` }
|
||||||
const bundle: CircuitNode = { id: uid('n'), kind: 'bundle', bits: outs.length, x: part.x + outs[0]!.dx, y: part.y + outs[0]!.dy }
|
const bundle: CircuitNode = { id: uid('n'), kind: 'bundle', bits: outs.length, x: part.x + outs[0]!.dx, y: part.y + outs[0]!.dy }
|
||||||
def.nodes.push(bundle)
|
def.nodes.push(bundle)
|
||||||
outs.forEach((p, i) => def.wires.push({ id: uid('w'), from: { node: part.id, pin: p.key }, to: { node: bundle.id, pin: `b${i}` } }))
|
outs.forEach((p, i) => def.wires.push({ id: uid('w'), from: { node: part.id, pin: p.key }, to: { node: bundle.id, pin: `b${i}` } }))
|
||||||
plugInto(def, bundle, part.id, get)
|
plugInto(def, bundle, part.id, get)
|
||||||
return { ok: true, bundle }
|
const mid = Math.floor((outs.length - 1) / 2)
|
||||||
|
const busY = bundle.y + cableOffsets(bundle)[mid]!
|
||||||
|
const split: CircuitNode = { id: uid('n'), kind: 'split', bits: outs.length, x: 0, y: busY - mid }
|
||||||
|
split.x = clearSpot(def, get, bundle.x + 7, split.y, outs.length, 1)
|
||||||
|
def.nodes.push(split)
|
||||||
|
def.wires.push({ id: uid('w'), from: { node: bundle.id, pin: 'q' }, to: { node: split.id, pin: 'a' } })
|
||||||
|
return { ok: true, bundle, split }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A plug on some of a part's free inputs: a split sitting on the pins,
|
* A new cable plugged into some of a part's free inputs: its split sits on
|
||||||
* without a cable yet. Pulling the cable out of its pin gives it the
|
* the pins, the cable comes from a free bundle a few squares back, ready
|
||||||
* other end, where it is dropped (or attach an input panel to it).
|
* to be fed (drag it next to what drives them, or attach a panel to it).
|
||||||
*/
|
*/
|
||||||
export function cableIntoPins(def: ComponentDef, partId: string, pins: string[], get: DefLookup): { ok: true; split: CircuitNode } | { ok: false; error: string } {
|
export function cableIntoPins(def: ComponentDef, partId: string, pins: string[], get: DefLookup): { ok: true; bundle: CircuitNode; split: CircuitNode } | { ok: false; error: string } {
|
||||||
const part = def.nodes.find(n => n.id === partId)
|
const part = def.nodes.find(n => n.id === partId)
|
||||||
if (!part) return { ok: false, error: 'Part not found' }
|
if (!part) return { ok: false, error: 'Part not found' }
|
||||||
const fed = new Set(def.wires.filter(w => w.to.node === part.id).map(w => w.to.pin))
|
const fed = new Set(def.wires.filter(w => w.to.node === part.id).map(w => w.to.pin))
|
||||||
// Inputs on the left edge only: a cable end on the right would sit inside the box.
|
const ins = shapeOf(part, get).inputs.filter(p => !p.bus && pins.includes(p.key) && !fed.has(p.key)).sort((a, b) => a.dy - b.dy)
|
||||||
const ins = shapeOf(part, get).inputs.filter(p => !p.bus && p.face !== 1 && pins.includes(p.key) && !fed.has(p.key)).sort((a, b) => a.dy - b.dy)
|
|
||||||
if (ins.length < 2) return { ok: false, error: 'A cable needs at least two free inputs' }
|
if (ins.length < 2) return { ok: false, error: 'A cable needs at least two free inputs' }
|
||||||
if (ins.length > MAX_BITS) return { ok: false, error: `A cable holds at most ${MAX_BITS} wires` }
|
if (ins.length > MAX_BITS) return { ok: false, error: `A cable holds at most ${MAX_BITS} wires` }
|
||||||
const split: CircuitNode = { id: uid('n'), kind: 'split', bits: ins.length, x: part.x + ins[0]!.dx - 1, y: part.y + ins[0]!.dy }
|
const split: CircuitNode = { id: uid('n'), kind: 'split', bits: ins.length, x: part.x + ins[0]!.dx - 1, y: part.y + ins[0]!.dy }
|
||||||
def.nodes.push(split)
|
def.nodes.push(split)
|
||||||
ins.forEach((p, i) => def.wires.push({ id: uid('w'), from: { node: split.id, pin: `b${i}` }, to: { node: part.id, pin: p.key } }))
|
ins.forEach((p, i) => def.wires.push({ id: uid('w'), from: { node: split.id, pin: `b${i}` }, to: { node: part.id, pin: p.key } }))
|
||||||
plugInto(def, split, part.id, get)
|
plugInto(def, split, part.id, get)
|
||||||
return { ok: true, split }
|
const mid = Math.floor((ins.length - 1) / 2)
|
||||||
}
|
const busY = split.y + cableOffsets(split)[mid]!
|
||||||
|
const bundle: CircuitNode = { id: uid('n'), kind: 'bundle', bits: ins.length, x: 0, y: busY - mid }
|
||||||
/**
|
bundle.x = clearSpot(def, get, split.x - 8, bundle.y, ins.length, -1)
|
||||||
* The other end of a cable pulled out of a cable end, placed at `x`, `y`:
|
def.nodes.push(bundle)
|
||||||
* out of a bundle a split, out of a split a bundle, with as many wires.
|
|
||||||
* Null when it isn't a cable end, or a split that already has its cable.
|
|
||||||
*/
|
|
||||||
export function cableEnd(def: ComponentDef, endId: string, x: number, y: number): CircuitNode | null {
|
|
||||||
const from = def.nodes.find(n => n.id === endId)
|
|
||||||
if (!from || !CABLE_ENDS.has(from.kind)) return null
|
|
||||||
if (from.kind === 'split' && def.wires.some(w => w.to.node === from.id)) return null
|
|
||||||
const end: CircuitNode = { id: uid('n'), kind: from.kind === 'bundle' ? 'split' : 'bundle', bits: cableBits(from), x, y }
|
|
||||||
def.nodes.push(end)
|
|
||||||
const [bundle, split] = end.kind === 'split' ? [from, end] : [end, from]
|
|
||||||
def.wires.push({ id: uid('w'), from: { node: bundle.id, pin: 'q' }, to: { node: split.id, pin: 'a' } })
|
def.wires.push({ id: uid('w'), from: { node: bundle.id, pin: 'q' }, to: { node: split.id, pin: 'a' } })
|
||||||
return end
|
return { ok: true, bundle, split }
|
||||||
}
|
|
||||||
|
|
||||||
/** The ends of the cable a cable end belongs to (its bundle and every split it feeds), and which of its wires are in use. */
|
|
||||||
function cableUse(def: ComponentDef, endId: string): { ends: CircuitNode[]; before: number; keep: number[] } | null {
|
|
||||||
const end = def.nodes.find(n => n.id === endId && CABLE_ENDS.has(n.kind))
|
|
||||||
if (!end) return null
|
|
||||||
const nodes = new Map(def.nodes.map(n => [n.id, n]))
|
|
||||||
const feed = end.kind === 'split' ? def.wires.find(w => w.to.node === end.id && w.to.pin === 'a') : undefined
|
|
||||||
const fromBundle = feed && nodes.get(feed.from.node)
|
|
||||||
const bundle = end.kind === 'bundle' ? end : fromBundle?.kind === 'bundle' ? fromBundle : undefined
|
|
||||||
const ends = bundle
|
|
||||||
? [bundle, ...def.wires.filter(w => w.from.node === bundle.id).map(w => nodes.get(w.to.node)).filter((n): n is CircuitNode => n?.kind === 'split')]
|
|
||||||
: [end]
|
|
||||||
const before = Math.max(...ends.map(cableBits))
|
|
||||||
const ids = new Set(ends.map(e => e.id))
|
|
||||||
const used = new Set<number>()
|
|
||||||
for (const w of def.wires) {
|
|
||||||
if (ids.has(w.to.node) && nodes.get(w.to.node)!.kind === 'bundle') used.add(wireBit(w.to.pin))
|
|
||||||
if (ids.has(w.from.node) && nodes.get(w.from.node)!.kind === 'split') used.add(wireBit(w.from.pin))
|
|
||||||
}
|
|
||||||
const keep = Array.from({ length: before }, (_, i) => i).filter(i => used.has(i))
|
|
||||||
for (let i = 0; keep.length < 2 && i < before; i++) if (!keep.includes(i)) keep.push(i)
|
|
||||||
keep.sort((a, b) => a - b)
|
|
||||||
return { ends, before, keep }
|
|
||||||
}
|
|
||||||
|
|
||||||
const wireBit = (pin: string) => (/^b\d+$/.test(pin) ? Number(pin.slice(1)) : -1)
|
|
||||||
|
|
||||||
/** How many wires a cable has and how many of them are in use (at least two count). */
|
|
||||||
export function cableInUse(def: ComponentDef, endId: string): { before: number; after: number } | null {
|
|
||||||
const use = cableUse(def, endId)
|
|
||||||
return use ? { before: use.before, after: use.keep.length } : null
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Drops the wires of a cable that carry nothing: fed by nothing at its
|
|
||||||
* bundle and taken by nothing from any of its splits (or, for a lone end,
|
|
||||||
* not wired at all). The rest close up in order with their names, each on
|
|
||||||
* the row it had, so nothing wired to them moves; at least two stay.
|
|
||||||
* Returns the number of wires before and after, or null when all are in use.
|
|
||||||
*/
|
|
||||||
export function trimCable(def: ComponentDef, endId: string): { before: number; after: number } | null {
|
|
||||||
const use = cableUse(def, endId)
|
|
||||||
if (!use || use.keep.length >= use.before) return null
|
|
||||||
const { ends, before, keep } = use
|
|
||||||
const nodes = new Map(def.nodes.map(n => [n.id, n]))
|
|
||||||
const ids = new Set(ends.map(e => e.id))
|
|
||||||
const map = new Map(keep.map((old, k) => [old, k]))
|
|
||||||
for (const e of ends) {
|
|
||||||
const offs = cableOffsets(e)
|
|
||||||
const rows = keep.map(i => offs[i] ?? i)
|
|
||||||
const rel = rows.map(v => v - rows[0]!)
|
|
||||||
e.y += rows[0]!
|
|
||||||
e.bits = keep.length
|
|
||||||
const step = rel[1]!
|
|
||||||
if (step <= 8 && rel.every((v, k) => v === k * step)) {
|
|
||||||
if (step === 1) delete e.pitch
|
|
||||||
else e.pitch = step
|
|
||||||
delete e.offsets
|
|
||||||
} else e.offsets = rel
|
|
||||||
if (e.names) e.names = keep.map(i => e.names![i] ?? '')
|
|
||||||
}
|
|
||||||
// Wires on the dropped ones go; the others move to their new number.
|
|
||||||
def.wires = def.wires.filter(w => {
|
|
||||||
const side = ids.has(w.to.node) && nodes.get(w.to.node)!.kind === 'bundle' ? w.to : ids.has(w.from.node) && nodes.get(w.from.node)!.kind === 'split' ? w.from : undefined
|
|
||||||
if (!side || wireBit(side.pin) < 0) return true
|
|
||||||
const to = map.get(wireBit(side.pin))
|
|
||||||
if (to === undefined) return false
|
|
||||||
side.pin = `b${to}`
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
return { before, after: keep.length }
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -25,24 +25,11 @@ function partName(n: CircuitNode, get: DefLookup): string {
|
||||||
return own ? `${kind} ${own}` : (n.label?.trim() ? `${kind} ${n.label.trim()}` : kind)
|
return own ? `${kind} ${own}` : (n.label?.trim() ? `${kind} ${n.label.trim()}` : kind)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Pins of a part with a wire or cable, coming in or going out. */
|
/** Input pins of a part that have no wire. */
|
||||||
const linkedPins = (def: ComponentDef, n: CircuitNode) => new Set(def.wires.flatMap(w => [w.to.node === n.id ? w.to.pin : '', w.from.node === n.id ? w.from.pin : '']))
|
|
||||||
|
|
||||||
/** Input pins of a part that have no wire (a line of a split port is fed by the cable when one is in its socket). */
|
|
||||||
export function openInputs(def: ComponentDef, n: CircuitNode, get: DefLookup): string[] {
|
export function openInputs(def: ComponentDef, n: CircuitNode, get: DefLookup): string[] {
|
||||||
if (!CHECKED_INPUTS.has(n.kind)) return []
|
if (!CHECKED_INPUTS.has(n.kind)) return []
|
||||||
const linked = linkedPins(def, n)
|
|
||||||
const wired = new Set(def.wires.filter(w => w.to.node === n.id).map(w => w.to.pin))
|
const wired = new Set(def.wires.filter(w => w.to.node === n.id).map(w => w.to.pin))
|
||||||
// An RGB pixel may use only some of its colours.
|
return shapeOf(n, get).inputs.filter(p => !p.bus && !wired.has(p.key)).map(p => p.key)
|
||||||
if (n.kind === 'pixel' && n.rgb && wired.size) return []
|
|
||||||
return shapeOf(n, get).inputs.filter(p => !p.bus && !(p.port && linked.has(p.port)) && !wired.has(p.key)).map(p => p.key)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Lines of split ports on a component's box that are wired by hand while a cable is plugged into their port. */
|
|
||||||
export function doublyFedLines(def: ComponentDef, n: CircuitNode, get: DefLookup): string[] {
|
|
||||||
if (n.kind !== 'chip' || !n.splitPorts?.length) return []
|
|
||||||
const linked = linkedPins(def, n)
|
|
||||||
return shapeOf(n, get).inputs.filter(p => p.port && linked.has(p.key) && linked.has(p.port)).map(p => p.key)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function checkCircuit(def: ComponentDef, get: DefLookup): Issue[] {
|
export function checkCircuit(def: ComponentDef, get: DefLookup): Issue[] {
|
||||||
|
|
@ -67,12 +54,6 @@ export function checkCircuit(def: ComponentDef, get: DefLookup): Issue[] {
|
||||||
issues.push({ level: 'warn', text, nodes: [n.id] })
|
issues.push({ level: 'warn', text, nodes: [n.id] })
|
||||||
}
|
}
|
||||||
if (n.kind === 'split' && !def.wires.some(w => w.to.node === n.id)) issues.push({ level: 'warn', text: 'Cable split without a cable', nodes: [n.id] })
|
if (n.kind === 'split' && !def.wires.some(w => w.to.node === n.id)) issues.push({ level: 'warn', text: 'Cable split without a cable', nodes: [n.id] })
|
||||||
const twice = doublyFedLines(def, n, get)
|
|
||||||
if (twice.length) {
|
|
||||||
const shape = shapeOf(n, get)
|
|
||||||
const labels = twice.map(k => shape.inputs.find(p => p.key === k)?.label || k)
|
|
||||||
issues.push({ level: 'error', text: `${name(n)}: ${labels.join(', ')} wired and fed by the cable as well: they drive ${twice.length === 1 ? 'it' : 'them'} against each other`, nodes: [n.id] })
|
|
||||||
}
|
|
||||||
// Parts that drive nothing.
|
// Parts that drive nothing.
|
||||||
if ((n.kind === 'input' || n.kind === 'button' || n.kind === 'clock' || n.kind === 'nand') && !fed.has(`${n.id}:q`)) {
|
if ((n.kind === 'input' || n.kind === 'button' || n.kind === 'clock' || n.kind === 'nand') && !fed.has(`${n.id}:q`)) {
|
||||||
issues.push({ level: 'info', text: n.kind === 'nand' ? 'NAND gate: its output goes nowhere' : `${name(n)}: goes nowhere`, nodes: [n.id] })
|
issues.push({ level: 'info', text: n.kind === 'nand' ? 'NAND gate: its output goes nowhere' : `${name(n)}: goes nowhere`, nodes: [n.id] })
|
||||||
|
|
|
||||||
|
|
@ -2,10 +2,7 @@
|
||||||
// nets. Chip boundaries and input/output pins disappear: they are aliases,
|
// nets. Chip boundaries and input/output pins disappear: they are aliases,
|
||||||
// merged with union-find. Net 0 is constant LOW, net 1 constant HIGH.
|
// merged with union-find. Net 0 is constant LOW, net 1 constant HIGH.
|
||||||
|
|
||||||
import { cableBits, chipPins, isPinRow, portLines, rowPin, splitLines, type ChipPins, type DefLookup } from './geometry'
|
import { cableBits, chipPins, isPinRow, rowPin, type ChipPins, type DefLookup } from './geometry'
|
||||||
import { colKeys } from './benchLayout'
|
|
||||||
import { DATA_KEYS } from './devices'
|
|
||||||
import { displayPins } from './displays'
|
|
||||||
import type { CircuitNode, ComponentDef, Wire } from './types'
|
import type { CircuitNode, ComponentDef, Wire } from './types'
|
||||||
|
|
||||||
export const LOW = 0
|
export const LOW = 0
|
||||||
|
|
@ -39,56 +36,31 @@ export interface Netlist {
|
||||||
errors: string[]
|
errors: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export function inputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup): string[] {
|
export function inputKeys(node: CircuitNode, pins?: ChipPins): string[] {
|
||||||
switch (node.kind) {
|
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':
|
case 'nand':
|
||||||
return ['a', 'b']
|
return ['a', 'b']
|
||||||
case 'pixel':
|
|
||||||
return node.rgb ? ['r', 'g', 'b'] : ['a']
|
|
||||||
case 'output':
|
case 'output':
|
||||||
case 'lamp':
|
case 'lamp':
|
||||||
|
case 'pixel':
|
||||||
case 'split':
|
case 'split':
|
||||||
case 'tag':
|
case 'tag':
|
||||||
return ['a']
|
return ['a']
|
||||||
case 'hex':
|
case 'hex':
|
||||||
return ['b0', 'b1', 'b2', 'b3']
|
return ['b0', 'b1', 'b2', 'b3']
|
||||||
case 'terminal':
|
|
||||||
case 'monitor':
|
|
||||||
case 'rgbmonitor':
|
|
||||||
return displayPins(node).map(p => p.key)
|
|
||||||
case 'keyboard':
|
|
||||||
return ['next']
|
|
||||||
case 'bench':
|
|
||||||
return (node.bench?.cols ?? []).filter(c => c.dir === 'check').flatMap(colKeys)
|
|
||||||
case 'scope':
|
|
||||||
return (node.scope?.cols ?? []).flatMap(colKeys)
|
|
||||||
case 'outpanel':
|
case 'outpanel':
|
||||||
return (node.rows ?? []).map(r => r.id)
|
return (node.rows ?? []).map(r => r.id)
|
||||||
case 'bundle':
|
case 'bundle':
|
||||||
return cableKeys(node)
|
return cableKeys(node)
|
||||||
case 'chip':
|
case 'chip':
|
||||||
return pins ? [...pins.inputs.map(p => p.key), ...portKeys(pins, 'in'), ...lineKeys(node, pins, get, true)] : []
|
return pins ? pins.inputs.map(p => p.key) : []
|
||||||
default:
|
default:
|
||||||
return []
|
return []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Keys of a component's connector ports on one side. */
|
export function outputKeys(node: CircuitNode, pins?: ChipPins): string[] {
|
||||||
const portKeys = (pins: ChipPins, side: 'in' | 'out') => (pins.ports ?? []).filter(p => p.side === side).map(p => p.key)
|
|
||||||
|
|
||||||
/** Keys of the lines of ports split on a placed component's box that go in (or come out). */
|
|
||||||
const lineKeys = (node: CircuitNode, pins: ChipPins, get: DefLookup | undefined, enters: boolean) => splitLines(node, pins, get).filter(l => l.enters === enters).map(l => l.key)
|
|
||||||
|
|
||||||
export function outputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup): string[] {
|
|
||||||
switch (node.kind) {
|
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 'output':
|
||||||
case 'lamp':
|
case 'lamp':
|
||||||
return ['q']
|
return ['q']
|
||||||
|
|
@ -101,13 +73,9 @@ export function outputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup):
|
||||||
case 'ref':
|
case 'ref':
|
||||||
return ['q']
|
return ['q']
|
||||||
case 'chip':
|
case 'chip':
|
||||||
return pins ? [...pins.outputs.map(p => p.key), ...portKeys(pins, 'out'), ...lineKeys(node, pins, get, false)] : []
|
return pins ? pins.outputs.map(p => p.key) : []
|
||||||
case 'hex':
|
case 'hex':
|
||||||
return ['q0', 'q1', 'q2', 'q3']
|
return ['q0', 'q1', 'q2', 'q3']
|
||||||
case 'keyboard':
|
|
||||||
return [...DATA_KEYS, 'rdy']
|
|
||||||
case 'bench':
|
|
||||||
return (node.bench?.cols ?? []).filter(c => c.dir === 'drive').flatMap(colKeys)
|
|
||||||
case 'panel':
|
case 'panel':
|
||||||
case 'outpanel':
|
case 'outpanel':
|
||||||
return (node.rows ?? []).map(r => r.id)
|
return (node.rows ?? []).map(r => r.id)
|
||||||
|
|
@ -138,7 +106,7 @@ export function cableKeys(node: CircuitNode): string[] {
|
||||||
/** Key of a panel row in the simulator's sources, like a switch's node id. */
|
/** Key of a panel row in the simulator's sources, like a switch's node id. */
|
||||||
export const rowSource = rowPin
|
export const rowSource = rowPin
|
||||||
|
|
||||||
export const MAX_DEPTH = 64
|
const MAX_DEPTH = 64
|
||||||
|
|
||||||
export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boolean } = {}): Netlist {
|
export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boolean } = {}): Netlist {
|
||||||
const parent: number[] = [LOW, HIGH]
|
const parent: number[] = [LOW, HIGH]
|
||||||
|
|
@ -186,14 +154,7 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
|
||||||
return p
|
return p
|
||||||
}
|
}
|
||||||
|
|
||||||
// `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[]): Map<string, number> => {
|
||||||
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>()
|
const result = new Map<string, number>()
|
||||||
if (stack.includes(def.id)) {
|
if (stack.includes(def.id)) {
|
||||||
errors.push(`"${def.name}" contains itself`)
|
errors.push(`"${def.name}" contains itself`)
|
||||||
|
|
@ -208,14 +169,10 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
|
||||||
const wiresTo = new Map<string, Wire>()
|
const wiresTo = new Map<string, Wire>()
|
||||||
for (const w of def.wires) wiresTo.set(`${w.to.node}:${w.to.pin}`, w)
|
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]))
|
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[]>()
|
|
||||||
// Line pins of ports split on boxes ("node:pin"): the line's net, wired by hand or fed through the cable.
|
|
||||||
const lineNets = new Map<string, number>()
|
|
||||||
|
|
||||||
const outNet = new Map<string, number>()
|
const outNet = new Map<string, number>()
|
||||||
for (const n of def.nodes) {
|
for (const n of def.nodes) {
|
||||||
for (const k of outputKeys(n, pinsOf(n), getDef)) outNet.set(`${n.id}:${k}`, make())
|
for (const k of outputKeys(n, pinsOf(n))) outNet.set(`${n.id}:${k}`, make())
|
||||||
}
|
}
|
||||||
const inNet = (nodeId: string, pin: string) => {
|
const inNet = (nodeId: string, pin: string) => {
|
||||||
const w = wiresTo.get(`${nodeId}:${pin}`)
|
const w = wiresTo.get(`${nodeId}:${pin}`)
|
||||||
|
|
@ -264,11 +221,6 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
|
||||||
case 'button':
|
case 'button':
|
||||||
if (!inNets) sources.set(n.id, q)
|
if (!inNets) sources.set(n.id, q)
|
||||||
break
|
break
|
||||||
case 'bench':
|
|
||||||
case 'keyboard':
|
|
||||||
// Set from outside (the keys typed, a bench's row), in the open circuit; inside a component it is all 0.
|
|
||||||
if (!inNets) for (const k of outputKeys(n)) sources.set(`${n.id}:${k}`, outNet.get(`${n.id}:${k}`)!)
|
|
||||||
break
|
|
||||||
case 'high':
|
case 'high':
|
||||||
union(q, HIGH)
|
union(q, HIGH)
|
||||||
break
|
break
|
||||||
|
|
@ -322,20 +274,6 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
|
||||||
if (!n.inner) result.set(rowPin(n.id, r.id), net)
|
if (!n.inner) result.set(rowPin(n.id, r.id), net)
|
||||||
}
|
}
|
||||||
break
|
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': {
|
case 'chip': {
|
||||||
const child = n.chip ? getDef(n.chip) : undefined
|
const child = n.chip ? getDef(n.chip) : undefined
|
||||||
const pins = pinsOf(n)
|
const pins = pinsOf(n)
|
||||||
|
|
@ -345,35 +283,13 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
|
||||||
}
|
}
|
||||||
const childIn = new Map<string, number>()
|
const childIn = new Map<string, number>()
|
||||||
for (const p of pins.inputs) childIn.set(p.key, pinIn(n, p.key))
|
for (const p of pins.inputs) childIn.set(p.key, pinIn(n, p.key))
|
||||||
const childPorts = new Map<string, number[]>()
|
const childOut = expand(child, childIn, `${path}${n.id}/`, inner)
|
||||||
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)
|
|
||||||
}
|
|
||||||
// A port split on the box: each line is a pin of its own as well. A
|
|
||||||
// wire into a line drives it like the cable would (both at once is a short).
|
|
||||||
for (const l of splitLines(n, pins, getDef)) {
|
|
||||||
const net = childPorts.get(l.port)?.[l.index]
|
|
||||||
if (net === undefined) continue
|
|
||||||
lineNets.set(`${n.id}:${l.key}`, net)
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
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)
|
for (const p of pins.outputs) union(outNet.get(`${n.id}:${p.key}`)!, childOut.get(p.key) ?? LOW)
|
||||||
break
|
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.
|
// Lamps, displays and pixels inside placed components, at every depth: a box may show those of parts inside it.
|
||||||
if (stack.length >= 1) {
|
if (stack.length >= 1) {
|
||||||
for (const n of def.nodes) {
|
for (const n of def.nodes) {
|
||||||
|
|
@ -388,8 +304,8 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
|
||||||
}
|
}
|
||||||
for (const n of def.nodes) {
|
for (const n of def.nodes) {
|
||||||
const pins = pinsOf(n)
|
const pins = pinsOf(n)
|
||||||
for (const k of inputKeys(n, pins, getDef)) record(n, k, lineNets.get(`${n.id}:${k}`) ?? inNet(n.id, k))
|
for (const k of inputKeys(n, pins)) record(n, k, inNet(n.id, k))
|
||||||
for (const k of outputKeys(n, pins, getDef)) record(n, k, outNet.get(`${n.id}:${k}`)!)
|
for (const k of outputKeys(n, pins)) record(n, k, outNet.get(`${n.id}:${k}`)!)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
|
|
|
||||||
|
|
@ -1,71 +0,0 @@
|
||||||
// Text in and out: a terminal shows the characters a circuit writes, a
|
|
||||||
// keyboard hands it the keys you type. Both act on the rising edge of a pin
|
|
||||||
// (WR, CLR, NEXT), the way a real chip latches on a strobe, and only in the
|
|
||||||
// circuit you have open (inside a component they do nothing).
|
|
||||||
|
|
||||||
/** Data pins, bit 0 first: one character code, 8 bits. */
|
|
||||||
export const DATA_KEYS = ['d0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7']
|
|
||||||
|
|
||||||
export const TERMINAL_COLS = 32
|
|
||||||
export const TERMINAL_LINES = 10
|
|
||||||
/** Lines a terminal keeps (what scrolled out of view is gone after these). */
|
|
||||||
const KEEP = 200
|
|
||||||
/** Keys a keyboard holds before it drops new ones. */
|
|
||||||
export const KEY_QUEUE = 64
|
|
||||||
|
|
||||||
export const DEVICE_PIN_NAMES: Record<string, string> = {
|
|
||||||
...Object.fromEntries(DATA_KEYS.map((k, i) => [k, `D${i}`])),
|
|
||||||
wr: 'WR',
|
|
||||||
clr: 'CLR',
|
|
||||||
next: 'NEXT',
|
|
||||||
rdy: 'RDY',
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A terminal's text after one more character: printable codes from 32 (in
|
|
||||||
* Latin-1), 10 a new line, 13 back to the line's start, 8 one back, 9 to the
|
|
||||||
* next multiple of 4, 12 a clear screen; other control codes do nothing.
|
|
||||||
* Lines wrap at the terminal's width.
|
|
||||||
*/
|
|
||||||
export function putChar(lines: string[], code: number, cols = TERMINAL_COLS): string[] {
|
|
||||||
const out = lines.length ? [...lines] : ['']
|
|
||||||
const last = () => out[out.length - 1]!
|
|
||||||
const set = (s: string) => (out[out.length - 1] = s)
|
|
||||||
if (code === 12) return ['']
|
|
||||||
if (code === 10) out.push('')
|
|
||||||
else if (code === 13) set('')
|
|
||||||
else if (code === 8) set(last().slice(0, -1))
|
|
||||||
else if (code === 9) {
|
|
||||||
const n = 4 - (last().length % 4)
|
|
||||||
for (let i = 0; i < n; i++) {
|
|
||||||
if (last().length >= cols) out.push('')
|
|
||||||
set(last() + ' ')
|
|
||||||
}
|
|
||||||
} else if (code >= 32 && code !== 127 && code < 256) {
|
|
||||||
if (last().length >= cols) out.push('')
|
|
||||||
set(last() + String.fromCharCode(code))
|
|
||||||
}
|
|
||||||
return out.length > KEEP ? out.slice(out.length - KEEP) : out
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The code a key press types, or null for keys that type nothing. */
|
|
||||||
export function keyCode(e: { key: string; ctrlKey?: boolean; metaKey?: boolean; altKey?: boolean }): number | null {
|
|
||||||
if (e.metaKey || e.altKey) return null
|
|
||||||
if (e.ctrlKey) return e.key.length === 1 && /[a-z]/i.test(e.key) ? e.key.toUpperCase().charCodeAt(0) - 64 : null
|
|
||||||
if (e.key === 'Enter') return 10
|
|
||||||
if (e.key === 'Backspace') return 8
|
|
||||||
if (e.key === 'Tab') return 9
|
|
||||||
if (e.key === 'Delete') return 127
|
|
||||||
if (e.key.length !== 1) return null
|
|
||||||
const c = e.key.charCodeAt(0)
|
|
||||||
return c < 256 ? c : null
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A key's code as data bits. */
|
|
||||||
export const codeBits = (code: number) => DATA_KEYS.map((_, i) => (code >> i) & 1)
|
|
||||||
|
|
||||||
/** Data bits as a code. */
|
|
||||||
export const bitsCode = (bits: number[]) => bits.reduce((v, b, i) => v + (b ? 1 << i : 0), 0)
|
|
||||||
|
|
||||||
/** How a key waiting in a keyboard shows. */
|
|
||||||
export const keyLabel = (code: number) => (code === 10 ? '⏎' : code === 8 ? '⌫' : code === 9 ? '⇥' : code === 32 ? '␣' : code < 32 || code === 127 ? '·' : String.fromCharCode(code))
|
|
||||||
|
|
@ -1,84 +0,0 @@
|
||||||
// Screens you write to instead of wiring every pixel: the terminal (text),
|
|
||||||
// the monitor (one bit a pixel, like an OLED) and the RGB monitor (eight
|
|
||||||
// colours). Each has a size you set (characters, or pixels), and its pins
|
|
||||||
// follow it: a monitor's X and Y address bits are as many as its width and
|
|
||||||
// height need. A rising WR writes, a rising CLR clears.
|
|
||||||
|
|
||||||
import type { CircuitNode, NodeKind } from './types'
|
|
||||||
|
|
||||||
export type DisplayKind = 'terminal' | 'monitor' | 'rgbmonitor'
|
|
||||||
export const DISPLAY_KINDS: NodeKind[] = ['terminal', 'monitor', 'rgbmonitor']
|
|
||||||
export const isDisplay = (k: NodeKind): k is DisplayKind => DISPLAY_KINDS.includes(k)
|
|
||||||
|
|
||||||
/** Sizes: characters for the terminal, pixels for the monitors. */
|
|
||||||
export const DISPLAY_SIZES: Record<DisplayKind, { min: [number, number]; max: [number, number]; start: [number, number]; unit: string }> = {
|
|
||||||
terminal: { min: [4, 1], max: [120, 60], start: [32, 10], unit: 'characters' },
|
|
||||||
monitor: { min: [2, 2], max: [128, 128], start: [32, 32], unit: 'pixels' },
|
|
||||||
rgbmonitor: { min: [2, 2], max: [128, 128], start: [32, 24], unit: 'pixels' },
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Grid units a character (terminal) or a pixel (monitors) takes on the box. */
|
|
||||||
export const TERM_CHAR = 6.6 / 16
|
|
||||||
export const TERM_LINE = 1
|
|
||||||
export const PIXEL = 0.5
|
|
||||||
|
|
||||||
export function clampSize(kind: DisplayKind, w: number, h: number): [number, number] {
|
|
||||||
const { min, max } = DISPLAY_SIZES[kind]
|
|
||||||
const c = (v: number, i: 0 | 1) => Math.max(min[i], Math.min(max[i], Math.round(v) || min[i]))
|
|
||||||
return [c(w, 0), c(h, 1)]
|
|
||||||
}
|
|
||||||
|
|
||||||
export function displaySize(n: CircuitNode): [number, number] {
|
|
||||||
const kind = n.kind as DisplayKind
|
|
||||||
return n.dims ? clampSize(kind, n.dims[0], n.dims[1]) : DISPLAY_SIZES[kind].start
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Address bits for a count of columns or rows. */
|
|
||||||
export const addrBits = (n: number) => Math.max(1, Math.ceil(Math.log2(n)))
|
|
||||||
|
|
||||||
/** The input pins, top to bottom. */
|
|
||||||
export function displayPins(n: CircuitNode): { key: string; label: string }[] {
|
|
||||||
const bits = (p: string, k: number) => Array.from({ length: k }, (_, i) => ({ key: `${p}${i}`, label: `${p.toUpperCase()}${i}` }))
|
|
||||||
if (n.kind === 'terminal') return [...bits('d', 8), { key: 'wr', label: 'WR' }, { key: 'clr', label: 'CLR' }]
|
|
||||||
const [w, h] = displaySize(n)
|
|
||||||
const data = n.kind === 'rgbmonitor' ? ['r', 'g', 'b'].map(k => ({ key: k, label: k.toUpperCase() })) : [{ key: 'd', label: 'D' }]
|
|
||||||
return [...bits('x', addrBits(w)), ...bits('y', addrBits(h)), ...data, { key: 'wr', label: 'WR' }, { key: 'clr', label: 'CLR' }]
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DisplayLayout {
|
|
||||||
w: number
|
|
||||||
h: number
|
|
||||||
/** The screen, in grid units from the node. */
|
|
||||||
sx: number
|
|
||||||
sy: number
|
|
||||||
sw: number
|
|
||||||
sh: number
|
|
||||||
/** One character or pixel. */
|
|
||||||
cw: number
|
|
||||||
ch: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export function displayLayout(n: CircuitNode): DisplayLayout {
|
|
||||||
const [cols, lines] = displaySize(n)
|
|
||||||
const pins = displayPins(n).length
|
|
||||||
const cw = n.kind === 'terminal' ? TERM_CHAR : PIXEL
|
|
||||||
const ch = n.kind === 'terminal' ? TERM_LINE : PIXEL
|
|
||||||
const sx = 2
|
|
||||||
const sy = -0.5 + 0.2
|
|
||||||
const sw = cols * cw + (n.kind === 'terminal' ? 0.3 : 0)
|
|
||||||
const sh = lines * ch
|
|
||||||
return { w: Math.ceil(sx + sw + 0.3), h: Math.max(pins, Math.ceil(sh + 0.4)), sx, sy, sw, sh, cw, ch }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Width to height, in small numbers when there are some (16:9), else to two places (1.78:1). */
|
|
||||||
export function ratioText(w: number, h: number): string {
|
|
||||||
const gcd = (a: number, b: number): number => (b ? gcd(b, a % b) : a)
|
|
||||||
const g = gcd(w, h)
|
|
||||||
const a = w / g
|
|
||||||
const b = h / g
|
|
||||||
return a <= 32 && b <= 32 ? `${a}:${b}` : `${(w / h).toFixed(2)}:1`
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A pixel's colour on an RGB monitor (value r + 2g + 4b); black is 0. */
|
|
||||||
export const RGB_PIXEL = ['#000000', '#ff4d4d', '#3ddc84', '#ffe04d', '#4d7dff', '#ff5cf0', '#4de8ff', '#f2f6fa']
|
|
||||||
export const MONO_PIXEL = '#e8f0f8'
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
// and the pins a part being dragged lands on (connected when it is dropped).
|
// and the pins a part being dragged lands on (connected when it is dropped).
|
||||||
|
|
||||||
import { byPosition, type Link } from './bulk'
|
import { byPosition, type Link } from './bulk'
|
||||||
import { pinKindOf, shapeOf, type DefLookup, type Pt, type Shape } from './geometry'
|
import { shapeOf, type DefLookup, type Pt, type Shape } from './geometry'
|
||||||
import { SOURCE_KINDS } from './ops'
|
import { SOURCE_KINDS } from './ops'
|
||||||
import type { CircuitNode, ComponentDef, PinRef } from './types'
|
import type { CircuitNode, ComponentDef, PinRef } from './types'
|
||||||
|
|
||||||
|
|
@ -141,8 +141,7 @@ export interface DropPin {
|
||||||
node: string
|
node: string
|
||||||
pin: string
|
pin: string
|
||||||
dir: 'in' | 'out'
|
dir: 'in' | 'out'
|
||||||
/** What it plugs into: '' a wire, 'bus' a cable, 'c:<id>' a connector port. */
|
bus: boolean
|
||||||
bus: string
|
|
||||||
/** Wired already: an input can't take a second wire. */
|
/** Wired already: an input can't take a second wire. */
|
||||||
wired: boolean
|
wired: boolean
|
||||||
x: number
|
x: number
|
||||||
|
|
@ -155,8 +154,8 @@ export function dropPins(def: ComponentDef, nodes: CircuitNode[], shape: ShapeOf
|
||||||
const out: DropPin[] = []
|
const out: DropPin[] = []
|
||||||
for (const n of nodes) {
|
for (const n of nodes) {
|
||||||
const s = shape(n)
|
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.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: pinKindOf(p), wired: wired.out.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 })
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,7 @@
|
||||||
// Node shapes and pin positions, all in grid units relative to the node's
|
// 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.
|
// (x, y). Pins always sit on whole grid points so straight wires line up.
|
||||||
|
|
||||||
import type { CircuitNode, ComponentDef, ConnectorType, FaceShape, LampColor, PanelRow, SymbolKind } from './types'
|
import type { CircuitNode, ComponentDef, FaceShape, LampColor, PanelRow, SymbolKind } from './types'
|
||||||
import { benchLayout } from './benchLayout'
|
|
||||||
import { scopeLayout } from './scopeLayout'
|
|
||||||
import { DATA_KEYS, DEVICE_PIN_NAMES } from './devices'
|
|
||||||
import { displayLayout, displayPins } from './displays'
|
|
||||||
|
|
||||||
export const GRID = 16
|
export const GRID = 16
|
||||||
|
|
||||||
|
|
@ -16,12 +12,6 @@ export interface PinInfo {
|
||||||
dy: number
|
dy: number
|
||||||
/** A cable pin: only joins another cable pin. */
|
/** A cable pin: only joins another cable pin. */
|
||||||
bus?: boolean
|
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
|
|
||||||
/** A line of a port split on a component's box: the port's key. */
|
|
||||||
port?: string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Shape {
|
export interface Shape {
|
||||||
|
|
@ -40,15 +30,9 @@ export interface Shape {
|
||||||
drawing?: FaceShape[]
|
drawing?: FaceShape[]
|
||||||
}
|
}
|
||||||
|
|
||||||
/** What an RGB pixel shows for its red, green and blue inputs (index r + 2g + 4b); black is off. */
|
|
||||||
export const RGB_HEX = ['', '#ff4d4d', '#3ddc84', '#ffe04d', '#4d7dff', '#ff5cf0', '#4de8ff', '#f2f6fa'] as const
|
|
||||||
export const rgbHex = (r: number, g: number, b: number) => RGB_HEX[(r ? 1 : 0) + (g ? 2 : 0) + (b ? 4 : 0)]!
|
|
||||||
|
|
||||||
export interface ScreenPixel {
|
export interface ScreenPixel {
|
||||||
/** Pixel node id inside the component. */
|
/** Pixel node id inside the component. */
|
||||||
id: string
|
id: string
|
||||||
/** Lit by its red, green and blue inputs. */
|
|
||||||
rgb?: boolean
|
|
||||||
col: number
|
col: number
|
||||||
row: number
|
row: number
|
||||||
color?: LampColor
|
color?: LampColor
|
||||||
|
|
@ -64,8 +48,6 @@ export interface FaceItem {
|
||||||
rotate?: number
|
rotate?: number
|
||||||
/** A display of a component inside: that component's name. */
|
/** A display of a component inside: that component's name. */
|
||||||
from?: string
|
from?: string
|
||||||
/** A pixel shown on its own: the key of the screen it is part of. */
|
|
||||||
screenOf?: string
|
|
||||||
kind: 'lamp' | 'hex' | 'screen'
|
kind: 'lamp' | 'hex' | 'screen'
|
||||||
/** Screen only: its pixels and the size of one, in grid units. */
|
/** Screen only: its pixels and the size of one, in grid units. */
|
||||||
pixels?: ScreenPixel[]
|
pixels?: ScreenPixel[]
|
||||||
|
|
@ -79,8 +61,7 @@ export interface FaceItem {
|
||||||
h: number
|
h: number
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Finds a component by id; `conn` finds a connector type (set by `lookup(project)`). */
|
export type DefLookup = (id: string) => ComponentDef | undefined
|
||||||
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 LABEL_CHAR = 0.4 // grid units per character of a pin label
|
||||||
const NAME_CHAR = 0.44
|
const NAME_CHAR = 0.44
|
||||||
|
|
@ -89,58 +70,11 @@ const FACE_CHAR = 0.34
|
||||||
export interface ChipPins {
|
export interface ChipPins {
|
||||||
inputs: { key: string; label: string }[]
|
inputs: { key: string; label: string }[]
|
||||||
outputs: { 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. */
|
/** 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}`
|
export const rowPin = (panelId: string, rowId: string) => `${panelId}:${rowId}`
|
||||||
|
|
||||||
/** What a port is called on a component's box: its own name, else its connector type's. */
|
|
||||||
export const portName = (p: PortPin, get?: DefLookup) => p.label || get?.conn?.(p.conn)?.name || 'port'
|
|
||||||
|
|
||||||
/** Pin key of a line of a port split on a component's box: port.line (a dot, so it never reads as a panel row). */
|
|
||||||
export const linePin = (port: string, line: string) => `${port}.${line}`
|
|
||||||
|
|
||||||
export interface SplitLine {
|
|
||||||
/** Pin key on the box. */
|
|
||||||
key: string
|
|
||||||
name: string
|
|
||||||
/** The port's key, and the line's place in its connector type. */
|
|
||||||
port: string
|
|
||||||
index: number
|
|
||||||
/** The line goes into the component (an input pin on the box); otherwise it comes out (an output). */
|
|
||||||
enters: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The lines of the ports split on a placed component's box, top to bottom,
|
|
||||||
* as pins of their own: inputs for lines going into the component, outputs
|
|
||||||
* for lines coming out. An in port brings its forward lines in, an out port
|
|
||||||
* its back lines.
|
|
||||||
*/
|
|
||||||
export function splitLines(node: CircuitNode, pins: ChipPins, get?: DefLookup): SplitLine[] {
|
|
||||||
if (!node.splitPorts?.length) return []
|
|
||||||
const split = new Set(node.splitPorts)
|
|
||||||
const out: SplitLine[] = []
|
|
||||||
for (const p of pins.ports ?? []) {
|
|
||||||
if (!split.has(p.key)) continue
|
|
||||||
get?.conn?.(p.conn)?.lines.forEach((l, i) => out.push({ key: linePin(p.key, `l${i}`), name: l.name, port: p.key, index: i, enters: (p.side === 'in') !== !!l.back }))
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Panel rows that are input pins of their component: switches and buttons, unless the panel keeps them inside. */
|
/** Panel rows that are input pins of their component: switches and buttons, unless the panel keeps them inside. */
|
||||||
export const isPinRow = (panel: CircuitNode, row: PanelRow) => !panel.inner && row.type !== 'clock'
|
export const isPinRow = (panel: CircuitNode, row: PanelRow) => !panel.inner && row.type !== 'clock'
|
||||||
|
|
||||||
|
|
@ -172,14 +106,9 @@ export function chipPins(def: ComponentDef): ChipPins {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
outputs.sort((a, b) => a.y - b.y || a.x - b.x)
|
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 {
|
return {
|
||||||
inputs: inputs.map((p, i) => ({ key: p.key, label: p.label || `in${i + 1}` })),
|
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}` })),
|
outputs: outputs.map((p, i) => ({ key: p.key, label: p.label || `out${i + 1}` })),
|
||||||
...(ports.length ? { ports } : {}),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -254,16 +183,10 @@ function shownItems(def: ComponentDef, get: DefLookup, depth: number): FaceItem[
|
||||||
if (def.face === false || depth > 4) return []
|
if (def.face === false || depth > 4) return []
|
||||||
const d = def.design
|
const d = def.design
|
||||||
const hide = new Set(d?.hide ?? [])
|
const hide = new Set(d?.hide ?? [])
|
||||||
// As its own box shows them: turned and sized the same, screens split into pixels where it does.
|
const own = ownFaceItems(def).filter(it => !hide.has(it.key))
|
||||||
const looks = (it: FaceItem): FaceItem => ({
|
|
||||||
...it,
|
|
||||||
...(d?.scale?.[it.key] ? { scale: d.scale[it.key] } : {}),
|
|
||||||
...(d?.rotate?.[it.key] ? { rotate: d.rotate[it.key] } : {}),
|
|
||||||
})
|
|
||||||
const own = splitScreens(ownFaceItems(def), new Set(d?.split ?? [])).filter(it => !hide.has(it.key)).map(looks)
|
|
||||||
if (!d?.show?.length) return own
|
if (!d?.show?.length) return own
|
||||||
const show = new Set(d.show)
|
const show = new Set(d.show)
|
||||||
return [...own, ...nestedItems(def, get, depth).filter(it => show.has(it.key)).map(looks)]
|
return [...own, ...nestedItems(def, get, depth).filter(it => show.has(it.key))]
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -278,49 +201,6 @@ export function faceCandidates(def: ComponentDef, get: DefLookup): { key: string
|
||||||
return [...own, ...nested]
|
return [...own, ...nested]
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The key of one pixel of a screen shown pixel by pixel. */
|
|
||||||
export const pixelKey = (pixelId: string) => `px:${pixelId}`
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Screens listed in `split` shown pixel by pixel: each pixel its own item,
|
|
||||||
* where it sat in the screen (sized and turned as the screen was, `looks`),
|
|
||||||
* so splitting moves nothing.
|
|
||||||
*/
|
|
||||||
export function splitScreens(items: FaceItem[], split: Set<string>, looks: (key: string) => { scale?: number; rotate?: number } = () => ({})): FaceItem[] {
|
|
||||||
if (!split.size) return items
|
|
||||||
return items.flatMap(it => {
|
|
||||||
if (it.kind !== 'screen' || !split.has(it.key) || !it.pixels || !it.px) return [it]
|
|
||||||
const { scale, rotate } = { scale: it.scale, rotate: it.rotate, ...looks(it.key) }
|
|
||||||
const k = scale ?? 1
|
|
||||||
const px = it.px!
|
|
||||||
// The screen's middle; each pixel's middle turned around it.
|
|
||||||
const cx = it.x + (it.w * k) / 2
|
|
||||||
const cy = it.y + (it.h * k) / 2
|
|
||||||
const turn = (((rotate ?? 0) % 360) + 360) % 360
|
|
||||||
return it.pixels.map(p => {
|
|
||||||
let dx = (p.col + 0.5) * px * k - (it.w * k) / 2
|
|
||||||
let dy = (p.row + 0.5) * px * k - (it.h * k) / 2
|
|
||||||
for (let a = 0; a < turn; a += 90) [dx, dy] = [-dy, dx]
|
|
||||||
const item: FaceItem = {
|
|
||||||
...it,
|
|
||||||
id: p.id,
|
|
||||||
key: pixelKey(p.id),
|
|
||||||
label: '',
|
|
||||||
x: cx + dx - (px * k) / 2,
|
|
||||||
y: cy + dy - (px * k) / 2,
|
|
||||||
w: px,
|
|
||||||
h: px,
|
|
||||||
pixels: [{ ...p, col: 0, row: 0 }],
|
|
||||||
screenOf: it.key,
|
|
||||||
}
|
|
||||||
delete item.rotate
|
|
||||||
if (k !== 1) item.scale = k
|
|
||||||
else delete item.scale
|
|
||||||
return item
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A box item's size and turn, as an SVG transform: grown from its top left corner, turned around its middle. */
|
/** A box item's size and turn, as an SVG transform: grown from its top left corner, turned around its middle. */
|
||||||
export function faceTransform(f: FaceItem): string | undefined {
|
export function faceTransform(f: FaceItem): string | undefined {
|
||||||
if (!f.scale && !f.rotate) return undefined
|
if (!f.scale && !f.rotate) return undefined
|
||||||
|
|
@ -401,7 +281,7 @@ function screenOf(pixels: CircuitNode[], name: string): FaceItem {
|
||||||
w: xs.length * px,
|
w: xs.length * px,
|
||||||
h: ys.length * px,
|
h: ys.length * px,
|
||||||
px,
|
px,
|
||||||
pixels: pixels.map(n => ({ id: n.id, col: col.get(n.x)!, row: row.get(n.y)!, color: n.color, ...(n.rgb ? { rgb: true } : {}) })),
|
pixels: pixels.map(n => ({ id: n.id, col: col.get(n.x)!, row: row.get(n.y)!, color: n.color })),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -436,93 +316,51 @@ function gateShape(symbol: SymbolKind, inputs: { key: string; label: string }[],
|
||||||
* need), everything placed where it was put, the rest where it would go
|
* need), everything placed where it was put, the rest where it would go
|
||||||
* anyway, and its drawings.
|
* anyway, and its drawings.
|
||||||
*/
|
*/
|
||||||
function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType<typeof faceLayout>, get: DefLookup, node?: CircuitNode): Shape {
|
function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType<typeof faceLayout>, get: DefLookup): Shape {
|
||||||
const auto = boxShape(def.name, pins, face, get, node)
|
const auto = boxShape(def.name, pins, face)
|
||||||
const d = def.design!
|
const d = def.design!
|
||||||
const top = auto.body.y
|
const top = auto.body.y
|
||||||
const hide = new Set(d.hide ?? [])
|
const hide = new Set(d.hide ?? [])
|
||||||
const place = d.place ?? {}
|
const place = d.place ?? {}
|
||||||
// Pins on each edge, top to bottom (in the order set, else as they come): where they were put, the others one row under the pin above.
|
// Pins on their edges: where they were put, the others one row under the pin above.
|
||||||
const order = new Map((d.pinOrder ?? []).map((k, i) => [k, i]))
|
const placePins = <P extends PinInfo>(list: P[]) => {
|
||||||
const rank = (p: PinInfo) => order.get(p.key) ?? 1e6 + p.dy
|
|
||||||
const placePins = (list: PinInfo[]) => {
|
|
||||||
let prev = -Infinity
|
let prev = -Infinity
|
||||||
// The first pin takes the edge's first row, whichever pin that is.
|
return list.map(p => {
|
||||||
const first = Math.min(...list.map(p => p.dy))
|
|
||||||
return list
|
|
||||||
.sort((a, b) => rank(a) - rank(b) || a.dy - b.dy)
|
|
||||||
.map(p => {
|
|
||||||
const want = d.pinAt?.[p.key]
|
const want = d.pinAt?.[p.key]
|
||||||
const dy = Math.max(want ?? (prev === -Infinity ? first : prev + 1), prev + 1, 0)
|
const dy = Math.max(want ?? (prev === -Infinity ? p.dy : prev + 1), prev + 1, 0)
|
||||||
prev = dy
|
prev = dy
|
||||||
return [p.key, dy] as const
|
return { ...p, dy }
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
const edgePins = [...auto.inputs, ...auto.outputs]
|
const inputs = placePins(auto.inputs)
|
||||||
const rightPins = edgePins.filter(p => p.dx > 0)
|
const lowest = Math.max(0, ...inputs.map(p => p.dy), ...auto.outputs.map(p => d.pinAt?.[p.key] ?? p.dy))
|
||||||
const rows = new Map([...placePins(edgePins.filter(p => p.dx === 0)), ...placePins(rightPins)])
|
const w = Math.max(2, d.w)
|
||||||
const lowest = Math.max(0, ...rightPins.map(p => d.pinAt?.[p.key] ?? p.dy))
|
const outputs = placePins(auto.outputs).map(p => ({ ...p, dx: w }))
|
||||||
const bottom = Math.max(lowest, ...rows.values())
|
const bottom = Math.max(...inputs.map(p => p.dy), ...outputs.map(p => p.dy), lowest)
|
||||||
// Fitted: as wide as its pin names and its name need, as high as its pins; what it shows makes it bigger.
|
const h = Math.max(d.h, bottom - top + 0.5, 2)
|
||||||
const longest = (ps: PinInfo[]) => ps.reduce((m, p) => Math.max(m, p.label.length), 0)
|
// Own items where auto layout put them unless placed; displays of parts inside only when shown.
|
||||||
const labels = Math.ceil(longest(edgePins.filter(p => p.dx === 0)) * LABEL_CHAR + longest(rightPins) * LABEL_CHAR + (hide.has('name') || place.name ? 0 : def.name.length * NAME_CHAR) + 1.5)
|
|
||||||
const w = d.fit ? Math.max(2, labels) : Math.max(2, d.w)
|
|
||||||
const h = d.fit ? Math.max(bottom - top + 0.5, 2) : Math.max(d.h, bottom - top + 0.5, 2)
|
|
||||||
// Own items where the automatic layout put them unless placed; displays of parts inside only when shown,
|
|
||||||
// each in the first free spot unless placed. Screens split into pixels where asked: each pixel where it
|
|
||||||
// sat in the screen as placed, unless placed on its own.
|
|
||||||
const show = new Set(d.show ?? [])
|
const show = new Set(d.show ?? [])
|
||||||
const split = new Set(d.split ?? [])
|
const nested = nestedItems(def, get).filter(it => show.has(it.key))
|
||||||
const placed = (it: FaceItem): FaceItem => (place[it.key] ? { ...it, x: place[it.key]!.x, y: top + place[it.key]!.y } : it)
|
let below = (auto.face ?? []).reduce((m, it) => Math.max(m, it.y + it.h), auto.body.y + auto.body.h - 0.6) + 0.3
|
||||||
const sized = (it: FaceItem) => {
|
const items = [
|
||||||
const k = d.scale?.[it.key] ?? it.scale ?? 1
|
...(auto.face ?? []),
|
||||||
const turned = (d.rotate?.[it.key] ?? it.rotate) === 90 || (d.rotate?.[it.key] ?? it.rotate) === 270
|
...nested.map(it => {
|
||||||
return { w: (turned ? it.h : it.w) * k, h: (turned ? it.w : it.h) * k }
|
const at = { ...it, x: 0.6, y: below }
|
||||||
}
|
below += it.h + 0.3
|
||||||
const own = (auto.face ?? []).filter(it => !hide.has(it.key)).map(placed)
|
return at
|
||||||
const nestedAll = nestedItems(def, get).filter(it => show.has(it.key) && !hide.has(it.key))
|
}),
|
||||||
const taken: { x: number; y: number; w: number; h: number }[] = own.map(it => ({ x: it.x, y: it.y, ...sized(it) }))
|
]
|
||||||
// The name, where it shows.
|
const shown = items
|
||||||
if (!hide.has('name')) {
|
|
||||||
const nw = def.name.length * NAME_CHAR + 0.4
|
|
||||||
const c = place.name ? { x: place.name.x, y: top + place.name.y } : { x: w / 2, y: auto.nameY ?? 0 }
|
|
||||||
taken.push({ x: c.x - nw / 2, y: c.y - 0.55, w: nw, h: 1.1 })
|
|
||||||
}
|
|
||||||
for (const it of nestedAll) if (place[it.key]) taken.push({ x: place[it.key]!.x, y: top + place[it.key]!.y, ...sized(it) })
|
|
||||||
const labelL = longest(edgePins.filter(p => p.dx === 0)) * LABEL_CHAR + 0.6
|
|
||||||
const labelR = longest(rightPins) * LABEL_CHAR + 0.6
|
|
||||||
const nested = nestedAll.map(it => {
|
|
||||||
if (place[it.key]) return placed(it)
|
|
||||||
const spot = freeSpot(taken, sized(it), { x0: labelL, x1: Math.max(w - labelR, labelL + sized(it).w), y0: top + 0.3 })
|
|
||||||
taken.push({ ...spot, ...sized(it) })
|
|
||||||
return { ...it, ...spot }
|
|
||||||
})
|
|
||||||
const looks = (key: string) => ({ ...(d.scale?.[key] ? { scale: d.scale[key] } : {}), ...(d.rotate?.[key] ? { rotate: d.rotate[key] } : {}) })
|
|
||||||
const items = splitScreens([...own, ...nested], split, looks)
|
|
||||||
.filter(it => !hide.has(it.key))
|
.filter(it => !hide.has(it.key))
|
||||||
.map(it => (it.screenOf ? placed(it) : it))
|
.map(it => {
|
||||||
// Sized and turned as this box says, else as the part inside shows it.
|
const at = place[it.key]
|
||||||
const shown = items.map(it => {
|
const scale = d.scale?.[it.key]
|
||||||
const out: FaceItem = { ...it }
|
const rotate = d.rotate?.[it.key]
|
||||||
const scale = d.scale?.[it.key] ?? it.scale
|
return { ...it, ...(at ? { x: at.x, y: top + at.y } : {}), ...(scale ? { scale } : {}), ...(rotate ? { rotate } : {}) }
|
||||||
const rotate = d.rotate?.[it.key] ?? it.rotate
|
|
||||||
if (scale) out.scale = scale
|
|
||||||
else delete out.scale
|
|
||||||
if (rotate) out.rotate = rotate
|
|
||||||
else delete out.rotate
|
|
||||||
return out
|
|
||||||
})
|
})
|
||||||
// The box is never smaller than what it shows (sized and turned as shown), its name and, fitted, its drawings.
|
// The box is never smaller than what it shows (sized and turned as shown).
|
||||||
let right = w
|
let right = w
|
||||||
let floor = top + h
|
let floor = top + h
|
||||||
if (d.fit) {
|
|
||||||
for (const sh of d.shapes ?? []) {
|
|
||||||
const tw = sh.kind === 'text' ? (sh.text?.length ?? 1) * 0.42 * (sh.size ?? 1) : 0
|
|
||||||
right = Math.max(right, sh.x + Math.max(sh.w, 0, tw) + 0.3)
|
|
||||||
floor = Math.max(floor, top + sh.y + Math.max(sh.h, 0, sh.kind === 'text' ? (sh.size ?? 1) : 0) + 0.3)
|
|
||||||
}
|
|
||||||
if (place.name && !hide.has('name')) right = Math.max(right, place.name.x + (def.name.length * NAME_CHAR) / 2 + 0.3)
|
|
||||||
}
|
|
||||||
for (const it of shown) {
|
for (const it of shown) {
|
||||||
const k = it.scale ?? 1
|
const k = it.scale ?? 1
|
||||||
const turned = it.rotate === 90 || it.rotate === 270
|
const turned = it.rotate === 90 || it.rotate === 270
|
||||||
|
|
@ -534,11 +372,10 @@ function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType<typeo
|
||||||
floor = Math.max(floor, cy + ih / 2 + 0.3)
|
floor = Math.max(floor, cy + ih / 2 + 0.3)
|
||||||
}
|
}
|
||||||
const bw = Math.ceil(right * 2) / 2
|
const bw = Math.ceil(right * 2) / 2
|
||||||
const onEdge = (p: PinInfo) => ({ ...p, dx: p.dx > 0 ? bw : 0, dy: rows.get(p.key)! })
|
|
||||||
return {
|
return {
|
||||||
...auto,
|
...auto,
|
||||||
inputs: auto.inputs.map(onEdge),
|
inputs,
|
||||||
outputs: auto.outputs.map(onEdge),
|
outputs: bw === w ? outputs : outputs.map(p => ({ ...p, dx: bw })),
|
||||||
body: { x: 0, y: top, w: bw, h: Math.ceil((floor - top) * 2) / 2 },
|
body: { x: 0, y: top, w: bw, h: Math.ceil((floor - top) * 2) / 2 },
|
||||||
face: shown,
|
face: shown,
|
||||||
nameAt: hide.has('name') ? null : place.name ? { x: place.name.x, y: top + place.name.y } : undefined,
|
nameAt: hide.has('name') ? null : place.name ? { x: place.name.x, y: top + place.name.y } : undefined,
|
||||||
|
|
@ -546,69 +383,26 @@ function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType<typeo
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
function boxShape(name: string, pins: ChipPins, face: ReturnType<typeof faceLayout>): Shape {
|
||||||
* The first spot for a thing of size `s`, going along rows from the top
|
const nIn = pins.inputs.length
|
||||||
* left, that keeps clear of everything taken; below them all when none is.
|
const nOut = pins.outputs.length
|
||||||
*/
|
const n = Math.max(nIn, nOut, 1)
|
||||||
function freeSpot(taken: { x: number; y: number; w: number; h: number }[], s: { w: number; h: number }, area: { x0: number; x1: number; y0: number }): { x: number; y: number } {
|
const inOff = Math.floor((n - nIn) / 2)
|
||||||
const gap = 0.3
|
const outOff = Math.floor((n - nOut) / 2)
|
||||||
const clear = (x: number, y: number) => taken.every(t => x + s.w + gap <= t.x || x >= t.x + t.w + gap || y + s.h + gap <= t.y || y >= t.y + t.h + gap)
|
const longest = (ps: { label: string }[]) => ps.reduce((m, p) => Math.max(m, p.label.length), 0)
|
||||||
const lowest = taken.reduce((m, t) => Math.max(m, t.y + t.h), area.y0)
|
|
||||||
for (let y = area.y0; y <= lowest; y += 0.25) {
|
|
||||||
for (let x = area.x0; x + s.w <= area.x1 + 1e-9; x += 0.25) if (clear(x, y)) return { x, y }
|
|
||||||
}
|
|
||||||
return { x: area.x0, y: lowest + gap }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A pin on one edge of a component's box, and whether a signal goes in or comes out there. */
|
|
||||||
interface EdgePin {
|
|
||||||
pin: Omit<PinInfo, 'dx' | 'dy'>
|
|
||||||
dir: 'in' | 'out'
|
|
||||||
}
|
|
||||||
|
|
||||||
function boxShape(name: string, plain: ChipPins, face: ReturnType<typeof faceLayout>, get?: DefLookup, node?: CircuitNode): Shape {
|
|
||||||
// Ports sit at the very top of their side, as one cable pin each. A port
|
|
||||||
// split on this box has a pin per line right below it, facing out of its side.
|
|
||||||
const lines = node ? splitLines(node, plain, get) : []
|
|
||||||
const edge = (side: 'in' | 'out'): EdgePin[] => {
|
|
||||||
const out: EdgePin[] = []
|
|
||||||
for (const p of plain.ports ?? []) {
|
|
||||||
if (p.side !== side) continue
|
|
||||||
out.push({ dir: side, pin: { key: p.key, label: portName(p, get), bus: true, conn: p.conn } })
|
|
||||||
for (const l of lines) {
|
|
||||||
if (l.port === p.key) out.push({ dir: l.enters ? 'in' : 'out', pin: { key: l.key, label: l.name, face: side === 'in' ? -1 : 1, port: p.key } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (const p of side === 'in' ? plain.inputs : plain.outputs) out.push({ dir: side, pin: p })
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
const left = edge('in')
|
|
||||||
const right = edge('out')
|
|
||||||
const n = Math.max(left.length, right.length, 1)
|
|
||||||
const longest = (ps: EdgePin[]) => ps.reduce((m, p) => Math.max(m, p.pin.label.length), 0)
|
|
||||||
const w = Math.max(
|
const w = Math.max(
|
||||||
3,
|
3,
|
||||||
Math.ceil(longest(left) * LABEL_CHAR + longest(right) * LABEL_CHAR + name.length * NAME_CHAR + 1.5),
|
Math.ceil(longest(pins.inputs) * LABEL_CHAR + longest(pins.outputs) * LABEL_CHAR + name.length * NAME_CHAR + 1.5),
|
||||||
Math.ceil(face.w + 1.2),
|
Math.ceil(face.w + 1.2),
|
||||||
)
|
)
|
||||||
// An edge with ports starts at the top; one of single pins only is centred,
|
|
||||||
// on the box as it is without split lines, so splitting a port never moves it.
|
|
||||||
const unsplit = Math.max(...[left, right].map(ps => ps.filter(p => !p.pin.port).length), 1)
|
|
||||||
const place = (ps: EdgePin[], dx: number) => {
|
|
||||||
const off = ps.some(p => p.pin.bus) ? 0 : Math.floor((unsplit - ps.length) / 2)
|
|
||||||
return ps.map((p, i) => ({ dir: p.dir, pin: { ...p.pin, dx, dy: off + i } }))
|
|
||||||
}
|
|
||||||
// Each edge's own pins first: code that takes the first free input or output finds one on its usual edge.
|
|
||||||
const onLeft = place(left, 0)
|
|
||||||
const onRight = place(right, w)
|
|
||||||
const top = n === 1 ? -1 : -0.5
|
const top = n === 1 ? -1 : -0.5
|
||||||
const pinBottom = n === 1 ? 1 : n - 0.5
|
const pinBottom = n === 1 ? 1 : n - 0.5
|
||||||
const faceTop = pinBottom + 0.2
|
const faceTop = pinBottom + 0.2
|
||||||
const faceLeft = (w - face.w) / 2
|
const faceLeft = (w - face.w) / 2
|
||||||
return {
|
return {
|
||||||
body: { x: 0, y: top, w, h: pinBottom - top + (face.items.length ? face.h + 0.6 : 0) },
|
body: { x: 0, y: top, w, h: pinBottom - top + (face.items.length ? face.h + 0.6 : 0) },
|
||||||
inputs: [...onLeft, ...onRight].filter(p => p.dir === 'in').map(p => p.pin),
|
inputs: pins.inputs.map((p, i) => ({ ...p, dx: 0, dy: inOff + i })),
|
||||||
outputs: [...onRight, ...onLeft].filter(p => p.dir === 'out').map(p => p.pin),
|
outputs: pins.outputs.map((p, i) => ({ ...p, dx: w, dy: outOff + i })),
|
||||||
nameY: (top + pinBottom) / 2,
|
nameY: (top + pinBottom) / 2,
|
||||||
face: face.items.map(it => ({ ...it, x: it.x + faceLeft, y: it.y + faceTop })),
|
face: face.items.map(it => ({ ...it, x: it.x + faceLeft, y: it.y + faceTop })),
|
||||||
}
|
}
|
||||||
|
|
@ -714,36 +508,6 @@ const PIXEL_SHAPE: Shape = {
|
||||||
outputs: [],
|
outputs: [],
|
||||||
}
|
}
|
||||||
|
|
||||||
const PIXEL_RGB_SHAPE: Shape = {
|
|
||||||
body: { x: 0, y: -0.5, w: 1, h: 3 },
|
|
||||||
inputs: [
|
|
||||||
{ key: 'r', label: '', dx: 0, dy: 0 },
|
|
||||||
{ key: 'g', label: '', dx: 0, dy: 1 },
|
|
||||||
{ key: 'b', label: '', dx: 0, dy: 2 },
|
|
||||||
],
|
|
||||||
outputs: [],
|
|
||||||
}
|
|
||||||
|
|
||||||
function displayShape(node: CircuitNode): Shape {
|
|
||||||
const l = displayLayout(node)
|
|
||||||
return { body: { x: 0, y: -0.5, w: l.w, h: l.h }, inputs: displayPins(node).map((p, i) => ({ ...p, dx: 0, dy: i })), outputs: [] }
|
|
||||||
}
|
|
||||||
|
|
||||||
function benchShape(node: CircuitNode): Shape {
|
|
||||||
const l = benchLayout(node)
|
|
||||||
return {
|
|
||||||
body: { x: 0, y: -0.5, w: l.w, h: l.h },
|
|
||||||
inputs: l.left.map((p, i) => ({ key: p.key, label: p.label, dx: 0, dy: i })),
|
|
||||||
outputs: l.right.map((p, i) => ({ key: p.key, label: p.label, dx: l.w, dy: i })),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const KEYBOARD_SHAPE: Shape = {
|
|
||||||
body: { x: 0, y: -0.5, w: 7, h: 9 },
|
|
||||||
inputs: [{ key: 'next', label: 'NEXT', dx: 0, dy: 8 }],
|
|
||||||
outputs: [...DATA_KEYS, 'rdy'].map((key, i) => ({ key, label: DEVICE_PIN_NAMES[key]!, dx: 7, dy: i })),
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Grid offset of every panel row below the first one. */
|
/** Grid offset of every panel row below the first one. */
|
||||||
export function panelOffsets(rows: PanelRow[]): number[] {
|
export function panelOffsets(rows: PanelRow[]): number[] {
|
||||||
const out: number[] = []
|
const out: number[] = []
|
||||||
|
|
@ -784,39 +548,6 @@ export function noteScale(node: CircuitNode): number {
|
||||||
return node.size === 'sm' ? 0.8 : node.size === 'lg' ? 1.5 : 1
|
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>" (9px letters, about a third of a square each).
|
|
||||||
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.34 + 0.8))
|
|
||||||
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 {
|
export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
|
||||||
switch (node.kind) {
|
switch (node.kind) {
|
||||||
case 'nand':
|
case 'nand':
|
||||||
|
|
@ -839,19 +570,7 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
|
||||||
case 'split':
|
case 'split':
|
||||||
return cableShape(node)
|
return cableShape(node)
|
||||||
case 'pixel':
|
case 'pixel':
|
||||||
return node.rgb ? PIXEL_RGB_SHAPE : PIXEL_SHAPE
|
return PIXEL_SHAPE
|
||||||
case 'terminal':
|
|
||||||
case 'monitor':
|
|
||||||
case 'rgbmonitor':
|
|
||||||
return displayShape(node)
|
|
||||||
case 'bench':
|
|
||||||
return benchShape(node)
|
|
||||||
case 'scope': {
|
|
||||||
const l = scopeLayout(node)
|
|
||||||
return { body: { x: 0, y: -0.5, w: l.w, h: l.h }, inputs: l.pins.map(p => ({ key: p.key, label: p.label, dx: 0, dy: p.dy })), outputs: [] }
|
|
||||||
}
|
|
||||||
case 'keyboard':
|
|
||||||
return KEYBOARD_SHAPE
|
|
||||||
case 'outpanel':
|
case 'outpanel':
|
||||||
return outPanelShape(node)
|
return outPanelShape(node)
|
||||||
case 'tag':
|
case 'tag':
|
||||||
|
|
@ -869,21 +588,18 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
|
||||||
if (!def) return MISSING_SHAPE
|
if (!def) return MISSING_SHAPE
|
||||||
const pins = chipPins(def)
|
const pins = chipPins(def)
|
||||||
const face = faceLayout(def)
|
const face = faceLayout(def)
|
||||||
if (def.design) return designedShape(def, pins, face, getDef, node)
|
if (def.design) return designedShape(def, pins, face, getDef)
|
||||||
if (def.symbol !== 'box' && !face.items.length && !pins.ports && pins.outputs.length === 1 && pins.inputs.length >= 1 && pins.inputs.length <= 16) {
|
if (def.symbol !== 'box' && !face.items.length && pins.outputs.length === 1 && pins.inputs.length >= 1 && pins.inputs.length <= 16) {
|
||||||
return gateShape(def.symbol, pins.inputs, pins.outputs[0]!)
|
return gateShape(def.symbol, pins.inputs, pins.outputs[0]!)
|
||||||
}
|
}
|
||||||
return boxShape(def.name, pins, face, getDef, node)
|
return boxShape(def.name, pins, face)
|
||||||
}
|
}
|
||||||
case 'portin':
|
|
||||||
case 'portout':
|
|
||||||
return portShape(node, getDef)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function pinPos(node: CircuitNode, shape: Shape, key: string, dir: 'in' | 'out') {
|
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)
|
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, face: pin.face ?? (dir === 'in' ? -1 : 1) } : undefined
|
return pin ? { x: node.x + pin.dx, y: node.y + pin.dy } : undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Pt = [number, number]
|
export type Pt = [number, number]
|
||||||
|
|
@ -910,7 +626,7 @@ export function simplify(pts: Pt[]): Pt[] {
|
||||||
* wires get one vertical segment halfway; backward wires (feedback loops) go
|
* wires get one vertical segment halfway; backward wires (feedback loops) go
|
||||||
* out to the right, around, and back in from the left.
|
* out to the right, around, and back in from the left.
|
||||||
*/
|
*/
|
||||||
export function routeWire(a: Pt, b: Pt, corners?: Pt[], aFace: 1 | -1 = 1, bFace: 1 | -1 = -1): Pt[] {
|
export function routeWire(a: Pt, b: Pt, corners?: Pt[]): Pt[] {
|
||||||
const [x1, y1] = a
|
const [x1, y1] = a
|
||||||
const [x2, y2] = b
|
const [x2, y2] = b
|
||||||
if (corners?.length) {
|
if (corners?.length) {
|
||||||
|
|
@ -925,13 +641,6 @@ export function routeWire(a: Pt, b: Pt, corners?: Pt[], aFace: 1 | -1 = 1, bFace
|
||||||
out.push(b)
|
out.push(b)
|
||||||
return simplify(out)
|
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 (y1 === y2 && x2 > x1) return [a, b]
|
||||||
if (x2 >= x1 + 1) {
|
if (x2 >= x1 + 1) {
|
||||||
const m = Math.round((x1 + x2) / 2)
|
const m = Math.round((x1 + x2) / 2)
|
||||||
|
|
|
||||||
|
|
@ -2,10 +2,7 @@
|
||||||
// A, B, C), and a switch, lamp or pin without a name of its own takes the
|
// A, B, C), and a switch, lamp or pin without a name of its own takes the
|
||||||
// name of the component pin it is wired to.
|
// name of the component pin it is wired to.
|
||||||
|
|
||||||
import { chipPins, splitLines, type DefLookup } from './geometry'
|
import type { DefLookup } from './geometry'
|
||||||
import { colPinNames } from './benchLayout'
|
|
||||||
import { DEVICE_PIN_NAMES } from './devices'
|
|
||||||
import { displayPins } from './displays'
|
|
||||||
import type { CircuitNode, ComponentDef, NodeKind } from './types'
|
import type { CircuitNode, ComponentDef, NodeKind } from './types'
|
||||||
|
|
||||||
const SERIES = /^(.*?)(\d+)$/
|
const SERIES = /^(.*?)(\d+)$/
|
||||||
|
|
@ -85,18 +82,8 @@ export function pinName(node: CircuitNode, pin: string, get: DefLookup): string
|
||||||
}
|
}
|
||||||
// A wire of a cable carries the name of its signal (the cable pin itself has none).
|
// A wire of a cable carries the name of its signal (the cable pin itself has none).
|
||||||
if (node.kind === 'bundle' || node.kind === 'split') return /^b\d+$/.test(pin) ? node.names?.[Number(pin.slice(1))]?.trim() || undefined : undefined
|
if (node.kind === 'bundle' || node.kind === 'split') return /^b\d+$/.test(pin) ? node.names?.[Number(pin.slice(1))]?.trim() || undefined : undefined
|
||||||
if (node.kind === 'terminal' || node.kind === 'keyboard') return DEVICE_PIN_NAMES[pin]
|
|
||||||
if (node.kind === 'monitor' || node.kind === 'rgbmonitor') return displayPins(node).find(p => p.key === pin)?.label
|
|
||||||
if (node.kind === 'bench' || node.kind === 'scope') {
|
|
||||||
const [id, bit] = pin.split('.')
|
|
||||||
const c = (node.kind === 'bench' ? node.bench?.cols : node.scope?.cols)?.find(x => x.id === id)
|
|
||||||
return c ? colPinNames(c)[Number(bit)] : undefined
|
|
||||||
}
|
|
||||||
if (node.kind !== 'chip' || !node.chip) return undefined
|
if (node.kind !== 'chip' || !node.chip) return undefined
|
||||||
const def = get(node.chip)
|
const def = get(node.chip)
|
||||||
// A line of a port split on the box: port.line, named after the line.
|
|
||||||
const line = def && node.splitPorts?.length ? splitLines(node, chipPins(def), get).find(l => l.key === pin) : undefined
|
|
||||||
if (line) return line.name
|
|
||||||
// A pin made from a panel row: panel:row.
|
// A pin made from a panel row: panel:row.
|
||||||
const at = pin.indexOf(':')
|
const at = pin.indexOf(':')
|
||||||
if (at > 0) {
|
if (at > 0) {
|
||||||
|
|
|
||||||
|
|
@ -1,178 +0,0 @@
|
||||||
// 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) }
|
|
||||||
}
|
|
||||||
|
|
@ -1,372 +0,0 @@
|
||||||
// The public component library: components people published for everyone,
|
|
||||||
// each with every component it uses and the connector types those need.
|
|
||||||
// Publishing sends one component and what it uses (a bundle); adding an
|
|
||||||
// entry to a project brings the bundle in with new ids, and uses what the
|
|
||||||
// project has in exactly that form already. Shared by the browser and the
|
|
||||||
// library server, so it must stay free of browser APIs.
|
|
||||||
|
|
||||||
import { nandCounts, TRANSISTORS_PER_NAND } from './analyze'
|
|
||||||
import { CHALLENGES } from './challenges'
|
|
||||||
import { MAX_DEPTH } from './compile'
|
|
||||||
import { chipPins, type DefLookup } from './geometry'
|
|
||||||
import { containsDef, lookup, uid, uniqueName } from './ops'
|
|
||||||
import { isCampaign, KIND_NAMES } from './progress'
|
|
||||||
import { toProject } from './project'
|
|
||||||
import type { ComponentDef, ConnectorType, LibraryOrigin, Project } from './types'
|
|
||||||
import { NAND_BASE } from './wide'
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Upper bounds for a published component: the request, its name,
|
|
||||||
* description and group, and the pin names the listing shows (how many per
|
|
||||||
* side, how long each).
|
|
||||||
*/
|
|
||||||
export const LIBRARY_LIMITS = { bytes: 1_000_000, name: 60, description: 400, group: 40, pinNames: 16, pinName: 24 }
|
|
||||||
|
|
||||||
/** What gets published: a component (`root`) and everything it uses, used ones first, with their connector types. */
|
|
||||||
export interface LibraryBundle {
|
|
||||||
root: string
|
|
||||||
components: ComponentDef[]
|
|
||||||
connectors?: ConnectorType[]
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A library entry as it is listed: what it is, who published it, what it takes. */
|
|
||||||
export interface LibraryMeta {
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
description: string
|
|
||||||
group: string
|
|
||||||
/** The publisher's leaderboard name; empty for anonymous. */
|
|
||||||
author: string
|
|
||||||
version: number
|
|
||||||
created: number
|
|
||||||
updated: number
|
|
||||||
/** Transistors at every depth, 4 per NAND. */
|
|
||||||
transistors: number
|
|
||||||
/** Pins on each side. */
|
|
||||||
inputs: number
|
|
||||||
outputs: number
|
|
||||||
/** Names of the first pins on each side, top to bottom, shortened. */
|
|
||||||
inNames: string[]
|
|
||||||
outNames: string[]
|
|
||||||
/** Components it uses, at every depth; they come along. */
|
|
||||||
uses: number
|
|
||||||
/** Connector types that come along. */
|
|
||||||
connectors: number
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Deep copy that also works on Vue reactive proxies (structuredClone does not). */
|
|
||||||
function clone<T>(value: T): T {
|
|
||||||
return JSON.parse(JSON.stringify(value)) as T
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A component and every component it uses, at every depth, each once: the
|
|
||||||
* used ones before the ones that use them, the component itself last. A
|
|
||||||
* component that contains itself is not followed round again.
|
|
||||||
*/
|
|
||||||
export function closure(get: DefLookup, defId: string): ComponentDef[] {
|
|
||||||
const out: ComponentDef[] = []
|
|
||||||
const seen = new Set<string>()
|
|
||||||
const visit = (id: string) => {
|
|
||||||
if (seen.has(id)) return
|
|
||||||
seen.add(id)
|
|
||||||
const def = get(id)
|
|
||||||
if (!def) return
|
|
||||||
for (const n of def.nodes) if (n.kind === 'chip' && n.chip) visit(n.chip)
|
|
||||||
if (def.wide && def.wide.base !== NAND_BASE) visit(def.wide.base)
|
|
||||||
out.push(def)
|
|
||||||
}
|
|
||||||
visit(defId)
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Connector types the ports of these components use, in the project's order. */
|
|
||||||
function connectorsUsed(connectors: ConnectorType[] | undefined, defs: ComponentDef[]): ConnectorType[] {
|
|
||||||
const used = new Set(defs.flatMap(d => d.nodes.filter(n => (n.kind === 'portin' || n.kind === 'portout') && n.conn).map(n => n.conn!)))
|
|
||||||
return (connectors ?? []).filter(c => used.has(c.id))
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Why a component can't go to the library, in words; null when it can.
|
|
||||||
* Challenges and puzzles stay private, so nobody gets the answer: neither
|
|
||||||
* a challenge circuit itself nor a solution used anywhere inside it.
|
|
||||||
*/
|
|
||||||
export function publishProblem(project: Project, defId: string): string | null {
|
|
||||||
const get = lookup(project)
|
|
||||||
const def = get(defId)
|
|
||||||
if (!def) return 'Circuit not found'
|
|
||||||
if (def.challenge) return 'Challenges and puzzles stay private, so nobody gets the answer'
|
|
||||||
if (!def.nodes.length) return 'There is nothing in it yet'
|
|
||||||
const solution = closure(get, defId).find(d => d.challenge)
|
|
||||||
if (solution) return `It uses your solution to the ${CHALLENGES.some(c => c.id === solution.challenge) ? 'challenge' : 'puzzle'} "${solution.name}", which stays private`
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Why library entries can't be added to a project, in words; null when they
|
|
||||||
* can. A campaign is earned part by part, and a part from the library could
|
|
||||||
* be copied or taken apart into a solution, so a campaign takes none.
|
|
||||||
*/
|
|
||||||
export function importProblem(project: Project): string | null {
|
|
||||||
return isCampaign(project) ? 'A campaign is built from your own work: add library components to another project' : null
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The library entry a component is when this browser published it, from
|
|
||||||
* this very project and component; its key is in `keys`. The component's
|
|
||||||
* own mark never counts for this, since marks come along in files and links.
|
|
||||||
*/
|
|
||||||
export function ownedEntry(keys: Record<string, { project: string; def: string }>, projectId: string, defId: string): string | undefined {
|
|
||||||
return Object.entries(keys).find(([, k]) => k.project === projectId && k.def === defId)?.[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What publishing a component sends: copies of it and of what it uses,
|
|
||||||
* without challenge or library marks, and their connector types.
|
|
||||||
*/
|
|
||||||
export function libraryBundle(project: Project, defId: string): LibraryBundle {
|
|
||||||
const components = clone(closure(lookup(project), defId))
|
|
||||||
for (const d of components) {
|
|
||||||
delete d.challenge
|
|
||||||
delete d.from
|
|
||||||
}
|
|
||||||
const connectors = clone(connectorsUsed(project.connectors, components))
|
|
||||||
return { root: defId, components, ...(connectors.length ? { connectors } : {}) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Parts a published component may have at every depth, so whoever adds it can still run it. */
|
|
||||||
export const MAX_FLAT_PARTS = 10_000_000
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What the simulator would refuse in a component, or choke on: a component
|
|
||||||
* inside that is missing, one that contains itself, nesting too deep, or
|
|
||||||
* too many parts once every component inside is opened up. Found by looking
|
|
||||||
* at each component once, never by building the whole circuit, so a part
|
|
||||||
* made to be huge costs no more to check than a small one.
|
|
||||||
*/
|
|
||||||
function nestingProblem(get: DefLookup, rootId: string): string | null {
|
|
||||||
const seen = new Map<string, { depth: number; parts: number }>()
|
|
||||||
const busy = new Set<string>()
|
|
||||||
let problem: string | null = null
|
|
||||||
const visit = (def: ComponentDef): { depth: number; parts: number } => {
|
|
||||||
const known = seen.get(def.id)
|
|
||||||
if (known) return known
|
|
||||||
busy.add(def.id)
|
|
||||||
const size = { depth: 1, parts: 0 }
|
|
||||||
for (const n of def.nodes) {
|
|
||||||
const child = n.kind === 'chip' && n.chip ? get(n.chip) : undefined
|
|
||||||
if (n.kind !== 'chip') size.parts++
|
|
||||||
else if (!child) problem ??= `Missing component in "${def.name}"`
|
|
||||||
else if (busy.has(child.id)) problem ??= `"${child.name}" contains itself`
|
|
||||||
else {
|
|
||||||
const inner = visit(child)
|
|
||||||
size.depth = Math.max(size.depth, 1 + inner.depth)
|
|
||||||
size.parts += inner.parts
|
|
||||||
}
|
|
||||||
}
|
|
||||||
busy.delete(def.id)
|
|
||||||
seen.set(def.id, size)
|
|
||||||
return size
|
|
||||||
}
|
|
||||||
const size = visit(get(rootId)!)
|
|
||||||
if (size.depth > MAX_DEPTH) problem ??= `Nesting deeper than ${MAX_DEPTH} levels`
|
|
||||||
if (size.parts > MAX_FLAT_PARTS) problem ??= `Too large to run: over ${MAX_FLAT_PARTS.toLocaleString('en')} parts with everything inside opened up`
|
|
||||||
return problem
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Every kind of node there is: the built-in parts and components. */
|
|
||||||
const KINDS = new Set<string>([...Object.keys(KIND_NAMES), 'chip'])
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Checks a bundle from outside with the same checks as any project, plus
|
|
||||||
* the ones a part from a stranger needs: every node and wire well formed,
|
|
||||||
* nothing missing, nothing inside itself, nothing too big to run. Keeps only
|
|
||||||
* the component and what it uses, and drops challenge and library marks:
|
|
||||||
* an entry's components are marked when they are added, never by whoever
|
|
||||||
* published them. Throws with a readable message.
|
|
||||||
*/
|
|
||||||
export function cleanBundle(raw: unknown): LibraryBundle {
|
|
||||||
const b = raw as Partial<LibraryBundle>
|
|
||||||
if (!b || typeof b !== 'object' || typeof b.root !== 'string') throw new Error('Not a component for the library')
|
|
||||||
const p = toProject({ name: 'Library', components: b.components, connectors: b.connectors, openId: b.root })
|
|
||||||
for (const d of p.components) {
|
|
||||||
const broken = () => new Error(`"${d.name}" is broken`)
|
|
||||||
for (const n of d.nodes) {
|
|
||||||
if (!n || typeof n.id !== 'string' || !KINDS.has(n.kind) || !Number.isFinite(n.x) || !Number.isFinite(n.y)) throw broken()
|
|
||||||
if (n.label !== undefined && typeof n.label !== 'string') delete n.label
|
|
||||||
}
|
|
||||||
for (const w of d.wires) {
|
|
||||||
if (!w || typeof w.id !== 'string' || [w.from, w.to].some(r => !r || typeof r.node !== 'string' || typeof r.pin !== 'string')) throw broken()
|
|
||||||
}
|
|
||||||
for (const k of ['description', 'group'] as const) if (d[k] !== undefined && typeof d[k] !== 'string') delete d[k]
|
|
||||||
}
|
|
||||||
const get = lookup(p)
|
|
||||||
const root = get(b.root)
|
|
||||||
if (!root) throw new Error('The component itself is missing')
|
|
||||||
const problem = nestingProblem(get, root.id)
|
|
||||||
if (problem) throw new Error(problem)
|
|
||||||
const components = closure(get, root.id)
|
|
||||||
for (const d of components) {
|
|
||||||
delete d.challenge
|
|
||||||
delete d.from
|
|
||||||
}
|
|
||||||
root.name = root.name.trim().slice(0, LIBRARY_LIMITS.name) || 'Component'
|
|
||||||
if (root.description !== undefined) root.description = root.description.trim().slice(0, LIBRARY_LIMITS.description)
|
|
||||||
if (root.group !== undefined) root.group = root.group.trim().slice(0, LIBRARY_LIMITS.group)
|
|
||||||
const connectors = connectorsUsed(p.connectors, components)
|
|
||||||
return { root: root.id, components, ...(connectors.length ? { connectors } : {}) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What the listing says about a cleaned bundle, counted from the circuit
|
|
||||||
* itself so it can be trusted. Small whatever was sent: every entry's
|
|
||||||
* listing is read on each visit to the library.
|
|
||||||
*/
|
|
||||||
export function describeBundle(b: LibraryBundle): Pick<LibraryMeta, 'name' | 'description' | 'group' | 'transistors' | 'inputs' | 'outputs' | 'inNames' | 'outNames' | 'uses' | 'connectors'> {
|
|
||||||
const root = b.components.find(d => d.id === b.root)
|
|
||||||
if (!root) throw new Error('The component itself is missing')
|
|
||||||
const pins = chipPins(root)
|
|
||||||
const names = (list: { label: string }[]) => list.slice(0, LIBRARY_LIMITS.pinNames).map(p => p.label.slice(0, LIBRARY_LIMITS.pinName))
|
|
||||||
return {
|
|
||||||
name: root.name.slice(0, LIBRARY_LIMITS.name),
|
|
||||||
description: (root.description ?? '').slice(0, LIBRARY_LIMITS.description),
|
|
||||||
group: (root.group ?? '').slice(0, LIBRARY_LIMITS.group),
|
|
||||||
transistors: (nandCounts(b.components).get(root.id) ?? 0) * TRANSISTORS_PER_NAND,
|
|
||||||
inputs: pins.inputs.length,
|
|
||||||
outputs: pins.outputs.length,
|
|
||||||
inNames: names(pins.inputs),
|
|
||||||
outNames: names(pins.outputs),
|
|
||||||
uses: b.components.length - 1,
|
|
||||||
connectors: b.connectors?.length ?? 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** JSON with object keys sorted, so the same data always gives the same text. */
|
|
||||||
function canon(value: unknown): string {
|
|
||||||
return JSON.stringify(value, (_, v) =>
|
|
||||||
v && typeof v === 'object' && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) : v,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** What a component is, apart from its id, name, texts and marks: the same for two copies of one thing. */
|
|
||||||
const form = (d: ComponentDef) => canon({ symbol: d.symbol, face: d.face, wide: d.wide, design: d.design, nodes: d.nodes, wires: d.wires })
|
|
||||||
|
|
||||||
const sameLines = (a: ConnectorType, b: ConnectorType) => canon(a.lines.map(l => [l.name, !!l.back])) === canon(b.lines.map(l => [l.name, !!l.back]))
|
|
||||||
|
|
||||||
/** Parts of a component that an update replaces; its name and group stay as they are here. */
|
|
||||||
const CONTENT = ['symbol', 'description', 'face', 'wide', 'design', 'nodes', 'wires'] as const
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Adds a library entry to a project. What the project has in exactly this
|
|
||||||
* form already (an earlier import, the examples) is used as it is; the rest
|
|
||||||
* comes in with new ids, and with a number after its name when the name is
|
|
||||||
* taken. A connector type joins the project's type of the same id or name
|
|
||||||
* when their lines match, and comes in as a new type otherwise. The entry's
|
|
||||||
* component is marked with where it came from; the ones it uses are marked
|
|
||||||
* as having come along.
|
|
||||||
*
|
|
||||||
* With `replace` (a component here from the same entry), that component
|
|
||||||
* takes the entry's new version instead, so every place it is used follows.
|
|
||||||
* What came along with the old version and is used nowhere else any more
|
|
||||||
* goes, and the parts that replace it take its names.
|
|
||||||
* Returns the id of the entry's component here and how many were added.
|
|
||||||
*/
|
|
||||||
export function importBundle(project: Project, bundle: LibraryBundle, origin: LibraryOrigin, replace?: string): { root: string; added: number } {
|
|
||||||
const conns = new Map<string, string>()
|
|
||||||
for (const c of bundle.connectors ?? []) {
|
|
||||||
const have = project.connectors ?? []
|
|
||||||
const same = have.find(h => (h.id === c.id || h.name.toLowerCase() === c.name.toLowerCase()) && sameLines(h, c))
|
|
||||||
if (same) {
|
|
||||||
conns.set(c.id, same.id)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const copy = clone(c)
|
|
||||||
if (have.some(h => h.id === copy.id)) copy.id = uid('k')
|
|
||||||
const names = new Set(have.map(h => h.name.toLowerCase()))
|
|
||||||
for (let i = 2; names.has(copy.name.toLowerCase()); i++) copy.name = `${c.name} ${i}`
|
|
||||||
project.connectors = [...have, copy]
|
|
||||||
conns.set(c.id, copy.id)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Components already here, by form. Not challenge attempts, which are
|
|
||||||
// still being worked on; not another entry's component, which a newer
|
|
||||||
// version of that entry would change under this one; nor anything that
|
|
||||||
// contains the one being replaced, or it would end up inside itself.
|
|
||||||
const forms = new Map<string, string>()
|
|
||||||
for (const d of project.components) {
|
|
||||||
if (d.challenge || (d.from && !d.from.inside && d.from.id !== origin.id) || (replace && containsDef(project, d.id, replace))) continue
|
|
||||||
const k = form(d)
|
|
||||||
if (!forms.has(k)) forms.set(k, d.id)
|
|
||||||
}
|
|
||||||
const target = replace ? project.components.find(d => d.id === replace) : undefined
|
|
||||||
// What came along with the version being replaced.
|
|
||||||
const before = target ? closure(lookup(project), target.id).filter(d => d.from?.inside && d.from.id === origin.id) : []
|
|
||||||
const byId = new Map(bundle.components.map(d => [d.id, d]))
|
|
||||||
const ids = new Map<string, string>()
|
|
||||||
const fresh: { def: ComponentDef; name: string }[] = []
|
|
||||||
let root = ''
|
|
||||||
let added = 0
|
|
||||||
for (const d of closure(id => byId.get(id), bundle.root)) {
|
|
||||||
const copy = clone(d)
|
|
||||||
for (const n of copy.nodes) {
|
|
||||||
if (n.kind === 'chip' && n.chip) n.chip = ids.get(n.chip) ?? n.chip
|
|
||||||
if (n.conn) n.conn = conns.get(n.conn) ?? n.conn
|
|
||||||
}
|
|
||||||
if (copy.wide && copy.wide.base !== NAND_BASE) copy.wide.base = ids.get(copy.wide.base) ?? copy.wide.base
|
|
||||||
delete copy.challenge
|
|
||||||
const isRoot = d.id === bundle.root
|
|
||||||
copy.from = isRoot ? { ...origin } : { ...origin, inside: true }
|
|
||||||
|
|
||||||
if (isRoot && target) {
|
|
||||||
const t = target as unknown as Record<string, unknown>
|
|
||||||
for (const k of CONTENT) {
|
|
||||||
if (copy[k] === undefined) delete t[k]
|
|
||||||
else t[k] = copy[k]
|
|
||||||
}
|
|
||||||
target.from = copy.from
|
|
||||||
delete target.challenge
|
|
||||||
ids.set(d.id, target.id)
|
|
||||||
root = target.id
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const same = forms.get(form(copy))
|
|
||||||
if (same) {
|
|
||||||
ids.set(d.id, same)
|
|
||||||
// The same entry again, unchanged: it now counts as the newer version.
|
|
||||||
const have = project.components.find(x => x.id === same)!
|
|
||||||
if (have.from?.id === copy.from.id && (isRoot ? !have.from.inside : have.from.inside)) have.from = copy.from
|
|
||||||
if (isRoot) root = same
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
copy.id = uid('c')
|
|
||||||
while (project.components.some(x => x.id === copy.id)) copy.id = uid('c')
|
|
||||||
copy.name = uniqueName(project, copy.name)
|
|
||||||
project.components.push(copy)
|
|
||||||
forms.set(form(copy), copy.id)
|
|
||||||
ids.set(d.id, copy.id)
|
|
||||||
fresh.push({ def: copy, name: d.name })
|
|
||||||
added++
|
|
||||||
if (isRoot) root = copy.id
|
|
||||||
}
|
|
||||||
if (target) {
|
|
||||||
dropUnused(project, before)
|
|
||||||
for (const f of fresh) if (f.def.name !== f.name && !project.components.some(x => x.name.toLowerCase() === f.name.toLowerCase())) f.def.name = f.name
|
|
||||||
}
|
|
||||||
return { root, added }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Removes those of these components that nothing uses (or has open), and then those only they used. */
|
|
||||||
function dropUnused(project: Project, defs: ComponentDef[]) {
|
|
||||||
const left = new Set(defs.map(d => d.id))
|
|
||||||
const used = (id: string) =>
|
|
||||||
id === project.openId || project.components.some(d => d.id !== id && (d.wide?.base === id || d.nodes.some(n => n.kind === 'chip' && n.chip === id)))
|
|
||||||
for (let gone = true; gone; ) {
|
|
||||||
gone = false
|
|
||||||
for (const id of left) {
|
|
||||||
if (used(id)) continue
|
|
||||||
project.components = project.components.filter(d => d.id !== id)
|
|
||||||
left.delete(id)
|
|
||||||
gone = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,65 +0,0 @@
|
||||||
// Moving parts by whole squares, the same way for a drag and for the arrow
|
|
||||||
// keys. A drag moves from where the parts started on every step, so what
|
|
||||||
// shows while dragging is what stays when the parts are let go. Wires come
|
|
||||||
// along: one between two moved parts keeps its shape, the hand-placed
|
|
||||||
// corners of the others are looked at again (routing.ts, settleCorners).
|
|
||||||
|
|
||||||
import type { Pt, Shape } from './geometry'
|
|
||||||
import { settleCorners, type RouteOptions } from './routing'
|
|
||||||
import type { ComponentDef } from './types'
|
|
||||||
|
|
||||||
/** Where the moving parts and the wires' corners were when the move started. */
|
|
||||||
export interface MoveStart {
|
|
||||||
/** Parts that move (followers included), where they were. */
|
|
||||||
nodes: Map<string, Pt>
|
|
||||||
/** Corners of every wire that has hand-placed ones. */
|
|
||||||
pts: Map<string, Pt[]>
|
|
||||||
/** Wires picked along with the parts. */
|
|
||||||
wires: Set<string>
|
|
||||||
}
|
|
||||||
|
|
||||||
export function moveStart(def: ComponentDef, ids: Set<string>, wires: Iterable<string> = []): MoveStart {
|
|
||||||
const nodes = new Map<string, Pt>()
|
|
||||||
for (const n of def.nodes) {
|
|
||||||
if (!ids.has(n.id)) continue
|
|
||||||
nodes.set(n.id, [n.x, n.y])
|
|
||||||
}
|
|
||||||
const pts = new Map<string, Pt[]>()
|
|
||||||
for (const w of def.wires) if (w.pts) pts.set(w.id, w.pts.map(p => [p[0], p[1]] as Pt))
|
|
||||||
return { nodes, pts, wires: new Set(wires) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Puts the moving parts `dx`, `dy` squares from where they started. A wire
|
|
||||||
* whose ends both moved the same way takes its corners along, and so does a
|
|
||||||
* picked wire whose ends both stay (a wire moved on its own goes where it is
|
|
||||||
* put). Every other wire starts again from the corners it had, and keeps
|
|
||||||
* those that still leave it a clear way.
|
|
||||||
*/
|
|
||||||
export function moveParts(def: ComponentDef, start: MoveStart, dx: number, dy: number, shapes: Map<string, Shape>, opts: RouteOptions = {}) {
|
|
||||||
const by = new Map<string, Pt>()
|
|
||||||
for (const n of def.nodes) {
|
|
||||||
const at = start.nodes.get(n.id)
|
|
||||||
if (!at) continue
|
|
||||||
const step: Pt = [dx, dy]
|
|
||||||
n.x = at[0] + step[0]
|
|
||||||
n.y = at[1] + step[1]
|
|
||||||
if (step[0] || step[1]) by.set(n.id, step)
|
|
||||||
}
|
|
||||||
const carried = new Set<string>()
|
|
||||||
for (const w of def.wires) {
|
|
||||||
const pts = start.pts.get(w.id)
|
|
||||||
if (!pts) continue
|
|
||||||
const a = by.get(w.from.node)
|
|
||||||
const b = by.get(w.to.node)
|
|
||||||
const step = a && b && a[0] === b[0] && a[1] === b[1] ? a : !a && !b && start.wires.has(w.id) ? ([dx, dy] as Pt) : undefined
|
|
||||||
w.pts = pts.map(([x, y]) => (step ? [x + step[0], y + step[1]] : [x, y]))
|
|
||||||
if (step) carried.add(w.id)
|
|
||||||
}
|
|
||||||
const byId = new Map(def.wires.map(w => [w.id, w]))
|
|
||||||
for (const [id, pts] of settleCorners(def, shapes, { by, carried }, opts)) {
|
|
||||||
const w = byId.get(id)!
|
|
||||||
if (pts) w.pts = pts
|
|
||||||
else delete w.pts
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -4,7 +4,7 @@
|
||||||
import type { Challenge } from './challenges'
|
import type { Challenge } from './challenges'
|
||||||
import { inputKeys, outputKeys } from './compile'
|
import { inputKeys, outputKeys } from './compile'
|
||||||
import { exampleLibrary, starterCircuit } from './examples'
|
import { exampleLibrary, starterCircuit } from './examples'
|
||||||
import { chipPins, linePin, shapeOf, splitLines, type DefLookup } from './geometry'
|
import { chipPins, shapeOf, type DefLookup } from './geometry'
|
||||||
import type { CircuitNode, ComponentDef, NodeKind, Project, PuzzleSpec, Wire } from './types'
|
import type { CircuitNode, ComponentDef, NodeKind, Project, PuzzleSpec, Wire } from './types'
|
||||||
|
|
||||||
export function uid(prefix = ''): string {
|
export function uid(prefix = ''): string {
|
||||||
|
|
@ -18,10 +18,7 @@ function clone<T>(value: T): T {
|
||||||
|
|
||||||
export function lookup(project: Project): DefLookup {
|
export function lookup(project: Project): DefLookup {
|
||||||
const map = new Map(project.components.map(d => [d.id, d]))
|
const map = new Map(project.components.map(d => [d.id, d]))
|
||||||
const conns = new Map((project.connectors ?? []).map(c => [c.id, c]))
|
return id => map.get(id)
|
||||||
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 {
|
export function createProject(opts: { examples: boolean; name?: string; campaign?: boolean }): Project {
|
||||||
|
|
@ -160,7 +157,6 @@ export function duplicateComponent(project: Project, id: string): ComponentDef |
|
||||||
if (!src) return undefined
|
if (!src) return undefined
|
||||||
const copy: ComponentDef = { ...clone(src), id: uid('c'), name: uniqueName(project, `${src.name} copy`) }
|
const copy: ComponentDef = { ...clone(src), id: uid('c'), name: uniqueName(project, `${src.name} copy`) }
|
||||||
delete copy.challenge
|
delete copy.challenge
|
||||||
delete copy.from
|
|
||||||
project.components.push(copy)
|
project.components.push(copy)
|
||||||
return copy
|
return copy
|
||||||
}
|
}
|
||||||
|
|
@ -185,16 +181,10 @@ export function pruneWires(project: Project): boolean {
|
||||||
for (const def of project.components) {
|
for (const def of project.components) {
|
||||||
const ins = new Set<string>()
|
const ins = new Set<string>()
|
||||||
const outs = 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) {
|
for (const n of def.nodes) {
|
||||||
const pins = n.kind === 'chip' && n.chip && get(n.chip) ? chipPins(get(n.chip)!) : undefined
|
const pins = n.kind === 'chip' && n.chip && get(n.chip) ? chipPins(get(n.chip)!) : undefined
|
||||||
for (const k of inputKeys(n, pins, get)) ins.add(`${n.id}:${k}`)
|
for (const k of inputKeys(n, pins)) ins.add(`${n.id}:${k}`)
|
||||||
for (const k of outputKeys(n, pins, get)) outs.add(`${n.id}:${k}`)
|
for (const k of outputKeys(n, pins)) 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 taken = new Set<string>()
|
||||||
const kept: Wire[] = []
|
const kept: Wire[] = []
|
||||||
|
|
@ -202,10 +192,6 @@ export function pruneWires(project: Project): boolean {
|
||||||
const w = def.wires[i]!
|
const w = def.wires[i]!
|
||||||
const to = `${w.to.node}:${w.to.pin}`
|
const to = `${w.to.node}:${w.to.pin}`
|
||||||
if (!ins.has(to) || !outs.has(`${w.from.node}:${w.from.pin}`) || taken.has(to)) continue
|
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)
|
taken.add(to)
|
||||||
kept.push(w)
|
kept.push(w)
|
||||||
}
|
}
|
||||||
|
|
@ -251,18 +237,15 @@ export function pasteClip(def: ComponentDef, clip: Clip, dx: number, dy: number)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Copied panels dock to the copy of their component, copied cable ends plug
|
* Copied panels dock to the copy of their component, and copied cable ends
|
||||||
* into the copy of their part and copied latched parts latch onto the copy of
|
* plug into the copy of their part, or to nothing when it was not copied along.
|
||||||
* theirs, or to nothing when it was not copied along.
|
|
||||||
*/
|
*/
|
||||||
function redock(nodes: CircuitNode[], ids: Map<string, string>) {
|
function redock(nodes: CircuitNode[], ids: Map<string, string>) {
|
||||||
for (const n of nodes) {
|
for (const n of nodes) {
|
||||||
for (const k of ['plug', 'latch'] as const) {
|
if (n.plug) {
|
||||||
const was = n[k]
|
const to = ids.get(n.plug)
|
||||||
if (!was) continue
|
if (to) n.plug = to
|
||||||
const to = ids.get(was)
|
else delete n.plug
|
||||||
if (to) n[k] = to
|
|
||||||
else delete n[k]
|
|
||||||
}
|
}
|
||||||
if (!n.attach) continue
|
if (!n.attach) continue
|
||||||
const to = ids.get(n.attach)
|
const to = ids.get(n.attach)
|
||||||
|
|
@ -395,7 +378,7 @@ export const SINK_KINDS: NodeKind[] = ['output', 'lamp', 'hex']
|
||||||
export function pinKeys(node: CircuitNode, get: DefLookup): { ins: string[]; outs: string[] } {
|
export function pinKeys(node: CircuitNode, get: DefLookup): { ins: string[]; outs: string[] } {
|
||||||
const def = node.kind === 'chip' && node.chip ? get(node.chip) : undefined
|
const def = node.kind === 'chip' && node.chip ? get(node.chip) : undefined
|
||||||
const pins = def ? chipPins(def) : undefined
|
const pins = def ? chipPins(def) : undefined
|
||||||
return { ins: inputKeys(node, pins, get), outs: outputKeys(node, pins, get) }
|
return { ins: inputKeys(node, pins), outs: outputKeys(node, pins) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -440,52 +423,9 @@ export function swapNode(project: Project, def: ComponentDef, nodeId: string, ta
|
||||||
if (target.kind !== 'input' && target.kind !== 'button') delete node.key
|
if (target.kind !== 'input' && target.kind !== 'button') delete node.key
|
||||||
if (target.kind !== 'lamp' && target.kind !== 'hex') delete node.color
|
if (target.kind !== 'lamp' && target.kind !== 'hex') delete node.color
|
||||||
if (target.kind !== 'note') delete node.size
|
if (target.kind !== 'note') delete node.size
|
||||||
if (target.kind !== 'chip') delete node.splitPorts
|
|
||||||
return removed
|
return removed
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Shows a port of a placed component split into a pin per line below its
|
|
||||||
* socket, to wire lines by hand, or joined into the socket alone again.
|
|
||||||
* Joining removes the wires on its lines; returns how many.
|
|
||||||
*/
|
|
||||||
export function splitPort(project: Project, def: ComponentDef, nodeId: string, port: string, split: boolean): number {
|
|
||||||
const get = lookup(project)
|
|
||||||
const node = def.nodes.find(n => n.id === nodeId)
|
|
||||||
const child = node?.kind === 'chip' && node.chip ? get(node.chip) : undefined
|
|
||||||
if (!node || !child || !chipPins(child).ports?.some(p => p.key === port)) return 0
|
|
||||||
const ports = new Set(node.splitPorts ?? [])
|
|
||||||
if (split) ports.add(port)
|
|
||||||
else ports.delete(port)
|
|
||||||
if (ports.size) node.splitPorts = [...ports]
|
|
||||||
else delete node.splitPorts
|
|
||||||
// The lines' pins are gone, and so are the wires on them.
|
|
||||||
const before = def.wires.length
|
|
||||||
pruneWires(project)
|
|
||||||
return before - def.wires.length
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The line of a component's port a single wire takes when dropped on its
|
|
||||||
* socket: the first free one going into the component (`enters`, for a wire
|
|
||||||
* from an output), or coming out of it (for a wire to an input; every line
|
|
||||||
* can feed more wires, an unused one first). Null when no line runs that way,
|
|
||||||
* and for lines going in while a cable is in the socket: the cable feeds them.
|
|
||||||
*/
|
|
||||||
export function lineForWire(project: Project, def: ComponentDef, nodeId: string, port: string, enters: boolean): string | null {
|
|
||||||
const get = lookup(project)
|
|
||||||
const node = def.nodes.find(n => n.id === nodeId)
|
|
||||||
const child = node?.kind === 'chip' && node.chip ? get(node.chip) : undefined
|
|
||||||
if (!node || !child) return null
|
|
||||||
const into = new Set(def.wires.filter(w => w.to.node === nodeId).map(w => w.to.pin))
|
|
||||||
const from = new Set(def.wires.filter(w => w.from.node === nodeId).map(w => w.from.pin))
|
|
||||||
// A wire on a line the cable feeds would drive it against the cable.
|
|
||||||
if (enters && (into.has(port) || from.has(port))) return null
|
|
||||||
const lines = splitLines({ ...node, splitPorts: [port] }, chipPins(child), get).filter(l => l.enters === enters)
|
|
||||||
const used = enters ? into : from
|
|
||||||
return (lines.find(l => !used.has(l.key)) ?? (enters ? undefined : lines[0]))?.key ?? null
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Removes every wire attached to the given parts. Returns how many. A cable
|
* Removes every wire attached to the given parts. Returns how many. A cable
|
||||||
* (bundle to split) is part of the cable, not a connection: it stays, only
|
* (bundle to split) is part of the cable, not a connection: it stays, only
|
||||||
|
|
@ -502,10 +442,9 @@ export function unlinkWires(def: ComponentDef, ids: Set<string>): number {
|
||||||
/**
|
/**
|
||||||
* Replaces a placed component with the parts inside it (the reverse of
|
* Replaces a placed component with the parts inside it (the reverse of
|
||||||
* "Make component"). Its pins disappear: outside wires are joined straight
|
* "Make component"). Its pins disappear: outside wires are joined straight
|
||||||
* to the parts they reached inside, the lines of split ports too. Returns
|
* to the parts they reached inside. Returns the ids of the new parts.
|
||||||
* the ids of the new parts, and how many wires on lines had nowhere to go.
|
|
||||||
*/
|
*/
|
||||||
export function unpackChip(project: Project, defId: string, nodeId: string): { ok: true; nodes: string[]; dropped: number } | { ok: false; error: string } {
|
export function unpackChip(project: Project, defId: string, nodeId: string): { ok: true; nodes: string[] } | { ok: false; error: string } {
|
||||||
const get = lookup(project)
|
const get = lookup(project)
|
||||||
const def = get(defId)
|
const def = get(defId)
|
||||||
const chip = def?.nodes.find(n => n.id === nodeId)
|
const chip = def?.nodes.find(n => n.id === nodeId)
|
||||||
|
|
@ -529,21 +468,8 @@ export function unpackChip(project: Project, defId: string, nodeId: string): { o
|
||||||
const kindOf = new Map(child.nodes.map(n => [n.id, n.kind]))
|
const kindOf = new Map(child.nodes.map(n => [n.id, n.kind]))
|
||||||
const feed = new Map<string, Wire['from']>()
|
const feed = new Map<string, Wire['from']>()
|
||||||
for (const w of def.wires) if (w.to.node === chip.id) feed.set(w.to.pin, w.from)
|
for (const w of def.wires) if (w.to.node === chip.id) feed.set(w.to.pin, w.from)
|
||||||
// Lines of split ports on the box, and those whose wires found a place.
|
const resolve = (ref: Wire['from']): Wire['from'] | undefined =>
|
||||||
const lines = new Map(splitLines(chip, chipPins(child), get).map(l => [l.key, l]))
|
kindOf.get(ref.node) === 'input' ? feed.get(ref.node) : ids.has(ref.node) ? { node: ids.get(ref.node)!, pin: ref.pin } : undefined
|
||||||
const carried = new Set<string>()
|
|
||||||
const resolve = (ref: Wire['from']): Wire['from'] | undefined => {
|
|
||||||
if (kindOf.get(ref.node) === 'input') return feed.get(ref.node)
|
|
||||||
// A line of a port going in: what was wired into it on the box, if anything.
|
|
||||||
const port = kindOf.get(ref.node) === 'portin' || kindOf.get(ref.node) === 'portout'
|
|
||||||
const line = linePin(ref.node, ref.pin)
|
|
||||||
const hand = port ? feed.get(line) : undefined
|
|
||||||
if (hand) {
|
|
||||||
carried.add(line)
|
|
||||||
return hand
|
|
||||||
}
|
|
||||||
return ids.has(ref.node) ? { node: ids.get(ref.node)!, pin: ref.pin } : undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
const added: Wire[] = []
|
const added: Wire[] = []
|
||||||
for (const w of child.wires) {
|
for (const w of child.wires) {
|
||||||
|
|
@ -551,25 +477,20 @@ export function unpackChip(project: Project, defId: string, nodeId: string): { o
|
||||||
const from = resolve(w.from)
|
const from = resolve(w.from)
|
||||||
if (!from) continue
|
if (!from) continue
|
||||||
const wire: Wire = { id: uid('w'), from, to: { node: ids.get(w.to.node)!, pin: w.to.pin } }
|
const wire: Wire = { id: uid('w'), from, to: { node: ids.get(w.to.node)!, pin: w.to.pin } }
|
||||||
if (from.node === ids.get(w.from.node) && w.pts) wire.pts = w.pts.map(([x, y]) => [x + ox, y + oy])
|
if (ids.has(w.from.node) && w.pts) wire.pts = w.pts.map(([x, y]) => [x + ox, y + oy])
|
||||||
if (w.color) wire.color = w.color
|
if (w.color) wire.color = w.color
|
||||||
added.push(wire)
|
added.push(wire)
|
||||||
}
|
}
|
||||||
for (const w of def.wires) {
|
for (const w of def.wires) {
|
||||||
if (w.from.node !== chip.id) continue
|
if (w.from.node !== chip.id) continue
|
||||||
// An output pin is fed by the wire into its output part; a line coming out, by the wire into that line of its port.
|
const inside = child.wires.find(x => x.to.node === w.from.pin)
|
||||||
const line = lines.get(w.from.pin)
|
|
||||||
const inside = line ? child.wires.find(x => x.to.node === line.port && x.to.pin === `l${line.index}`) : child.wires.find(x => x.to.node === w.from.pin)
|
|
||||||
const from = inside && resolve(inside.from)
|
const from = inside && resolve(inside.from)
|
||||||
if (!from) continue
|
if (from) added.push({ id: uid('w'), from, to: w.to })
|
||||||
added.push({ id: uid('w'), from, to: w.to })
|
|
||||||
if (line) carried.add(line.key)
|
|
||||||
}
|
}
|
||||||
const dropped = def.wires.filter(w => (w.to.node === chip.id && lines.has(w.to.pin) && !carried.has(w.to.pin)) || (w.from.node === chip.id && lines.has(w.from.pin) && !carried.has(w.from.pin))).length
|
|
||||||
|
|
||||||
def.nodes = def.nodes.filter(n => n !== chip)
|
def.nodes = def.nodes.filter(n => n !== chip)
|
||||||
def.wires = [...def.wires.filter(w => w.from.node !== chip.id && w.to.node !== chip.id), ...added]
|
def.wires = [...def.wires.filter(w => w.from.node !== chip.id && w.to.node !== chip.id), ...added]
|
||||||
return { ok: true, nodes: [...ids.values()], dropped }
|
return { ok: true, nodes: [...ids.values()] }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Points one placed component at its own copy of the definition, so edits to it don't change the others. */
|
/** Points one placed component at its own copy of the definition, so edits to it don't change the others. */
|
||||||
|
|
|
||||||
|
|
@ -29,18 +29,14 @@ interface ChipInput {
|
||||||
dy: number
|
dy: number
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** The pins of a chip a panel docks to: its inputs for an input panel, its outputs for an output panel. */
|
||||||
* The pins of a chip a panel docks to: its inputs for an input panel, its
|
|
||||||
* outputs for an output panel. Port sockets and the lines of split ports are
|
|
||||||
* left alone: a cable feeds those.
|
|
||||||
*/
|
|
||||||
function chipInputs(chip: CircuitNode, get: DefLookup, side: 'in' | 'out' = 'in'): ChipInput[] | null {
|
function chipInputs(chip: CircuitNode, get: DefLookup, side: 'in' | 'out' = 'in'): ChipInput[] | null {
|
||||||
const child = chip.kind === 'chip' && chip.chip ? get(chip.chip) : undefined
|
const child = chip.kind === 'chip' && chip.chip ? get(chip.chip) : undefined
|
||||||
if (!child) return null
|
if (!child) return null
|
||||||
const pins = chipPins(child)
|
const pins = chipPins(child)
|
||||||
const labels = new Map((side === 'in' ? pins.inputs : pins.outputs).map(p => [p.key, p.label]))
|
const labels = new Map((side === 'in' ? pins.inputs : pins.outputs).map(p => [p.key, p.label]))
|
||||||
const shape = shapeOf(chip, get)
|
const shape = shapeOf(chip, get)
|
||||||
return (side === 'in' ? shape.inputs : shape.outputs).filter(p => !p.bus && !p.port).map(p => ({ key: p.key, label: labels.get(p.key) ?? p.label, dy: p.dy }))
|
return (side === 'in' ? shape.inputs : shape.outputs).map(p => ({ key: p.key, label: labels.get(p.key) ?? p.label, dy: p.dy }))
|
||||||
}
|
}
|
||||||
|
|
||||||
const sideOf = (panel: CircuitNode) => (panel.kind === 'outpanel' ? 'out' : 'in')
|
const sideOf = (panel: CircuitNode) => (panel.kind === 'outpanel' ? 'out' : 'in')
|
||||||
|
|
@ -67,20 +63,6 @@ function layout(panel: CircuitNode, pins: ChipInput[]) {
|
||||||
return top
|
return top
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* A docked panel moved up or down off its component's pins: its first row no
|
|
||||||
* longer sits level with that row's pin. Moved only sideways, it still does.
|
|
||||||
*/
|
|
||||||
export function offItsPins(def: ComponentDef, panel: CircuitNode, get: DefLookup): boolean {
|
|
||||||
const chip = panel.attach ? def.nodes.find(n => n.id === panel.attach) : undefined
|
|
||||||
const pins = chip && chipInputs(chip, get, sideOf(panel))
|
|
||||||
if (!chip || !pins) return false
|
|
||||||
const order = new Map(pins.map((p, i) => [p.key, i]))
|
|
||||||
const first = (panel.rows ?? []).filter(r => order.has(r.id)).sort((a, b) => order.get(a.id)! - order.get(b.id)!)[0]
|
|
||||||
const pin = first && pins.find(p => p.key === first.id)
|
|
||||||
return !!pin && panel.y !== chip.y + pin.dy
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Docks a new panel to a placed component: an input panel on its left with
|
* Docks a new panel to a placed component: an input panel on its left with
|
||||||
* a switch for every input that is not wired yet, or an output panel on its
|
* a switch for every input that is not wired yet, or an output panel on its
|
||||||
|
|
@ -187,41 +169,6 @@ export function removeRow(def: ComponentDef, panel: CircuitNode, rowId: string)
|
||||||
if (panel.attach) panel.skip = [...new Set([...(panel.skip ?? []), rowId])]
|
if (panel.attach) panel.skip = [...new Set([...(panel.skip ?? []), rowId])]
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* A new row at place `index` in a free panel's order (0: above the first,
|
|
||||||
* rows.length: below the last), the same kind as its neighbour. It takes the
|
|
||||||
* place of the row it goes above; that row and the ones below move down one,
|
|
||||||
* keeping the gaps between them.
|
|
||||||
*/
|
|
||||||
export function insertPanelRow(panel: CircuitNode, index: number): PanelRow {
|
|
||||||
const rows = panel.rows ?? []
|
|
||||||
const at = panelOffsets(rows)
|
|
||||||
const i = Math.max(0, Math.min(Math.round(index), rows.length))
|
|
||||||
const row = newPanelRows(1)[0]!
|
|
||||||
row.type = rows[i]?.type ?? rows[i - 1]?.type ?? 'switch'
|
|
||||||
const place = i < rows.length ? at[i]! : at.length ? at[at.length - 1]! + 1 : 0
|
|
||||||
rows.forEach((r, k) => (r.dy = k < i ? at[k]! : at[k]! + 1))
|
|
||||||
row.dy = place
|
|
||||||
rows.splice(i, 0, row)
|
|
||||||
panel.rows = rows
|
|
||||||
return row
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Moves a row of a free panel from one place in the order to another. The
|
|
||||||
* places stay where they are (gaps too); the rows trade them, and each row
|
|
||||||
* keeps its wires. False when nothing moved.
|
|
||||||
*/
|
|
||||||
export function movePanelRow(panel: CircuitNode, from: number, to: number): boolean {
|
|
||||||
const rows = panel.rows ?? []
|
|
||||||
if (from === to || from < 0 || to < 0 || from >= rows.length || to >= rows.length) return false
|
|
||||||
const at = panelOffsets(rows)
|
|
||||||
const [r] = rows.splice(from, 1)
|
|
||||||
rows.splice(to, 0, r!)
|
|
||||||
rows.forEach((x, k) => (x.dy = at[k]!))
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A docked panel's pins drive the component; undocking keeps rows, wires and position. */
|
/** A docked panel's pins drive the component; undocking keeps rows, wires and position. */
|
||||||
export function detachPanel(panel: CircuitNode) {
|
export function detachPanel(panel: CircuitNode) {
|
||||||
delete panel.attach
|
delete panel.attach
|
||||||
|
|
@ -230,7 +177,7 @@ export function detachPanel(panel: CircuitNode) {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Joins panels into one: the top one keeps its rows, the others' rows follow
|
* Joins panels into one: the top one keeps its rows, the others' rows follow
|
||||||
* below in order, packed without gaps, with their wires. The joined panel
|
* below in order, keeping their spacing, with their wires. The joined panel
|
||||||
* is free (no longer docked). Returns it with the pin keys that changed
|
* is free (no longer docked). Returns it with the pin keys that changed
|
||||||
* (old → new), so circuits that place this one can keep their wires; null
|
* (old → new), so circuits that place this one can keep their wires; null
|
||||||
* for fewer than two panels.
|
* for fewer than two panels.
|
||||||
|
|
@ -243,11 +190,16 @@ export function mergePanels(def: ComponentDef, ids: string[]): { panel: CircuitN
|
||||||
if (panels.length < 2) return null
|
if (panels.length < 2) return null
|
||||||
const [target, ...rest] = panels as [CircuitNode, ...CircuitNode[]]
|
const [target, ...rest] = panels as [CircuitNode, ...CircuitNode[]]
|
||||||
const rows = target.rows ?? []
|
const rows = target.rows ?? []
|
||||||
|
const at = panelOffsets(rows)
|
||||||
|
rows.forEach((r, i) => (r.dy = at[i]!))
|
||||||
|
let bottom = at.length ? at[at.length - 1]! : -1
|
||||||
const used = new Set(rows.map(r => r.id))
|
const used = new Set(rows.map(r => r.id))
|
||||||
const renamed = new Map<string, string>()
|
const renamed = new Map<string, string>()
|
||||||
for (const p of rest) {
|
for (const p of rest) {
|
||||||
const theirs = p.rows ?? []
|
const theirs = p.rows ?? []
|
||||||
theirs.forEach(r => {
|
const off = panelOffsets(theirs)
|
||||||
|
const shift = bottom + 1 - (off[0] ?? 0)
|
||||||
|
theirs.forEach((r, i) => {
|
||||||
const id = used.has(r.id) ? uid('r') : r.id
|
const id = used.has(r.id) ? uid('r') : r.id
|
||||||
used.add(id)
|
used.add(id)
|
||||||
for (const w of def.wires) {
|
for (const w of def.wires) {
|
||||||
|
|
@ -255,11 +207,10 @@ export function mergePanels(def: ComponentDef, ids: string[]): { panel: CircuitN
|
||||||
if (w.to.node === p.id && w.to.pin === r.id) w.to = { node: target.id, pin: id }
|
if (w.to.node === p.id && w.to.pin === r.id) w.to = { node: target.id, pin: id }
|
||||||
}
|
}
|
||||||
renamed.set(rowPin(p.id, r.id), rowPin(target.id, id))
|
renamed.set(rowPin(p.id, r.id), rowPin(target.id, id))
|
||||||
rows.push({ ...r, id })
|
rows.push({ ...r, id, dy: off[i]! + shift })
|
||||||
})
|
})
|
||||||
|
if (theirs.length) bottom = rows[rows.length - 1]!.dy!
|
||||||
}
|
}
|
||||||
// One row under the other, no space between.
|
|
||||||
for (const r of rows) delete r.dy
|
|
||||||
target.rows = rows
|
target.rows = rows
|
||||||
delete target.attach
|
delete target.attach
|
||||||
delete target.skip
|
delete target.skip
|
||||||
|
|
@ -275,7 +226,8 @@ const SINKS = new Set(['output', 'lamp'])
|
||||||
/**
|
/**
|
||||||
* Turns separate switches, buttons and clocks into one input panel, or
|
* Turns separate switches, buttons and clocks into one input panel, or
|
||||||
* output pins and lamps into one output panel: a row each, top to bottom,
|
* output pins and lamps into one output panel: a row each, top to bottom,
|
||||||
* with their names, settings and wires, packed without gaps. Returns the panel and the pin keys that changed
|
* with their names, settings and wires. Rows keep their distance where the
|
||||||
|
* parts were spread out. Returns the panel and the pin keys that changed
|
||||||
* (old → new) for circuits that place this one; null when the parts are
|
* (old → new) for circuits that place this one; null when the parts are
|
||||||
* not all of one side or fewer than two.
|
* not all of one side or fewer than two.
|
||||||
*/
|
*/
|
||||||
|
|
@ -288,8 +240,11 @@ export function combineIntoPanel(def: ComponentDef, ids: string[], get: DefLooku
|
||||||
const pinKind = out ? 'output' : 'input'
|
const pinKind = out ? 'output' : 'input'
|
||||||
if (!sel.some(n => n.kind === pinKind)) panel.inner = true
|
if (!sel.some(n => n.kind === pinKind)) panel.inner = true
|
||||||
const renamed = new Map<string, string>()
|
const renamed = new Map<string, string>()
|
||||||
|
let prev = -1
|
||||||
for (const n of sel) {
|
for (const n of sel) {
|
||||||
const row: PanelRow = { id: n.id, type: n.kind === 'button' ? 'button' : n.kind === 'clock' ? 'clock' : 'switch' }
|
const dy = Math.max(prev + 1, n.y - sel[0]!.y)
|
||||||
|
prev = dy
|
||||||
|
const row: PanelRow = { id: n.id, type: n.kind === 'button' ? 'button' : n.kind === 'clock' ? 'clock' : 'switch', dy }
|
||||||
const label = n.label?.trim()
|
const label = n.label?.trim()
|
||||||
if (label && !n.autoLabel) row.label = label
|
if (label && !n.autoLabel) row.label = label
|
||||||
else if (label) row.name = label
|
else if (label) row.name = label
|
||||||
|
|
|
||||||
|
|
@ -24,16 +24,8 @@ export const KIND_NAMES: Partial<Record<NodeKind, string>> = {
|
||||||
bundle: 'Cable bundle',
|
bundle: 'Cable bundle',
|
||||||
split: 'Cable split',
|
split: 'Cable split',
|
||||||
pixel: 'Pixel',
|
pixel: 'Pixel',
|
||||||
portin: 'Connector in',
|
|
||||||
portout: 'Connector out',
|
|
||||||
tag: 'Send signal',
|
tag: 'Send signal',
|
||||||
ref: 'Use signal',
|
ref: 'Use signal',
|
||||||
terminal: 'Terminal',
|
|
||||||
keyboard: 'Keyboard',
|
|
||||||
monitor: 'Monitor',
|
|
||||||
rgbmonitor: 'RGB monitor',
|
|
||||||
bench: 'Test bench',
|
|
||||||
scope: 'Logic analyzer',
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Challenges each one builds on. */
|
/** Challenges each one builds on. */
|
||||||
|
|
@ -65,14 +57,8 @@ export const KIND_UNLOCK: Partial<Record<NodeKind, string>> = {
|
||||||
outpanel: 'and',
|
outpanel: 'and',
|
||||||
hex: 'dec2',
|
hex: 'dec2',
|
||||||
pixel: 'dec2',
|
pixel: 'dec2',
|
||||||
terminal: 'dec2',
|
|
||||||
keyboard: 'dec2',
|
|
||||||
monitor: 'dec2',
|
|
||||||
rgbmonitor: 'dec2',
|
|
||||||
bundle: 'add2',
|
bundle: 'add2',
|
||||||
split: 'add2',
|
split: 'add2',
|
||||||
portin: 'add2',
|
|
||||||
portout: 'add2',
|
|
||||||
button: 'sr',
|
button: 'sr',
|
||||||
clock: 'dlatch',
|
clock: 'dlatch',
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,14 +8,9 @@ import {
|
||||||
LAMP_COLORS,
|
LAMP_COLORS,
|
||||||
PANEL_CONTROLS,
|
PANEL_CONTROLS,
|
||||||
WIRE_COLORS,
|
WIRE_COLORS,
|
||||||
type AsmDoc,
|
|
||||||
type Bench,
|
|
||||||
type CircuitNode,
|
type CircuitNode,
|
||||||
type ComponentDef,
|
type ComponentDef,
|
||||||
type ConnectorType,
|
|
||||||
type FaceDesign,
|
type FaceDesign,
|
||||||
type HeldState,
|
|
||||||
type LibraryOrigin,
|
|
||||||
type PanelRow,
|
type PanelRow,
|
||||||
type Project,
|
type Project,
|
||||||
type PuzzleSpec,
|
type PuzzleSpec,
|
||||||
|
|
@ -29,7 +24,6 @@ function cleanNode(n: CircuitNode) {
|
||||||
if (n.size !== undefined && !['sm', 'md', 'lg'].includes(n.size)) delete n.size
|
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.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.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.attach !== undefined && typeof n.attach !== 'string') delete n.attach
|
||||||
if (n.skip !== undefined) {
|
if (n.skip !== undefined) {
|
||||||
if (Array.isArray(n.skip)) n.skip = n.skip.filter(k => typeof k === 'string').slice(0, MAX_ROWS)
|
if (Array.isArray(n.skip)) n.skip = n.skip.filter(k => typeof k === 'string').slice(0, MAX_ROWS)
|
||||||
|
|
@ -40,47 +34,13 @@ function cleanNode(n: CircuitNode) {
|
||||||
else n.rows = n.rows.filter(cleanRow).slice(0, MAX_ROWS)
|
else n.rows = n.rows.filter(cleanRow).slice(0, MAX_ROWS)
|
||||||
}
|
}
|
||||||
if (n.plug !== undefined && typeof n.plug !== 'string') delete n.plug
|
if (n.plug !== undefined && typeof n.plug !== 'string') delete n.plug
|
||||||
if (n.latch !== undefined && typeof n.latch !== 'string') delete n.latch
|
|
||||||
if (n.pitch !== undefined && !(Number.isInteger(n.pitch) && n.pitch >= 1 && n.pitch <= 8)) delete n.pitch
|
if (n.pitch !== undefined && !(Number.isInteger(n.pitch) && n.pitch >= 1 && n.pitch <= 8)) delete n.pitch
|
||||||
if (n.offsets !== undefined && !(Array.isArray(n.offsets) && n.offsets.every(v => Number.isInteger(v) && v >= 0 && v <= 10_000))) delete n.offsets
|
if (n.offsets !== undefined && !(Array.isArray(n.offsets) && n.offsets.every(v => Number.isInteger(v) && v >= 0 && v <= 10_000))) delete n.offsets
|
||||||
for (const k of ['names', 'invert', 'splitPorts'] as const) {
|
for (const k of ['names', 'invert'] as const) {
|
||||||
if (n[k] !== undefined && !(Array.isArray(n[k]) && n[k]!.every(v => typeof v === 'string'))) delete n[k]
|
if (n[k] !== undefined && !(Array.isArray(n[k]) && n[k]!.every(v => typeof v === 'string'))) delete n[k]
|
||||||
}
|
}
|
||||||
if (n.inner !== undefined && n.inner !== true) delete n.inner
|
if (n.inner !== undefined && n.inner !== true) delete n.inner
|
||||||
if (n.screen !== undefined && typeof n.screen !== 'string') delete n.screen
|
if (n.screen !== undefined && typeof n.screen !== 'string') delete n.screen
|
||||||
if (n.rgb !== undefined && n.rgb !== true) delete n.rgb
|
|
||||||
if (n.dims !== undefined && !(Array.isArray(n.dims) && n.dims.length === 2 && n.dims.every(v => Number.isInteger(v) && v >= 1 && v <= 128))) delete n.dims
|
|
||||||
if (n.scope !== undefined) {
|
|
||||||
const cols = Array.isArray(n.scope?.cols) ? n.scope.cols : []
|
|
||||||
n.scope = {
|
|
||||||
cols: cols
|
|
||||||
.filter(c => c && typeof c.id === 'string' && typeof c.name === 'string')
|
|
||||||
.slice(0, 32)
|
|
||||||
.map(c => ({ id: c.id, name: c.name.slice(0, 40), bits: Number.isInteger(c.bits) && c.bits >= 1 && c.bits <= 32 ? c.bits : 1 })),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (n.bench !== undefined) {
|
|
||||||
const b = n.bench as Partial<Bench>
|
|
||||||
const cells = (r: unknown) => (r && typeof r === 'object' && !Array.isArray(r) ? Object.fromEntries(Object.entries(r).filter(([, v]) => typeof v === 'string').slice(0, 256)) : undefined)
|
|
||||||
if (!b || typeof b !== 'object' || !Array.isArray(b.rows)) delete n.bench
|
|
||||||
else {
|
|
||||||
const cols = Array.isArray(b.cols)
|
|
||||||
? b.cols
|
|
||||||
.filter(c => c && typeof c.id === 'string' && typeof c.name === 'string' && (c.dir === 'drive' || c.dir === 'check'))
|
|
||||||
.slice(0, 64)
|
|
||||||
.map(c => ({ id: c.id, name: c.name.slice(0, 40), bits: Number.isInteger(c.bits) && c.bits >= 1 && c.bits <= 32 ? c.bits : 1, dir: c.dir }))
|
|
||||||
: undefined
|
|
||||||
n.bench = {
|
|
||||||
...(typeof b.on === 'string' ? { on: b.on } : {}),
|
|
||||||
...(cols ? { cols } : {}),
|
|
||||||
rows: b.rows.slice(0, 4096).filter(r => r && typeof r === 'object').map(r => ({
|
|
||||||
...(cells(r.set) ? { set: cells(r.set) } : {}),
|
|
||||||
...(cells(r.expect) ? { expect: cells(r.expect) } : {}),
|
|
||||||
...(typeof r.ticks === 'string' ? { ticks: r.ticks } : {}),
|
|
||||||
})),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const MAX_ROWS = 256
|
const MAX_ROWS = 256
|
||||||
|
|
@ -121,8 +81,6 @@ function cleanDesign(d: ComponentDef) {
|
||||||
if (f.rotate !== undefined) f.rotate = nums(f.rotate, v => [0, 90, 180, 270].includes(v))
|
if (f.rotate !== undefined) f.rotate = nums(f.rotate, v => [0, 90, 180, 270].includes(v))
|
||||||
if (f.pinAt !== undefined) f.pinAt = nums(f.pinAt, v => Number.isInteger(v) && v >= 0 && v <= 1000)
|
if (f.pinAt !== undefined) f.pinAt = nums(f.pinAt, v => Number.isInteger(v) && v >= 0 && v <= 1000)
|
||||||
for (const k of ['scale', 'rotate', 'pinAt'] as const) if (f[k] === undefined) delete f[k]
|
for (const k of ['scale', 'rotate', 'pinAt'] as const) if (f[k] === undefined) delete f[k]
|
||||||
for (const k of ['pinOrder', 'split'] as const) if (f[k] !== undefined && !(Array.isArray(f[k]) && f[k]!.every(v => typeof v === 'string'))) delete f[k]
|
|
||||||
if (f.fit !== undefined && f.fit !== true) delete f.fit
|
|
||||||
if (f.shapes !== undefined) {
|
if (f.shapes !== undefined) {
|
||||||
f.shapes = Array.isArray(f.shapes)
|
f.shapes = Array.isArray(f.shapes)
|
||||||
? f.shapes
|
? f.shapes
|
||||||
|
|
@ -145,21 +103,8 @@ function cleanDesign(d: ComponentDef) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Where a library component came from: an entry id, a version and a name; anything else is dropped. */
|
/** Upper bounds for a project that comes from outside. */
|
||||||
function cleanOrigin(d: ComponentDef) {
|
export const LIMITS = { bytes: 2_000_000, components: 2_000, nodes: 100_000 }
|
||||||
const f = d.from as Partial<LibraryOrigin> | undefined
|
|
||||||
if (!f || typeof f.id !== 'string' || !/^[A-Za-z0-9]{6,16}$/.test(f.id) || !Number.isInteger(f.version) || f.version! < 1) {
|
|
||||||
delete d.from
|
|
||||||
return
|
|
||||||
}
|
|
||||||
d.from = { id: f.id, version: f.version!, author: typeof f.author === 'string' ? f.author.slice(0, 24) : '', ...(f.inside === true ? { inside: true } : {}) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A wire's corner points: [x, y] pairs of plain numbers, or the wire can't be drawn. */
|
|
||||||
const cornersOk = (pts: unknown) => Array.isArray(pts) && pts.every(p => Array.isArray(p) && p.length === 2 && p.every(v => typeof v === 'number' && Number.isFinite(v)))
|
|
||||||
|
|
||||||
/** Upper bounds for a project that comes from outside. What its circuits hold has its own room (`state`) on top of `bytes`. */
|
|
||||||
export const LIMITS = { bytes: 2_000_000, components: 2_000, nodes: 100_000, state: 500_000 }
|
|
||||||
|
|
||||||
/** Checks and normalises project data. Throws with a readable message. */
|
/** Checks and normalises project data. Throws with a readable message. */
|
||||||
export function toProject(data: unknown): Project {
|
export function toProject(data: unknown): Project {
|
||||||
|
|
@ -177,15 +122,8 @@ export function toProject(data: unknown): Project {
|
||||||
d.symbol ??= 'box'
|
d.symbol ??= 'box'
|
||||||
if (d.wide !== undefined && !(d.wide && typeof d.wide.base === 'string' && Number.isInteger(d.wide.n) && d.wide.n >= 2 && d.wide.n <= 16)) delete d.wide
|
if (d.wide !== undefined && !(d.wide && typeof d.wide.base === 'string' && Number.isInteger(d.wide.n) && d.wide.n >= 2 && d.wide.n <= 16)) delete d.wide
|
||||||
if (d.design !== undefined) cleanDesign(d)
|
if (d.design !== undefined) cleanDesign(d)
|
||||||
if (d.from !== undefined) cleanOrigin(d)
|
|
||||||
if (d.probes !== undefined) {
|
|
||||||
d.probes = Array.isArray(d.probes) ? d.probes.filter(p => p && typeof p.node === 'string' && typeof p.pin === 'string').slice(0, 64) : []
|
|
||||||
for (const p of d.probes) if (p.label !== undefined && typeof p.label !== 'string') delete p.label
|
|
||||||
if (!d.probes.length) delete d.probes
|
|
||||||
}
|
|
||||||
for (const n of d.nodes) cleanNode(n)
|
for (const n of d.nodes) cleanNode(n)
|
||||||
for (const w of d.wires) if (w.color && !WIRE_COLORS.includes(w.color)) delete w.color
|
for (const w of d.wires) if (w.color && !WIRE_COLORS.includes(w.color)) delete w.color
|
||||||
for (const w of d.wires) if (w.pts !== undefined && !cornersOk(w.pts)) delete w.pts
|
|
||||||
}
|
}
|
||||||
if (nodes > LIMITS.nodes) throw new Error('Project too large')
|
if (nodes > LIMITS.nodes) throw new Error('Project too large')
|
||||||
return {
|
return {
|
||||||
|
|
@ -203,60 +141,9 @@ export function toProject(data: unknown): Project {
|
||||||
...(bestOf(p.best) ? { best: bestOf(p.best)! } : {}),
|
...(bestOf(p.best) ? { best: bestOf(p.best)! } : {}),
|
||||||
...(p.mode === 'campaign' || p.mode === 'challenges' ? { mode: p.mode } : {}),
|
...(p.mode === 'campaign' || p.mode === 'challenges' ? { mode: p.mode } : {}),
|
||||||
...(puzzlesOf(p.puzzles) ? { puzzles: puzzlesOf(p.puzzles)! } : {}),
|
...(puzzlesOf(p.puzzles) ? { puzzles: puzzlesOf(p.puzzles)! } : {}),
|
||||||
...(connectorsOf(p.connectors) ? { connectors: connectorsOf(p.connectors)! } : {}),
|
|
||||||
...(stateOf(p.state, p.components) ? { state: stateOf(p.state, p.components)! } : {}),
|
|
||||||
...(asmOf(p.asm) ? { asm: asmOf(p.asm)! } : {}),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The assembler's texts, if they are texts (long ones cut). */
|
|
||||||
function asmOf(a: unknown): AsmDoc | null {
|
|
||||||
const d = a as Partial<AsmDoc> | null
|
|
||||||
if (!d || typeof d !== 'object' || typeof d.table !== 'string' || typeof d.source !== 'string') return null
|
|
||||||
const width = Number.isInteger(d.width) && d.width! >= 1 && d.width! <= 32 ? d.width! : 8
|
|
||||||
return {
|
|
||||||
table: d.table.slice(0, 50_000),
|
|
||||||
source: d.source.slice(0, 200_000),
|
|
||||||
width,
|
|
||||||
...(typeof d.target === 'string' ? { target: d.target } : {}),
|
|
||||||
...(d.msbTop === true ? { msbTop: true } : {}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Bits the circuits held: only for circuits of the project, names and gates as text; broken entries are dropped. */
|
|
||||||
function stateOf(raw: unknown, components: ComponentDef[]): Record<string, HeldState> | null {
|
|
||||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
|
|
||||||
const ids = new Set(components.map(d => d.id))
|
|
||||||
const out: Record<string, HeldState> = {}
|
|
||||||
for (const [id, s] of Object.entries(raw as Record<string, Partial<HeldState>>)) {
|
|
||||||
if (!ids.has(id) || !s || typeof s.on !== 'string' || !Array.isArray(s.names) || !s.names.every(n => typeof n === 'string')) continue
|
|
||||||
const clocks = Array.isArray(s.clocks) ? s.clocks.filter(k => typeof k === 'string') : []
|
|
||||||
if (!s.on && !clocks.length) continue
|
|
||||||
out[id] = { names: s.names, on: s.on, ...(clocks.length ? { clocks } : {}) }
|
|
||||||
}
|
|
||||||
const kept = trimState(out)
|
|
||||||
return Object.keys(kept).length ? kept : null
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What circuits hold, newest last, cut to LIMITS.state: the newest are kept,
|
|
||||||
* older ones that no longer fit are dropped (those circuits start from 0), so
|
|
||||||
* no amount of memory makes a project too large to load or save.
|
|
||||||
*/
|
|
||||||
export function trimState(state: Record<string, HeldState>): Record<string, HeldState> {
|
|
||||||
const ids = Object.keys(state)
|
|
||||||
const kept = new Set<string>()
|
|
||||||
let room = LIMITS.state
|
|
||||||
for (let i = ids.length - 1; i >= 0; i--) {
|
|
||||||
const id = ids[i]!
|
|
||||||
const size = id.length + JSON.stringify(state[id]).length + 4
|
|
||||||
if (size > room) continue
|
|
||||||
room -= size
|
|
||||||
kept.add(id)
|
|
||||||
}
|
|
||||||
return kept.size === ids.length ? state : Object.fromEntries(ids.filter(id => kept.has(id)).map(id => [id, state[id]!]))
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Challenge records: challenge id → fewest transistors, whole non-negative numbers only. */
|
/** Challenge records: challenge id → fewest transistors, whole non-negative numbers only. */
|
||||||
function bestOf(raw: unknown): Record<string, number> | null {
|
function bestOf(raw: unknown): Record<string, number> | null {
|
||||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
|
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
|
||||||
|
|
@ -265,26 +152,6 @@ function bestOf(raw: unknown): Record<string, number> | null {
|
||||||
return Object.keys(out).length ? out : 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. */
|
/** Puzzles kept in a project; broken ones are dropped. */
|
||||||
function puzzlesOf(raw: unknown): PuzzleSpec[] | null {
|
function puzzlesOf(raw: unknown): PuzzleSpec[] | null {
|
||||||
if (!Array.isArray(raw)) return null
|
if (!Array.isArray(raw)) return null
|
||||||
|
|
@ -300,7 +167,7 @@ function puzzlesOf(raw: unknown): PuzzleSpec[] | null {
|
||||||
}
|
}
|
||||||
|
|
||||||
export function parseProject(json: string): Project {
|
export function parseProject(json: string): Project {
|
||||||
if (json.length > LIMITS.bytes + LIMITS.state) throw new Error('File too large')
|
if (json.length > LIMITS.bytes) throw new Error('File too large')
|
||||||
let data: unknown
|
let data: unknown
|
||||||
try {
|
try {
|
||||||
data = JSON.parse(json)
|
data = JSON.parse(json)
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,15 @@
|
||||||
// Routes all wires and cables of a circuit so that lines of different
|
// Routes all wires of a circuit so that wires of different signals never
|
||||||
// signals never run on top of (or right beside) each other, and nothing
|
// run on top of each other.
|
||||||
// runs over or under a part.
|
|
||||||
//
|
//
|
||||||
// 1. Wires with hand-placed corners keep them. Every other wire uses its
|
// 1. Wires with hand-placed corners keep them. Every other wire uses its
|
||||||
// usual route if that is free. A wire of a signal that is already laid
|
// usual route if that is free; otherwise the cheapest free alternative:
|
||||||
// may branch off it instead, so one signal (a cable too) splits from one
|
// another column for the vertical step, or a detour around parts.
|
||||||
// trunk. Otherwise the cheapest free alternative: another column for the
|
// 2. Anything still sharing a line with another signal is drawn on its own
|
||||||
// vertical step, a detour, and last a search of the grid around parts.
|
// parallel lane, a quarter grid step apart.
|
||||||
// 2. Parts are walls with a margin around them; a line only touches a part
|
// 3. Crossings between different signals are listed, so the view can draw
|
||||||
// where it ends on its pin. Cables count as wide as they are drawn.
|
// hops (bow, triangle, bridge, gap) at those points.
|
||||||
// 3. Anything still sharing a line with another signal is drawn on its own
|
|
||||||
// parallel lane, spaced by the widths of the two.
|
|
||||||
// 4. Crossings between different signals get hops (bow, triangle, bridge,
|
|
||||||
// gap): the thinner line jumps over the wider one, as wide as it needs.
|
|
||||||
|
|
||||||
import { GRID, pinPos, routeWire, simplify, type Pt, type Shape } from './geometry'
|
import { pinPos, routeWire, simplify, type Pt, type Shape } from './geometry'
|
||||||
import type { ComponentDef } from './types'
|
import type { ComponentDef } from './types'
|
||||||
|
|
||||||
export interface RouteInput {
|
export interface RouteInput {
|
||||||
|
|
@ -24,11 +19,6 @@ export interface RouteInput {
|
||||||
a: Pt
|
a: Pt
|
||||||
b: Pt
|
b: Pt
|
||||||
pts?: 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
|
|
||||||
/** Half the drawn width in grid units: a wire is thin, a cable as wide as its sleeve. */
|
|
||||||
h?: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Box {
|
export interface Box {
|
||||||
|
|
@ -45,8 +35,6 @@ export interface Routed {
|
||||||
grid: Pt[]
|
grid: Pt[]
|
||||||
/** Route as drawn, moved onto separate lanes where needed. */
|
/** Route as drawn, moved onto separate lanes where needed. */
|
||||||
draw: Pt[]
|
draw: Pt[]
|
||||||
/** Half the drawn width in grid units. */
|
|
||||||
h: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Crossing {
|
export interface Crossing {
|
||||||
|
|
@ -57,75 +45,46 @@ export interface Crossing {
|
||||||
x: number
|
x: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const LANE = 0.25
|
||||||
const EPS = 1e-6
|
const EPS = 1e-6
|
||||||
/** Space between two lines moved onto lanes beside each other. */
|
|
||||||
const LANE_GAP = 0.125
|
|
||||||
/** Half the width of a plain wire, in grid units. */
|
|
||||||
export const WIRE_H = 1 / GRID
|
|
||||||
/** Space two lines of different signals keep between their edges. */
|
|
||||||
const NEAR = 0.25
|
|
||||||
/** Space a line keeps from the parts it passes. */
|
|
||||||
const CLEAR = 0.2
|
|
||||||
/** Cost of a segment that runs through (or along) a part. */
|
|
||||||
const BODY = 5000
|
|
||||||
|
|
||||||
interface Seg {
|
interface Seg {
|
||||||
lo: number
|
lo: number
|
||||||
hi: number
|
hi: number
|
||||||
net: string
|
net: string
|
||||||
h: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Lines already taken, by row (horizontal) and column (vertical). */
|
/** Lines already taken, by row (horizontal) and column (vertical). */
|
||||||
class Occupancy {
|
class Occupancy {
|
||||||
rows = new Map<number, Seg[]>()
|
rows = new Map<number, Seg[]>()
|
||||||
cols = new Map<number, Seg[]>()
|
cols = new Map<number, Seg[]>()
|
||||||
/** The widest line so far, to know how far beside a line to look. */
|
|
||||||
hmax = WIRE_H
|
|
||||||
|
|
||||||
add(route: Pt[], net: string, h = WIRE_H) {
|
add(route: Pt[], net: string) {
|
||||||
this.hmax = Math.max(this.hmax, h)
|
|
||||||
for (let i = 0; i < route.length - 1; i++) {
|
for (let i = 0; i < route.length - 1; i++) {
|
||||||
const [ax, ay] = route[i]!
|
const [ax, ay] = route[i]!
|
||||||
const [bx, by] = route[i + 1]!
|
const [bx, by] = route[i + 1]!
|
||||||
if (ay === by && ax !== bx) push(this.rows, ay, { lo: Math.min(ax, bx), hi: Math.max(ax, bx), net, h })
|
if (ay === by && ax !== bx) push(this.rows, ay, { lo: Math.min(ax, bx), hi: Math.max(ax, bx), net })
|
||||||
else if (ax === bx && ay !== by) push(this.cols, ax, { lo: Math.min(ay, by), hi: Math.max(ay, by), net, h })
|
else if (ax === bx && ay !== by) push(this.cols, ax, { lo: Math.min(ay, by), hi: Math.max(ay, by), net })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Length that a segment shares with lines of other nets. */
|
||||||
* Length that a segment (of half-width h) shares with lines of other nets:
|
overlap(a: Pt, b: Pt, net: string): number {
|
||||||
* on its own line, or on a line so close beside it that the two would
|
|
||||||
* touch (a wide cable next to a wire or another cable).
|
|
||||||
*/
|
|
||||||
overlap(a: Pt, b: Pt, net: string, h = WIRE_H): number {
|
|
||||||
const horizontal = a[1] === b[1]
|
const horizontal = a[1] === b[1]
|
||||||
const c = horizontal ? a[1] : a[0]
|
const list = horizontal ? this.rows.get(a[1]) : this.cols.get(a[0])
|
||||||
|
if (!list) return 0
|
||||||
const lo = horizontal ? Math.min(a[0], b[0]) : Math.min(a[1], b[1])
|
const lo = horizontal ? Math.min(a[0], b[0]) : Math.min(a[1], b[1])
|
||||||
const hi = horizontal ? Math.max(a[0], b[0]) : Math.max(a[1], b[1])
|
const hi = horizontal ? Math.max(a[0], b[0]) : Math.max(a[1], b[1])
|
||||||
const lines = horizontal ? this.rows : this.cols
|
|
||||||
const reach = Math.floor(h + this.hmax + NEAR)
|
|
||||||
let total = 0
|
let total = 0
|
||||||
for (let d = -reach; d <= reach; d++) {
|
|
||||||
const list = lines.get(c + d)
|
|
||||||
if (!list) continue
|
|
||||||
for (const s of list) {
|
for (const s of list) {
|
||||||
if (s.net === net || (d !== 0 && Math.abs(d) >= h + s.h + NEAR)) continue
|
if (s.net === net) continue
|
||||||
const o = Math.min(hi, s.hi) - Math.max(lo, s.lo)
|
const o = Math.min(hi, s.hi) - Math.max(lo, s.lo)
|
||||||
// Touching end to end on one line counts too: it would read as one wire.
|
// Touching end to end counts too: it would read as one wire.
|
||||||
if (o > 0) total += o
|
if (o > 0) total += o
|
||||||
else if (o === 0 && d === 0) total += 0.5
|
else if (o === 0) total += 0.5
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return total
|
return total
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A line of another net crosses this point (running through it, not ending there). */
|
|
||||||
crossedAt(x: number, y: number, net: string, vertical: boolean): boolean {
|
|
||||||
const list = vertical ? this.cols.get(x) : this.rows.get(y)
|
|
||||||
const at = vertical ? y : x
|
|
||||||
return !!list?.some(s => s.net !== net && at > s.lo + EPS && at < s.hi - EPS)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function push<T>(map: Map<number, T[]>, key: number, value: T) {
|
function push<T>(map: Map<number, T[]>, key: number, value: T) {
|
||||||
|
|
@ -151,46 +110,24 @@ class BodyIndex {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Bodies whose inside (minus a small margin) the segment passes through. */
|
||||||
* Parts a segment (of half-width h) runs through or along: each part with a
|
hits(a: Pt, b: Pt): number {
|
||||||
* margin around it. An end on a pin (trimA, trimB) is let off that margin,
|
|
||||||
* since a line has to touch the part it plugs into.
|
|
||||||
*/
|
|
||||||
hits(a: Pt, b: Pt, h = WIRE_H, trimA = false, trimB = false): number {
|
|
||||||
const S = BodyIndex.SIZE
|
const S = BodyIndex.SIZE
|
||||||
const c = h + CLEAR
|
|
||||||
let [ax, ay] = a
|
|
||||||
let [bx, by] = b
|
|
||||||
if (trimA || trimB) {
|
|
||||||
const t = c + 0.01
|
|
||||||
const len = Math.abs(bx - ax) + Math.abs(by - ay)
|
|
||||||
if (len <= (trimA ? t : 0) + (trimB ? t : 0)) return 0
|
|
||||||
const dx = Math.sign(bx - ax)
|
|
||||||
const dy = Math.sign(by - ay)
|
|
||||||
if (trimA) {
|
|
||||||
ax += dx * t
|
|
||||||
ay += dy * t
|
|
||||||
}
|
|
||||||
if (trimB) {
|
|
||||||
bx -= dx * t
|
|
||||||
by -= dy * t
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const q = ++this.query
|
const q = ++this.query
|
||||||
let n = 0
|
let n = 0
|
||||||
const lx = Math.min(ax, bx)
|
const lx = Math.min(a[0], b[0])
|
||||||
const hx = Math.max(ax, bx)
|
const hx = Math.max(a[0], b[0])
|
||||||
const ly = Math.min(ay, by)
|
const ly = Math.min(a[1], b[1])
|
||||||
const hy = Math.max(ay, by)
|
const hy = Math.max(a[1], b[1])
|
||||||
for (let cx = Math.floor((lx - c) / S); cx <= Math.floor((hx + c) / S); cx++) {
|
for (let cx = Math.floor(lx / S); cx <= Math.floor(hx / S); cx++) {
|
||||||
for (let cy = Math.floor((ly - c) / S); cy <= Math.floor((hy + c) / S); cy++) {
|
for (let cy = Math.floor(ly / S); cy <= Math.floor(hy / S); cy++) {
|
||||||
for (const box of this.cells.get(BodyIndex.key(cx, cy)) ?? []) {
|
for (const box of this.cells.get(BodyIndex.key(cx, cy)) ?? []) {
|
||||||
if (this.stamp.get(box) === q) continue
|
if (this.stamp.get(box) === q) continue
|
||||||
this.stamp.set(box, q)
|
this.stamp.set(box, q)
|
||||||
const x0 = box.x - c
|
const x0 = box.x + 0.2
|
||||||
const x1 = box.x + box.w + c
|
const x1 = box.x + box.w - 0.2
|
||||||
const y0 = box.y - c
|
const y0 = box.y + 0.2
|
||||||
const y1 = box.y + box.h + c
|
const y1 = box.y + box.h - 0.2
|
||||||
const hit = ly === hy ? ly > y0 && ly < y1 && hx > x0 && lx < x1 : lx > x0 && lx < x1 && hy > y0 && ly < y1
|
const hit = ly === hy ? ly > y0 && ly < y1 && hx > x0 && lx < x1 : lx > x0 && lx < x1 && hy > y0 && ly < y1
|
||||||
if (hit) n++
|
if (hit) n++
|
||||||
}
|
}
|
||||||
|
|
@ -201,13 +138,9 @@ class BodyIndex {
|
||||||
}
|
}
|
||||||
|
|
||||||
const pinKey = (x: number, y: number) => (x + 50_000) * 100_000 + y + 50_000
|
const pinKey = (x: number, y: number) => (x + 50_000) * 100_000 + y + 50_000
|
||||||
const pinKeys = (pins: Pt[]) => new Set(pins.map(([x, y]) => pinKey(x, y)))
|
|
||||||
|
|
||||||
/**
|
/** Cost of a route; stops counting once it is above `limit`. */
|
||||||
* Cost of a route; stops counting once it is above `limit`. `fromPin`: it
|
function cost(route: Pt[], net: string, occ: Occupancy, bodies: BodyIndex, pins: Set<number>, limit = Infinity): { penalty: number; total: number } {
|
||||||
* starts on a pin (false for a branch off a line of its own signal).
|
|
||||||
*/
|
|
||||||
function cost(route: Pt[], net: string, occ: Occupancy, bodies: BodyIndex, pins: Set<number>, limit = Infinity, h = WIRE_H, fromPin = true): { penalty: number; total: number } {
|
|
||||||
let penalty = 0
|
let penalty = 0
|
||||||
let length = route.length * 0.5
|
let length = route.length * 0.5
|
||||||
const first = route[0]!
|
const first = route[0]!
|
||||||
|
|
@ -216,7 +149,7 @@ function cost(route: Pt[], net: string, occ: Occupancy, bodies: BodyIndex, pins:
|
||||||
const a = route[i]!
|
const a = route[i]!
|
||||||
const b = route[i + 1]!
|
const b = route[i + 1]!
|
||||||
length += Math.abs(b[0] - a[0]) + Math.abs(b[1] - a[1])
|
length += Math.abs(b[0] - a[0]) + Math.abs(b[1] - a[1])
|
||||||
penalty += occ.overlap(a, b, net, h) * 1000 + bodies.hits(a, b, h, fromPin && i === 0, i === route.length - 2) * BODY
|
penalty += occ.overlap(a, b, net) * 1000 + bodies.hits(a, b) * 60
|
||||||
// Running over someone else's pin looks like a connection.
|
// Running over someone else's pin looks like a connection.
|
||||||
if (pins.size) {
|
if (pins.size) {
|
||||||
if (a[1] === b[1]) {
|
if (a[1] === b[1]) {
|
||||||
|
|
@ -263,278 +196,27 @@ function* candidates(a: Pt, b: Pt): Generator<Pt[]> {
|
||||||
for (let d = 0; d <= 6; d++) rows.add(Math.round((y1 + y2) / 2) + d).add(Math.round((y1 + y2) / 2) - d)
|
for (let d = 0; d <= 6; d++) rows.add(Math.round((y1 + y2) / 2) + d).add(Math.round((y1 + y2) / 2) - d)
|
||||||
for (let d = 2; d <= 7; d++) rows.add(Math.max(y1, y2) + d).add(Math.min(y1, y2) - d)
|
for (let d = 2; d <= 7; d++) rows.add(Math.max(y1, y2) + d).add(Math.min(y1, y2) - d)
|
||||||
for (const ym of rows) {
|
for (const ym of rows) {
|
||||||
// On the row of either end the detour would fold back into a straight line through the parts.
|
|
||||||
if (ym === y1 || ym === y2) continue
|
|
||||||
for (const r of [x1 + 1, x1 + 2, x1 + 3]) {
|
for (const r of [x1 + 1, x1 + 2, x1 + 3]) {
|
||||||
for (const l of [x2 - 1, x2 - 2, x2 - 3]) yield [a, [r, y1], [r, ym], [l, ym], [l, y2], b]
|
for (const l of [x2 - 1, x2 - 2, x2 - 3]) yield [a, [r, y1], [r, ym], [l, ym], [l, y2], b]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A wire to or from a pin facing the unusual way (the inner pins of ports). */
|
function autoRoute(input: RouteInput, occ: Occupancy, bodies: BodyIndex, pins: Set<number>): Pt[] {
|
||||||
const reversed = (w: RouteInput) => w.aFace === -1 || w.bFace === 1
|
|
||||||
|
|
||||||
// ── Grid search ─────────────────────────────────────────────────────
|
|
||||||
// When neither the usual route nor its alternatives are free, a search of
|
|
||||||
// the grid around the two ends: steps along free lines, turns cost a little,
|
|
||||||
// parts are walls, other signals' lines are very expensive to run along and
|
|
||||||
// a little expensive to cross. It may also start from any point of a line of
|
|
||||||
// its own signal, so the wire branches off it.
|
|
||||||
|
|
||||||
const DX = [1, -1, 0, 0]
|
|
||||||
const DY = [0, 0, 1, -1]
|
|
||||||
const TURN = 2
|
|
||||||
const CROSS = 1.5
|
|
||||||
const ALONG = 60
|
|
||||||
const PIN = 300
|
|
||||||
/** Most points one search looks at before it gives up, and all searches of one routing together. */
|
|
||||||
const MAX_VISITS = 6_000
|
|
||||||
const ALL_VISITS = 120_000
|
|
||||||
|
|
||||||
/** A tiny binary heap of (cost, state). */
|
|
||||||
class Heap {
|
|
||||||
keys: number[] = []
|
|
||||||
vals: number[] = []
|
|
||||||
get size() {
|
|
||||||
return this.keys.length
|
|
||||||
}
|
|
||||||
push(k: number, v: number) {
|
|
||||||
const ks = this.keys
|
|
||||||
const vs = this.vals
|
|
||||||
let i = ks.length
|
|
||||||
ks.push(k)
|
|
||||||
vs.push(v)
|
|
||||||
while (i > 0) {
|
|
||||||
const p = (i - 1) >> 1
|
|
||||||
if (ks[p]! <= k) break
|
|
||||||
ks[i] = ks[p]!
|
|
||||||
vs[i] = vs[p]!
|
|
||||||
i = p
|
|
||||||
}
|
|
||||||
ks[i] = k
|
|
||||||
vs[i] = v
|
|
||||||
}
|
|
||||||
pop(): number {
|
|
||||||
const ks = this.keys
|
|
||||||
const vs = this.vals
|
|
||||||
const top = vs[0]!
|
|
||||||
const k = ks.pop()!
|
|
||||||
const v = vs.pop()!
|
|
||||||
const n = ks.length
|
|
||||||
if (n) {
|
|
||||||
let i = 0
|
|
||||||
for (;;) {
|
|
||||||
let c = 2 * i + 1
|
|
||||||
if (c >= n) break
|
|
||||||
if (c + 1 < n && ks[c + 1]! < ks[c]!) c++
|
|
||||||
if (ks[c]! >= k) break
|
|
||||||
ks[i] = ks[c]!
|
|
||||||
vs[i] = vs[c]!
|
|
||||||
i = c
|
|
||||||
}
|
|
||||||
ks[i] = k
|
|
||||||
vs[i] = v
|
|
||||||
}
|
|
||||||
return top
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The cheapest square path to `b` (arriving moving right, into a pin facing
|
|
||||||
* left) from `a` (leaving right, out of a pin facing right) or from any of
|
|
||||||
* `branches` (points on lines of the same signal). Null when none is found.
|
|
||||||
*/
|
|
||||||
function maze(a: Pt, b: Pt, branches: Pt[], net: string, h: number, occ: Occupancy, bodies: BodyIndex, pins: Set<number>, margin: number, budget: { left: number }): Pt[] | null {
|
|
||||||
// A pin whose first step is already blocked can not be reached.
|
|
||||||
if (budget.left <= 0 || bodies.hits(a, [a[0] + 1, a[1]], h, true) || bodies.hits([b[0] - 1, b[1]], b, h, false, true)) return null
|
|
||||||
const xs = [a[0], b[0], ...branches.map(p => p[0])]
|
|
||||||
const ys = [a[1], b[1], ...branches.map(p => p[1])]
|
|
||||||
const x0 = Math.min(...xs) - margin
|
|
||||||
const y0 = Math.min(...ys) - margin
|
|
||||||
const W = Math.max(...xs) + margin - x0 + 1
|
|
||||||
const H = Math.max(...ys) + margin - y0 + 1
|
|
||||||
const N = W * H
|
|
||||||
if (N > 400_000) return null
|
|
||||||
const id = (x: number, y: number) => x - x0 + (y - y0) * W
|
|
||||||
const best = new Float64Array(N * 4).fill(Infinity)
|
|
||||||
const prev = new Int32Array(N * 4).fill(-1)
|
|
||||||
const edge = new Float64Array(N * 4).fill(NaN)
|
|
||||||
const heap = new Heap()
|
|
||||||
const goal = id(b[0], b[1])
|
|
||||||
const est = (x: number, y: number) => Math.abs(x - b[0]) + Math.abs(y - b[1])
|
|
||||||
|
|
||||||
// Cost of one step from (x, y) in direction d; Infinity when it runs into a part.
|
|
||||||
const step = (x: number, y: number, d: number): number => {
|
|
||||||
const k = id(x, y) * 4 + d
|
|
||||||
const cached = edge[k]!
|
|
||||||
if (!Number.isNaN(cached)) return cached
|
|
||||||
const nx = x + DX[d]!
|
|
||||||
const ny = y + DY[d]!
|
|
||||||
const p: Pt = [x, y]
|
|
||||||
const q: Pt = [nx, ny]
|
|
||||||
let c = 1
|
|
||||||
if (bodies.hits(p, q, h, x === a[0] && y === a[1], nx === b[0] && ny === b[1])) c = Infinity
|
|
||||||
else {
|
|
||||||
c += occ.overlap(p, q, net, h) * ALONG
|
|
||||||
if ((nx !== b[0] || ny !== b[1]) && pins.has(pinKey(nx, ny))) c += PIN
|
|
||||||
if (occ.crossedAt(nx, ny, net, d < 2)) c += CROSS
|
|
||||||
}
|
|
||||||
edge[k] = c
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
const start = (x: number, y: number, d: number, c: number) => {
|
|
||||||
const s = id(x, y) * 4 + d
|
|
||||||
if (c < best[s]!) {
|
|
||||||
best[s] = c
|
|
||||||
heap.push(c + est(x, y), s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Out of the pin to the right; or from a branch point, any way.
|
|
||||||
start(a[0], a[1], 0, 0)
|
|
||||||
for (const p of branches) for (let d = 0; d < 4; d++) start(p[0], p[1], d, 1)
|
|
||||||
const fromPin = (s: number) => {
|
|
||||||
const node = s >> 2
|
|
||||||
return node === id(a[0], a[1])
|
|
||||||
}
|
|
||||||
|
|
||||||
let visits = 0
|
|
||||||
while (heap.size) {
|
|
||||||
const s = heap.pop()
|
|
||||||
const node = s >> 2
|
|
||||||
const d = s & 3
|
|
||||||
const c = best[s]!
|
|
||||||
if (node === goal && d === 0) {
|
|
||||||
// Walk back to where it started.
|
|
||||||
const out: Pt[] = []
|
|
||||||
let t = s
|
|
||||||
for (;;) {
|
|
||||||
const n = t >> 2
|
|
||||||
out.push([(n % W) + x0, Math.floor(n / W) + y0])
|
|
||||||
const pt = prev[t]!
|
|
||||||
if (pt < 0) break
|
|
||||||
t = pt
|
|
||||||
}
|
|
||||||
return simplify(out.reverse())
|
|
||||||
}
|
|
||||||
if (++visits > MAX_VISITS || --budget.left <= 0) return null
|
|
||||||
const x = (node % W) + x0
|
|
||||||
const y = Math.floor(node / W) + y0
|
|
||||||
for (let nd = 0; nd < 4; nd++) {
|
|
||||||
if (nd === (d ^ 1)) continue // no U-turns
|
|
||||||
// Leaving the source pin: straight out only.
|
|
||||||
if (prev[s]! < 0 && fromPin(s) && nd !== 0) continue
|
|
||||||
const nx = x + DX[nd]!
|
|
||||||
const ny = y + DY[nd]!
|
|
||||||
if (nx < x0 || ny < y0 || nx >= x0 + W || ny >= y0 + H) continue
|
|
||||||
// Into the target pin only from its left.
|
|
||||||
if (nx === b[0] && ny === b[1] && nd !== 0) continue
|
|
||||||
const e = step(x, y, nd)
|
|
||||||
if (e === Infinity) continue
|
|
||||||
const nc = c + e + (nd !== d ? TURN : 0)
|
|
||||||
const ns = id(nx, ny) * 4 + nd
|
|
||||||
if (nc < best[ns]!) {
|
|
||||||
best[ns] = nc
|
|
||||||
prev[ns] = s
|
|
||||||
heap.push(nc + est(nx, ny), ns)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Every grid point on a route, with the part of the route that leads to it. */
|
|
||||||
function pointsOn(route: Pt[]): { p: Pt; prefix: Pt[] }[] {
|
|
||||||
const out: { p: Pt; prefix: Pt[] }[] = []
|
|
||||||
for (let i = 0; i < route.length - 1; i++) {
|
|
||||||
const [ax, ay] = route[i]!
|
|
||||||
const [bx, by] = route[i + 1]!
|
|
||||||
const n = Math.abs(bx - ax) + Math.abs(by - ay)
|
|
||||||
const dx = Math.sign(bx - ax)
|
|
||||||
const dy = Math.sign(by - ay)
|
|
||||||
for (let k = i === 0 ? 1 : 0; k <= n; k++) {
|
|
||||||
const p: Pt = [ax + dx * k, ay + dy * k]
|
|
||||||
out.push({ p, prefix: [...route.slice(0, i + 1), p] })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
const routeLength = (r: Pt[]) => r.reduce((s, p, i) => (i ? s + Math.abs(p[0] - r[i - 1]![0]) + Math.abs(p[1] - r[i - 1]![1]) : 0), 0)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A wire of a signal that already has lines: it may branch off them, so the
|
|
||||||
* signal splits from one trunk. Tries the spots on each line nearest the
|
|
||||||
* target and keeps the shortest free branch.
|
|
||||||
*/
|
|
||||||
function branchRoute(input: RouteInput, trunk: Pt[][], occ: Occupancy, bodies: BodyIndex, pins: Set<number>, h: number): { route: Pt[]; added: number } | null {
|
|
||||||
const [bx, by] = input.b
|
|
||||||
let best: { route: Pt[]; added: number } | null = null
|
|
||||||
for (const t of trunk) {
|
|
||||||
for (let i = 0; i < t.length - 1; i++) {
|
|
||||||
const [ax, ay] = t[i]!
|
|
||||||
const [cx, cy] = t[i + 1]!
|
|
||||||
const spots: Pt[] = []
|
|
||||||
if (ay === cy) {
|
|
||||||
const lo = Math.min(ax, cx)
|
|
||||||
const hi = Math.max(ax, cx)
|
|
||||||
for (const k of [1, 2, 3]) spots.push([Math.max(lo, Math.min(hi, bx - k)), ay])
|
|
||||||
} else {
|
|
||||||
const lo = Math.min(ay, cy)
|
|
||||||
const hi = Math.max(ay, cy)
|
|
||||||
if (ax < bx) spots.push([ax, Math.max(lo, Math.min(hi, by))])
|
|
||||||
}
|
|
||||||
for (const p of spots) {
|
|
||||||
if (p[0] >= bx || (p[0] === t[0]![0] && p[1] === t[0]![1])) continue
|
|
||||||
const tail = routeWire(p, input.b)
|
|
||||||
const added = routeLength(tail)
|
|
||||||
if (best && added >= best.added) continue
|
|
||||||
if (cost(tail, input.net, occ, bodies, pins, Infinity, h, false).penalty > 0) continue
|
|
||||||
best = { route: simplify([...t.slice(0, i + 1), ...tail]), added }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return best
|
|
||||||
}
|
|
||||||
|
|
||||||
function autoRoute(input: RouteInput, occ: Occupancy, bodies: BodyIndex, pins: Set<number>, trunk: Pt[][], budget: { left: number }): Pt[] {
|
|
||||||
const h = input.h ?? WIRE_H
|
|
||||||
// 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 usual = routeWire(input.a, input.b)
|
||||||
const base = cost(usual, input.net, occ, bodies, pins, Infinity, h)
|
const base = cost(usual, input.net, occ, bodies, pins)
|
||||||
// Its signal is laid already: branch off it when that is free and no longer.
|
|
||||||
if (trunk.length) {
|
|
||||||
const branch = branchRoute(input, trunk, occ, bodies, pins, h)
|
|
||||||
if (branch && (base.penalty > 0 || branch.added <= routeLength(usual))) return branch.route
|
|
||||||
}
|
|
||||||
if (base.penalty === 0) return usual
|
if (base.penalty === 0) return usual
|
||||||
let best = usual
|
let best = usual
|
||||||
let bestCost = base.total
|
let bestCost = base.total
|
||||||
let bestPenalty = base.penalty
|
|
||||||
for (const c of candidates(input.a, input.b)) {
|
for (const c of candidates(input.a, input.b)) {
|
||||||
const route = simplify(c)
|
const route = simplify(c)
|
||||||
const k = cost(route, input.net, occ, bodies, pins, bestCost, h)
|
const k = cost(route, input.net, occ, bodies, pins, bestCost)
|
||||||
if (k.total < bestCost) {
|
if (k.total < bestCost) {
|
||||||
best = route
|
best = route
|
||||||
bestCost = k.total
|
bestCost = k.total
|
||||||
bestPenalty = k.penalty
|
|
||||||
if (k.penalty === 0 && route.length <= 4) break
|
if (k.penalty === 0 && route.length <= 4) break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (bestPenalty === 0) return best
|
|
||||||
// Still through a part or along another signal: search the grid, nearby first.
|
|
||||||
const branches = trunk.flatMap(pointsOn)
|
|
||||||
for (const margin of [6, 16]) {
|
|
||||||
const found = maze(input.a, input.b, branches.map(x => x.p), input.net, h, occ, bodies, pins, margin, budget)
|
|
||||||
if (!found) continue
|
|
||||||
// Started on a line of its own signal: the route runs along that line to there.
|
|
||||||
const from = found[0]!
|
|
||||||
const lead = from[0] === input.a[0] && from[1] === input.a[1] ? [] : (branches.find(x => x.p[0] === from[0] && x.p[1] === from[1])?.prefix.slice(0, -1) ?? [])
|
|
||||||
const route = simplify([...lead, ...found])
|
|
||||||
if (cost(route, input.net, occ, bodies, pins, Infinity, h, true).total < bestCost || bestPenalty >= BODY) return route
|
|
||||||
break
|
|
||||||
}
|
|
||||||
return best
|
return best
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -546,7 +228,6 @@ function separate(routes: Routed[]) {
|
||||||
lo: number
|
lo: number
|
||||||
hi: number
|
hi: number
|
||||||
net: string
|
net: string
|
||||||
h: number
|
|
||||||
}
|
}
|
||||||
const rows = new Map<number, Item[]>()
|
const rows = new Map<number, Item[]>()
|
||||||
const cols = new Map<number, Item[]>()
|
const cols = new Map<number, Item[]>()
|
||||||
|
|
@ -555,8 +236,8 @@ function separate(routes: Routed[]) {
|
||||||
for (let i = 0; i < p.length - 1; i++) {
|
for (let i = 0; i < p.length - 1; i++) {
|
||||||
const [ax, ay] = p[i]!
|
const [ax, ay] = p[i]!
|
||||||
const [bx, by] = p[i + 1]!
|
const [bx, by] = p[i + 1]!
|
||||||
if (ay === by && ax !== bx) push(rows, ay, { r, i, lo: Math.min(ax, bx), hi: Math.max(ax, bx), net: route.net, h: route.h })
|
if (ay === by && ax !== bx) push(rows, ay, { r, i, lo: Math.min(ax, bx), hi: Math.max(ax, bx), net: route.net })
|
||||||
else if (ax === bx && ay !== by) push(cols, ax, { r, i, lo: Math.min(ay, by), hi: Math.max(ay, by), net: route.net, h: route.h })
|
else if (ax === bx && ay !== by) push(cols, ax, { r, i, lo: Math.min(ay, by), hi: Math.max(ay, by), net: route.net })
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -571,24 +252,7 @@ function separate(routes: Routed[]) {
|
||||||
const flush = () => {
|
const flush = () => {
|
||||||
const nets = [...new Set(cluster.map(it => it.net))]
|
const nets = [...new Set(cluster.map(it => it.net))]
|
||||||
if (nets.length > 1) {
|
if (nets.length > 1) {
|
||||||
// The first stays, the others go alternately to either side, each
|
const lane = new Map(nets.map((n, k) => [n, k === 0 ? 0 : (k % 2 ? 1 : -1) * Math.ceil(k / 2) * LANE]))
|
||||||
// as far out as the widths of it and its neighbour need.
|
|
||||||
const width = new Map(cluster.map(it => [it.net, it.h]))
|
|
||||||
const lane = new Map<string, number>()
|
|
||||||
let up = width.get(nets[0]!)!
|
|
||||||
let down = up
|
|
||||||
nets.forEach((n, k) => {
|
|
||||||
const h = width.get(n)!
|
|
||||||
if (k === 0) return lane.set(n, 0)
|
|
||||||
// Next out from the edge reached so far on that side.
|
|
||||||
if (k % 2) {
|
|
||||||
lane.set(n, up + LANE_GAP + h)
|
|
||||||
up += LANE_GAP + 2 * h
|
|
||||||
} else {
|
|
||||||
lane.set(n, -(down + LANE_GAP + h))
|
|
||||||
down += LANE_GAP + 2 * h
|
|
||||||
}
|
|
||||||
})
|
|
||||||
for (const it of cluster) {
|
for (const it of cluster) {
|
||||||
const off = lane.get(it.net)!
|
const off = lane.get(it.net)!
|
||||||
if (off) push(shifts, it.r, { i: it.i, axis, off })
|
if (off) push(shifts, it.r, { i: it.i, axis, off })
|
||||||
|
|
@ -669,118 +333,6 @@ export function findCrossings(routes: Routed[]): Crossing[] {
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A hop on one segment: from lo to hi along it (grid units), r pixels high. */
|
|
||||||
export interface Hop {
|
|
||||||
lo: number
|
|
||||||
hi: number
|
|
||||||
r: number
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Where lines jump over each other. At each crossing of two signals the
|
|
||||||
* thinner line hops over the wider one (a wire over a cable), the horizontal
|
|
||||||
* one when both are as wide; when its segment has no room for the hop (too
|
|
||||||
* near a corner), the other one hops. A hop is as wide as the line it clears
|
|
||||||
* plus its own width, at least `minR` pixels; hops that would touch on one
|
|
||||||
* segment join into one longer bridge. Per route, per segment.
|
|
||||||
*/
|
|
||||||
export function planHops(routes: Routed[], minR = 5): Map<number, Map<number, Hop[]>> {
|
|
||||||
interface S {
|
|
||||||
r: number
|
|
||||||
seg: number
|
|
||||||
c: number
|
|
||||||
lo: number
|
|
||||||
hi: number
|
|
||||||
}
|
|
||||||
const hs: S[] = []
|
|
||||||
const vs: S[] = []
|
|
||||||
routes.forEach((route, r) => {
|
|
||||||
const p = route.draw
|
|
||||||
for (let i = 0; i < p.length - 1; i++) {
|
|
||||||
const [ax, ay] = p[i]!
|
|
||||||
const [bx, by] = p[i + 1]!
|
|
||||||
if (ay === by && ax !== bx) hs.push({ r, seg: i, c: ay, lo: Math.min(ax, bx), hi: Math.max(ax, bx) })
|
|
||||||
else if (ax === bx && ay !== by) vs.push({ r, seg: i, c: ax, lo: Math.min(ay, by), hi: Math.max(ay, by) })
|
|
||||||
}
|
|
||||||
})
|
|
||||||
vs.sort((p, q) => p.c - q.c)
|
|
||||||
const out = new Map<number, Map<number, Hop[]>>()
|
|
||||||
const add = (s: S, at: number, r: number) => {
|
|
||||||
const segs = out.get(s.r) ?? out.set(s.r, new Map()).get(s.r)!
|
|
||||||
const list = segs.get(s.seg) ?? segs.set(s.seg, []).get(s.seg)!
|
|
||||||
list.push({ lo: at - r / GRID, hi: at + r / GRID, r })
|
|
||||||
}
|
|
||||||
const fits = (s: S, at: number, r: number) => at - r / GRID >= s.lo + 0.15 && at + r / GRID <= s.hi - 0.15
|
|
||||||
for (const h of hs) {
|
|
||||||
// Verticals strictly inside this horizontal's span (binary search for the first).
|
|
||||||
let k = 0
|
|
||||||
let top = vs.length
|
|
||||||
while (k < top) {
|
|
||||||
const m = (k + top) >> 1
|
|
||||||
if (vs[m]!.c <= h.lo + EPS) k = m + 1
|
|
||||||
else top = m
|
|
||||||
}
|
|
||||||
for (; k < vs.length && vs[k]!.c < h.hi - EPS; k++) {
|
|
||||||
const v = vs[k]!
|
|
||||||
const hr = routes[h.r]!
|
|
||||||
const vr = routes[v.r]!
|
|
||||||
if (hr.net === vr.net || h.c <= v.lo + EPS || h.c >= v.hi - EPS) continue
|
|
||||||
const r = Math.max(minR, (hr.h + vr.h) * GRID + 2)
|
|
||||||
// The thinner one hops; as wide as each other, the horizontal one.
|
|
||||||
const order: [S, number][] = vr.h < hr.h - EPS ? [[v, h.c], [h, v.c]] : [[h, v.c], [v, h.c]]
|
|
||||||
const hop = order.find(([s, at]) => fits(s, at, r))
|
|
||||||
if (hop) add(hop[0], hop[1], r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Hops that would touch join into one.
|
|
||||||
for (const segs of out.values()) {
|
|
||||||
for (const [seg, list] of segs) {
|
|
||||||
list.sort((p, q) => p.lo - q.lo)
|
|
||||||
const merged: Hop[] = []
|
|
||||||
for (const hop of list) {
|
|
||||||
const last = merged[merged.length - 1]
|
|
||||||
if (last && hop.lo <= last.hi + 2 / GRID) {
|
|
||||||
last.hi = Math.max(last.hi, hop.hi)
|
|
||||||
last.r = Math.max(last.r, hop.r)
|
|
||||||
} else merged.push({ ...hop })
|
|
||||||
}
|
|
||||||
segs.set(seg, merged)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Where each route is crossed by (or crosses) a line of another signal, for labels to keep clear of. */
|
|
||||||
export function crossingPoints(routes: Routed[]): Map<number, Pt[]> {
|
|
||||||
const out = new Map<number, Pt[]>()
|
|
||||||
const verticals: { r: number; x: number; lo: number; hi: number }[] = []
|
|
||||||
routes.forEach((route, r) => {
|
|
||||||
const p = route.draw
|
|
||||||
for (let i = 0; i < p.length - 1; i++) {
|
|
||||||
const [ax, ay] = p[i]!
|
|
||||||
const [bx, by] = p[i + 1]!
|
|
||||||
if (ax === bx && ay !== by) verticals.push({ r, x: ax, lo: Math.min(ay, by), hi: Math.max(ay, by) })
|
|
||||||
}
|
|
||||||
})
|
|
||||||
routes.forEach((route, r) => {
|
|
||||||
const p = route.draw
|
|
||||||
for (let i = 0; i < p.length - 1; i++) {
|
|
||||||
const [ax, ay] = p[i]!
|
|
||||||
const [bx, by] = p[i + 1]!
|
|
||||||
if (ay !== by || ax === bx) continue
|
|
||||||
const lo = Math.min(ax, bx)
|
|
||||||
const hi = Math.max(ax, bx)
|
|
||||||
for (const v of verticals) {
|
|
||||||
if (routes[v.r]!.net === route.net || v.x <= lo + EPS || v.x >= hi - EPS || ay <= v.lo + EPS || ay >= v.hi - EPS) continue
|
|
||||||
const pt: Pt = [v.x, ay]
|
|
||||||
out.set(r, [...(out.get(r) ?? []), pt])
|
|
||||||
out.set(v.r, [...(out.get(v.r) ?? []), pt])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Tidy routing ────────────────────────────────────────────────────
|
// ── Tidy routing ────────────────────────────────────────────────────
|
||||||
// The way a panel builder wires a cabinet. Every forward wire takes its
|
// The way a panel builder wires a cabinet. Every forward wire takes its
|
||||||
// vertical step in the free gap right in front of the part it feeds. All
|
// vertical step in the free gap right in front of the part it feeds. All
|
||||||
|
|
@ -874,13 +426,13 @@ function tidyRoutes(inputs: RouteInput[], boxes: Box[], occ: Occupancy, bodies:
|
||||||
// sorted together, so separate bundles can't end up crossing each other.
|
// 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 }> }>()
|
const gaps = new Map<number, { hi: number; nets: Map<string, TidyNet & { lo: number }> }>()
|
||||||
for (const w of inputs) {
|
for (const w of inputs) {
|
||||||
if (grid.has(w.id) || reversed(w)) continue
|
if (grid.has(w.id)) continue
|
||||||
const [x1, y1] = w.a
|
const [x1, y1] = w.a
|
||||||
const [x2, y2] = w.b
|
const [x2, y2] = w.b
|
||||||
if (x2 < x1 + 2) continue // feedback wires keep the usual router
|
if (x2 < x1 + 2) continue // feedback wires keep the usual router
|
||||||
if (y1 === y2 && cost([w.a, w.b], w.net, occ, bodies, pins, Infinity, w.h).penalty === 0) {
|
if (y1 === y2 && cost([w.a, w.b], w.net, occ, bodies, pins).penalty === 0) {
|
||||||
grid.set(w.id, [w.a, w.b])
|
grid.set(w.id, [w.a, w.b])
|
||||||
occ.add([w.a, w.b], w.net, w.h)
|
occ.add([w.a, w.b], w.net)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
const min = Math.min(y1, y2)
|
const min = Math.min(y1, y2)
|
||||||
|
|
@ -923,12 +475,11 @@ function tidyRoutes(inputs: RouteInput[], boxes: Box[], occ: Occupancy, bodies:
|
||||||
// Through a part, or along another signal's line: the usual router finds a way around.
|
// Through a part, or along another signal's line: the usual router finds a way around.
|
||||||
let blocked = false
|
let blocked = false
|
||||||
for (let s = 0; s < route.length - 1 && !blocked; s++) {
|
for (let s = 0; s < route.length - 1 && !blocked; s++) {
|
||||||
const h = w.h ?? WIRE_H
|
blocked = bodies.hits(route[s]!, route[s + 1]!) > 0 || occ.overlap(route[s]!, route[s + 1]!, w.net) > 0
|
||||||
blocked = bodies.hits(route[s]!, route[s + 1]!, h, s === 0, s === route.length - 2) > 0 || occ.overlap(route[s]!, route[s + 1]!, w.net, h) > 0
|
|
||||||
}
|
}
|
||||||
if (blocked) continue
|
if (blocked) continue
|
||||||
grid.set(w.id, route)
|
grid.set(w.id, route)
|
||||||
occ.add(route, w.net, w.h)
|
occ.add(route, w.net)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -937,8 +488,6 @@ function tidyRoutes(inputs: RouteInput[], boxes: Box[], occ: Occupancy, bodies:
|
||||||
export interface RouteOptions {
|
export interface RouteOptions {
|
||||||
/** Electrician-style layout for wires without hand-placed corners. */
|
/** Electrician-style layout for wires without hand-placed corners. */
|
||||||
tidy?: boolean
|
tidy?: boolean
|
||||||
/** Drawn width of a wire in pixels (a cable's sleeve); plain wires otherwise. */
|
|
||||||
widthOf?: (wireId: string) => number | undefined
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function routeAll(inputs: RouteInput[], bodies: Box[], pins: Pt[], opts: RouteOptions = {}): Routed[] {
|
export function routeAll(inputs: RouteInput[], bodies: Box[], pins: Pt[], opts: RouteOptions = {}): Routed[] {
|
||||||
|
|
@ -953,26 +502,18 @@ export function routeAll(inputs: RouteInput[], bodies: Box[], pins: Pt[], opts:
|
||||||
if (!w.pts?.length || grid.has(w.id)) continue
|
if (!w.pts?.length || grid.has(w.id)) continue
|
||||||
const r = routeWire(w.a, w.b, w.pts)
|
const r = routeWire(w.a, w.b, w.pts)
|
||||||
grid.set(w.id, r)
|
grid.set(w.id, r)
|
||||||
occ.add(r, w.net, w.h)
|
occ.add(r, w.net)
|
||||||
}
|
}
|
||||||
if (opts.tidy) tidyRoutes(inputs, bodies, occ, bodyIndex, pinSet, grid)
|
if (opts.tidy) tidyRoutes(inputs, bodies, occ, bodyIndex, pinSet, grid)
|
||||||
// Lines of each signal so far, for the next wire of it to branch off.
|
|
||||||
const trunks = new Map<string, Pt[][]>()
|
|
||||||
for (const w of inputs) {
|
|
||||||
const g = grid.get(w.id)
|
|
||||||
if (g && g.length > 1) trunks.set(w.net, [...(trunks.get(w.net) ?? []), g])
|
|
||||||
}
|
|
||||||
const budget = { left: ALL_VISITS }
|
|
||||||
for (const w of inputs) {
|
for (const w of inputs) {
|
||||||
if (grid.has(w.id)) continue
|
if (grid.has(w.id)) continue
|
||||||
const r = autoRoute(w, occ, bodyIndex, pinSet, trunks.get(w.net) ?? [], budget)
|
const r = autoRoute(w, occ, bodyIndex, pinSet)
|
||||||
grid.set(w.id, r)
|
grid.set(w.id, r)
|
||||||
occ.add(r, w.net, w.h)
|
occ.add(r, w.net)
|
||||||
trunks.set(w.net, [...(trunks.get(w.net) ?? []), r])
|
|
||||||
}
|
}
|
||||||
const routes = inputs.map(w => {
|
const routes = inputs.map(w => {
|
||||||
const g = grid.get(w.id)!
|
const g = grid.get(w.id)!
|
||||||
return { id: w.id, net: w.net, grid: g, draw: g.map(p => [p[0], p[1]] as Pt), h: w.h ?? WIRE_H }
|
return { id: w.id, net: w.net, grid: g, draw: g.map(p => [p[0], p[1]] as Pt) }
|
||||||
})
|
})
|
||||||
separate(routes)
|
separate(routes)
|
||||||
return routes
|
return routes
|
||||||
|
|
@ -980,20 +521,14 @@ export function routeAll(inputs: RouteInput[], bodies: Box[], pins: Pt[], opts:
|
||||||
|
|
||||||
/** Routes every wire of a circuit, given the shapes of its parts. */
|
/** Routes every wire of a circuit, given the shapes of its parts. */
|
||||||
export function circuitRoutes(def: ComponentDef, shapes: Map<string, Shape>, opts: RouteOptions = {}): Routed[] {
|
export function circuitRoutes(def: ComponentDef, shapes: Map<string, Shape>, opts: RouteOptions = {}): Routed[] {
|
||||||
const c = circuitOf(def, shapes, opts)
|
|
||||||
return routeAll(c.inputs, [...c.bodies.values()], [...c.pins.values()].flat(), opts)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A circuit's wires to route, and the body and pins of each of its parts (by part id). */
|
|
||||||
function circuitOf(def: ComponentDef, shapes: Map<string, Shape>, opts: RouteOptions) {
|
|
||||||
const nodes = new Map(def.nodes.map(n => [n.id, n]))
|
const nodes = new Map(def.nodes.map(n => [n.id, n]))
|
||||||
const bodies = new Map<string, Box>()
|
const bodies: Box[] = []
|
||||||
const pins = new Map<string, Pt[]>()
|
const pins: Pt[] = []
|
||||||
for (const n of def.nodes) {
|
for (const n of def.nodes) {
|
||||||
const s = shapes.get(n.id)
|
const s = shapes.get(n.id)
|
||||||
if (!s) continue
|
if (!s) continue
|
||||||
if (n.kind !== 'note') bodies.set(n.id, { x: n.x + s.body.x, y: n.y + s.body.y, w: s.body.w, h: s.body.h })
|
if (n.kind !== 'note') bodies.push({ x: n.x + s.body.x, y: n.y + s.body.y, w: s.body.w, h: s.body.h })
|
||||||
pins.set(n.id, [...s.inputs, ...s.outputs].map(p => [n.x + p.dx, n.y + p.dy] as Pt))
|
for (const p of [...s.inputs, ...s.outputs]) pins.push([n.x + p.dx, n.y + p.dy])
|
||||||
}
|
}
|
||||||
const inputs: RouteInput[] = []
|
const inputs: RouteInput[] = []
|
||||||
for (const w of def.wires) {
|
for (const w of def.wires) {
|
||||||
|
|
@ -1003,118 +538,7 @@ function circuitOf(def: ComponentDef, shapes: Map<string, Shape>, opts: RouteOpt
|
||||||
const a = pinPos(fn, shapes.get(fn.id)!, w.from.pin, 'out')
|
const a = pinPos(fn, shapes.get(fn.id)!, w.from.pin, 'out')
|
||||||
const b = pinPos(tn, shapes.get(tn.id)!, w.to.pin, 'in')
|
const b = pinPos(tn, shapes.get(tn.id)!, w.to.pin, 'in')
|
||||||
if (!a || !b) continue
|
if (!a || !b) continue
|
||||||
const px = opts.widthOf?.(w.id)
|
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 } : {}),
|
|
||||||
...(px ? { h: px / 2 / GRID } : {}),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
return { inputs, bodies, pins }
|
return routeAll(inputs, bodies, pins, opts)
|
||||||
}
|
|
||||||
|
|
||||||
// ── Corners after a move ────────────────────────────────────────────
|
|
||||||
// Hand-placed corners are fixed lines the router routes around, so after
|
|
||||||
// parts move they are looked at again by the router's own rules: a route
|
|
||||||
// through them must not run over or under a part (by its full width), along
|
|
||||||
// a line of another signal or over someone else's pin. Only wires that
|
|
||||||
// moved or that a moved part now lies on are looked at.
|
|
||||||
|
|
||||||
export interface Moved {
|
|
||||||
/** How far each part that moved went. */
|
|
||||||
by: Map<string, Pt>
|
|
||||||
/** Wires whose corners went along with the parts. */
|
|
||||||
carried: Set<string>
|
|
||||||
}
|
|
||||||
|
|
||||||
type Side = 'a' | 'b' | ''
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Hand-placed corners after parts moved. A wire carried along whole keeps
|
|
||||||
* its corners unless something that did not come along is now in its way.
|
|
||||||
* A wire with a moved end keeps the corners on the side that stayed for as
|
|
||||||
* long as the route through them is clear, and lets go of the others; a
|
|
||||||
* wire that a moved part now lies on does the same from either side. What
|
|
||||||
* is let go the router lays out. Returns the corners of every wire looked
|
|
||||||
* at again; null where none are left.
|
|
||||||
*/
|
|
||||||
export function settleCorners(def: ComponentDef, shapes: Map<string, Shape>, moved: Moved, opts: RouteOptions = {}): Map<string, Pt[] | null> {
|
|
||||||
const out = new Map<string, Pt[] | null>()
|
|
||||||
if (!moved.by.size) return out
|
|
||||||
const { inputs, bodies, pins } = circuitOf(def, shapes, opts)
|
|
||||||
const wires = new Map(def.wires.map(w => [w.id, w]))
|
|
||||||
// How far a part went, as a key: parts with the same one moved together.
|
|
||||||
const went = (id: string) => `${moved.by.get(id) ?? [0, 0]}`
|
|
||||||
// The parts that did not go the same way, with their pins: what can be in the way of a wire that came along.
|
|
||||||
const apart = new Map<string, { bodies: BodyIndex; pins: Set<number> }>()
|
|
||||||
const apartFrom = (k: string) => {
|
|
||||||
let s = apart.get(k)
|
|
||||||
if (!s) {
|
|
||||||
const ids = new Set(def.nodes.filter(n => went(n.id) !== k).map(n => n.id))
|
|
||||||
const of = <T>(m: Map<string, T>) => [...m].filter(([id]) => ids.has(id)).map(([, v]) => v)
|
|
||||||
s = { bodies: new BodyIndex(of(bodies)), pins: pinKeys(of(pins).flat()) }
|
|
||||||
apart.set(k, s)
|
|
||||||
}
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
const hand = inputs.filter(w => w.pts?.length && (w.a[0] !== w.b[0] || w.a[1] !== w.b[1]))
|
|
||||||
const occ = new Occupancy()
|
|
||||||
const look = new Map<RouteInput, Side>()
|
|
||||||
const whole: RouteInput[] = []
|
|
||||||
// The parts that did not stay where they were.
|
|
||||||
const moving = apartFrom('0,0')
|
|
||||||
const none = new Occupancy()
|
|
||||||
for (const w of hand) {
|
|
||||||
const { from, to } = wires.get(w.id)!
|
|
||||||
const a = moved.by.has(from.node)
|
|
||||||
const b = moved.by.has(to.node)
|
|
||||||
if (moved.carried.has(w.id)) {
|
|
||||||
if (a && b && went(from.node) === went(to.node)) whole.push(w)
|
|
||||||
else look.set(w, '')
|
|
||||||
} else if (a || b) look.set(w, a && b ? '' : a ? 'b' : 'a')
|
|
||||||
else {
|
|
||||||
// Its ends stayed: looked at when a moved part, or a pin of one, now lies on it.
|
|
||||||
const r = routeWire(w.a, w.b, w.pts)
|
|
||||||
if (cost(r, w.net, none, moving.bodies, moving.pins, Infinity, w.h).penalty > 0) look.set(w, '')
|
|
||||||
else occ.add(r, w.net, w.h)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Carried along whole: only what did not come along, and the lines that stay, can be in the way.
|
|
||||||
const clear = whole.filter(w => {
|
|
||||||
const s = apartFrom(went(wires.get(w.id)!.from.node))
|
|
||||||
const ok = cost(routeWire(w.a, w.b, w.pts), w.net, occ, s.bodies, s.pins, Infinity, w.h).penalty === 0
|
|
||||||
if (!ok) look.set(w, '')
|
|
||||||
return ok
|
|
||||||
})
|
|
||||||
for (const w of clear) occ.add(routeWire(w.a, w.b, w.pts), w.net, w.h)
|
|
||||||
const all = { bodies: new BodyIndex([...bodies.values()]), pins: pinKeys([...pins.values()].flat()) }
|
|
||||||
for (const w of hand) {
|
|
||||||
const side = look.get(w)
|
|
||||||
if (side === undefined) continue
|
|
||||||
const kept = keepCorners(w, side, occ, all.bodies, all.pins)
|
|
||||||
out.set(w.id, kept)
|
|
||||||
if (kept) occ.add(routeWire(w.a, w.b, kept), w.net, w.h)
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The most hand-placed corners of a wire that still make a clear route,
|
|
||||||
* counted from its source ('a'), its target ('b') or either end (''), given
|
|
||||||
* as the corners of that route. Null when no corners do.
|
|
||||||
*/
|
|
||||||
function keepCorners(w: RouteInput, side: Side, occ: Occupancy, bodies: BodyIndex, pins: Set<number>): Pt[] | null {
|
|
||||||
const pts = w.pts!
|
|
||||||
for (let k = pts.length; k > 0; k--) {
|
|
||||||
for (const from of side ? [side] : k === pts.length ? ['a'] : ['a', 'b']) {
|
|
||||||
const route = routeWire(w.a, w.b, from === 'a' ? pts.slice(0, k) : pts.slice(pts.length - k))
|
|
||||||
if (route.length > 2 && cost(route, w.net, occ, bodies, pins, Infinity, w.h).penalty === 0) return route.slice(1, -1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,47 +0,0 @@
|
||||||
// The logic analyzer part's box: an input pin per bit down the left, the
|
|
||||||
// title bar on top, and a lane per channel beside its pins, the channel's
|
|
||||||
// value now and its wave over the last samples.
|
|
||||||
|
|
||||||
import { colKeys, colPinNames } from './benchLayout'
|
|
||||||
import type { CircuitNode, ScopeCol } from './types'
|
|
||||||
|
|
||||||
/** Samples a lane shows, and pixels each. */
|
|
||||||
export const SCOPE_SAMPLES = 96
|
|
||||||
export const SCOPE_CELL = 4
|
|
||||||
const CHAR = 0.4
|
|
||||||
|
|
||||||
export interface ScopeLane {
|
|
||||||
col: ScopeCol
|
|
||||||
/** First pin row and how many. */
|
|
||||||
row: number
|
|
||||||
bits: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ScopeLayout {
|
|
||||||
w: number
|
|
||||||
h: number
|
|
||||||
pins: { key: string; label: string; dy: number }[]
|
|
||||||
lanes: ScopeLane[]
|
|
||||||
/** Where the value column and the waves start, in grid units. */
|
|
||||||
valueX: number
|
|
||||||
waveX: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export function scopeLayout(node: CircuitNode): ScopeLayout {
|
|
||||||
const cols = node.scope?.cols ?? []
|
|
||||||
const pins: ScopeLayout['pins'] = []
|
|
||||||
const lanes: ScopeLane[] = []
|
|
||||||
let row = 1
|
|
||||||
for (const c of cols) {
|
|
||||||
const names = colPinNames(c)
|
|
||||||
colKeys(c).forEach((key, i) => pins.push({ key, label: names[i]!, dy: row + i }))
|
|
||||||
lanes.push({ col: c, row, bits: c.bits })
|
|
||||||
row += c.bits
|
|
||||||
}
|
|
||||||
const lw = pins.length ? Math.max(...pins.map(p => p.label.length)) * CHAR + 0.7 : 0.4
|
|
||||||
const valueX = lw + 0.2
|
|
||||||
const valueW = Math.max(2, ...cols.map(c => (c.bits === 1 ? 1 : String(2 ** c.bits - 1).length + Math.ceil(c.bits / 4) + 4))) * CHAR + 0.4
|
|
||||||
const waveX = valueX + valueW
|
|
||||||
const w = cols.length ? Math.ceil(waveX + (SCOPE_SAMPLES * SCOPE_CELL) / 16 + 0.4) : 12
|
|
||||||
return { w, h: Math.max(row + 0.5, 2.5), pins, lanes, valueX, waveX }
|
|
||||||
}
|
|
||||||
|
|
@ -5,9 +5,7 @@
|
||||||
// "oscillating".
|
// "oscillating".
|
||||||
|
|
||||||
import { HIGH, type Netlist } from './compile'
|
import { HIGH, type Netlist } from './compile'
|
||||||
import { flow } from './state'
|
|
||||||
|
|
||||||
/** Gate outputs and clock levels to start from, by key (see state.ts for what is saved). */
|
|
||||||
export interface SimCarry {
|
export interface SimCarry {
|
||||||
gates: Map<string, number>
|
gates: Map<string, number>
|
||||||
/** Level of all clocks when they ran in lockstep; per-clock levels win. */
|
/** Level of all clocks when they ran in lockstep; per-clock levels win. */
|
||||||
|
|
@ -40,9 +38,8 @@ export class Simulator {
|
||||||
}
|
}
|
||||||
this.clock = carry.clock
|
this.clock = carry.clock
|
||||||
nl.clocks.forEach((c, i) => (this.values[c] = carry.clocks?.get(nl.clockKeys[i]!) ?? carry.clock))
|
nl.clocks.forEach((c, i) => (this.values[c] = carry.clocks?.get(nl.clockKeys[i]!) ?? carry.clock))
|
||||||
// Gates run in the order signals flow, so a latch reads its inputs only once they are right and keeps its bit.
|
}
|
||||||
for (const g of flow(nl).order) this.push(g)
|
for (let i = 0; i < gates; i++) this.push(i)
|
||||||
} else for (let i = 0; i < gates; i++) this.push(i)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private push(g: number) {
|
private push(g: number) {
|
||||||
|
|
|
||||||
|
|
@ -1,137 +0,0 @@
|
||||||
// What a circuit remembers between visits and saves, like the contents of a
|
|
||||||
// memory chip. Only gates on feedback loops (latches, flip-flops, registers,
|
|
||||||
// RAM built from NANDs) can hold a bit; every other gate follows from its
|
|
||||||
// inputs. So only the loop gates that are 1 are kept, plus the clocks that
|
|
||||||
// are high, written small enough to save with the project.
|
|
||||||
|
|
||||||
import type { Netlist } from './compile'
|
|
||||||
import type { SimCarry, Simulator } from './sim'
|
|
||||||
import type { HeldState } from './types'
|
|
||||||
|
|
||||||
export interface Flow {
|
|
||||||
/** Every gate once, each after the gates that feed it; the gates of a loop after what feeds the loop. */
|
|
||||||
order: Int32Array
|
|
||||||
/** 1 for gates on a feedback loop. */
|
|
||||||
loop: Uint8Array
|
|
||||||
}
|
|
||||||
|
|
||||||
const flows = new WeakMap<Netlist, Flow>()
|
|
||||||
|
|
||||||
/** Which gates sit on a loop, and the order signals flow in. Tarjan's method without recursion, so a CPU can't run out of stack; kept per netlist. */
|
|
||||||
export function flow(nl: Netlist): Flow {
|
|
||||||
const known = flows.get(nl)
|
|
||||||
if (known) return known
|
|
||||||
const { gateA, gateB, gateOut, fanStart, fanList } = nl
|
|
||||||
const n = gateOut.length
|
|
||||||
const index = new Int32Array(n).fill(-1)
|
|
||||||
const low = new Int32Array(n)
|
|
||||||
const onStack = new Uint8Array(n)
|
|
||||||
const stack = new Int32Array(n)
|
|
||||||
const path = new Int32Array(n)
|
|
||||||
const edge = new Int32Array(n)
|
|
||||||
const loop = new Uint8Array(n)
|
|
||||||
// A group of gates is finished after every group it feeds, so the order fills from the back.
|
|
||||||
const order = new Int32Array(n)
|
|
||||||
let done = n
|
|
||||||
let sp = 0
|
|
||||||
let next = 0
|
|
||||||
for (let root = 0; root < n; root++) {
|
|
||||||
if (index[root]! >= 0) continue
|
|
||||||
let depth = 0
|
|
||||||
path[0] = root
|
|
||||||
index[root] = low[root] = next++
|
|
||||||
stack[sp++] = root
|
|
||||||
onStack[root] = 1
|
|
||||||
edge[root] = fanStart[gateOut[root]!]!
|
|
||||||
while (depth >= 0) {
|
|
||||||
const g = path[depth]!
|
|
||||||
if (edge[g]! < fanStart[gateOut[g]! + 1]!) {
|
|
||||||
const r = fanList[edge[g]!++]!
|
|
||||||
if (index[r]! < 0) {
|
|
||||||
index[r] = low[r] = next++
|
|
||||||
stack[sp++] = r
|
|
||||||
onStack[r] = 1
|
|
||||||
edge[r] = fanStart[gateOut[r]!]!
|
|
||||||
path[++depth] = r
|
|
||||||
} else if (onStack[r]) low[g] = Math.min(low[g]!, index[r]!)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if (low[g] === index[g]) {
|
|
||||||
const end = done
|
|
||||||
let r: number
|
|
||||||
do {
|
|
||||||
r = stack[--sp]!
|
|
||||||
onStack[r] = 0
|
|
||||||
order[--done] = r
|
|
||||||
} while (r !== g)
|
|
||||||
if (end - done > 1) {
|
|
||||||
// Inside a loop the gates keep the order they were placed in, which decides how a new latch starts (see ex-sr).
|
|
||||||
order.subarray(done, end).sort()
|
|
||||||
for (let i = done; i < end; i++) loop[order[i]!] = 1
|
|
||||||
} else if (gateA[g] === gateOut[g] || gateB[g] === gateOut[g]) {
|
|
||||||
// A gate on its own is a loop when it reads its own output.
|
|
||||||
loop[g] = 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
depth--
|
|
||||||
if (depth >= 0) low[path[depth]!] = Math.min(low[path[depth]!]!, low[g]!)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const res = { order, loop }
|
|
||||||
flows.set(nl, res)
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What the circuit holds right now, ready to save; undefined when nothing is 1.
|
|
||||||
* A gate's key is its path of node ids ("chipNode/chipNode/nand"): each id goes
|
|
||||||
* in `names` once, and a gate is written as how many levels of its path it
|
|
||||||
* shares with the gate before it, then the indexes of the rest. Gates come
|
|
||||||
* chip by chip, so most share all but the last level or two.
|
|
||||||
*/
|
|
||||||
export function packState(sim: Simulator): HeldState | undefined {
|
|
||||||
const { nl, values } = sim
|
|
||||||
const { loop } = flow(nl)
|
|
||||||
const names: string[] = []
|
|
||||||
const index = new Map<string, number>()
|
|
||||||
const on: string[] = []
|
|
||||||
let prev: string[] = []
|
|
||||||
for (let g = 0; g < loop.length; g++) {
|
|
||||||
if (!loop[g] || !values[nl.gateOut[g]!]) continue
|
|
||||||
const path = nl.gateKeys[g]!.split('/')
|
|
||||||
let shared = 0
|
|
||||||
while (shared < path.length - 1 && path[shared] === prev[shared]) shared++
|
|
||||||
const rest = path.slice(shared).map(id => {
|
|
||||||
let i = index.get(id)
|
|
||||||
if (i === undefined) {
|
|
||||||
i = names.push(id) - 1
|
|
||||||
index.set(id, i)
|
|
||||||
}
|
|
||||||
return i.toString(36)
|
|
||||||
})
|
|
||||||
on.push(`${shared.toString(36)}:${rest.join('.')}`)
|
|
||||||
prev = path
|
|
||||||
}
|
|
||||||
const clocks = nl.clockKeys.filter((_, i) => values[nl.clocks[i]!])
|
|
||||||
if (!on.length && !clocks.length) return undefined
|
|
||||||
const held: HeldState = { names, on: on.join(' ') }
|
|
||||||
if (clocks.length) held.clocks = clocks
|
|
||||||
return held
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Saved bits as the simulator's carry for this netlist: loop gates not named are 0, and so are clocks. */
|
|
||||||
export function stateCarry(held: HeldState, nl: Netlist): SimCarry {
|
|
||||||
const gates = new Map<string, number>()
|
|
||||||
let prev: string[] = []
|
|
||||||
for (const gate of held.on.split(' ')) {
|
|
||||||
const [shared, rest] = gate.split(':')
|
|
||||||
if (!shared || !rest) continue
|
|
||||||
// A broken entry makes a key no gate has, which is ignored like one that no longer exists.
|
|
||||||
const path = [...prev.slice(0, parseInt(shared, 36)), ...rest.split('.').map(i => held.names[parseInt(i, 36)] ?? '')]
|
|
||||||
gates.set(path.join('/'), 1)
|
|
||||||
prev = path
|
|
||||||
}
|
|
||||||
const high = new Set(held.clocks ?? [])
|
|
||||||
const clocks = new Map(nl.clockKeys.map(k => [k, high.has(k) ? 1 : 0]))
|
|
||||||
return { gates, clock: high.size ? 1 : 0, clocks }
|
|
||||||
}
|
|
||||||
|
|
@ -37,7 +37,6 @@ const CURRENT = 'logigate:current'
|
||||||
const LEGACY = 'logigate:project:v1'
|
const LEGACY = 'logigate:project:v1'
|
||||||
const ACCOUNT = 'logigate:account'
|
const ACCOUNT = 'logigate:account'
|
||||||
const PENDING_DELETES = 'logigate:pending-deletes'
|
const PENDING_DELETES = 'logigate:pending-deletes'
|
||||||
const LIBRARY_KEYS = 'logigate:library-keys'
|
|
||||||
const entry = (id: string) => `logigate:p:${id}`
|
const entry = (id: string) => `logigate:p:${id}`
|
||||||
|
|
||||||
function read(key: string): string | null {
|
function read(key: string): string | null {
|
||||||
|
|
@ -158,29 +157,3 @@ export function pendingDeletes(): { owner: string; id: string }[] {
|
||||||
export function setPendingDeletes(list: { owner: string; id: string }[]) {
|
export function setPendingDeletes(list: { owner: string; id: string }[]) {
|
||||||
write(PENDING_DELETES, JSON.stringify(list))
|
write(PENDING_DELETES, JSON.stringify(list))
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A library entry published from this browser. */
|
|
||||||
export interface LibraryKey {
|
|
||||||
/** Edit key: updates or removes the entry. */
|
|
||||||
key: string
|
|
||||||
/** The project and component it was published from. */
|
|
||||||
project: string
|
|
||||||
def: string
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Library entries published from this browser, by entry id. Never part of a project, so whoever gets a copy of it can't change them. */
|
|
||||||
export function libraryKeys(): Record<string, LibraryKey> {
|
|
||||||
try {
|
|
||||||
const keys = JSON.parse(read(LIBRARY_KEYS) ?? '{}')
|
|
||||||
return keys && typeof keys === 'object' && !Array.isArray(keys) ? keys : {}
|
|
||||||
} catch {
|
|
||||||
return {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function setLibraryKey(id: string, own: LibraryKey | null) {
|
|
||||||
const keys = libraryKeys()
|
|
||||||
if (own) keys[id] = own
|
|
||||||
else delete keys[id]
|
|
||||||
write(LIBRARY_KEYS, JSON.stringify(keys))
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -18,16 +18,8 @@ export type BuiltinKind =
|
||||||
| 'bundle' // gathers several wires into one cable
|
| 'bundle' // gathers several wires into one cable
|
||||||
| 'split' // fans a cable out into its wires again
|
| '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
|
| '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)
|
| '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
|
| 'ref' // carries the signal of the tag with the same name in this circuit, without a wire
|
||||||
| 'terminal' // a text screen: writes the character on D0–D7 at a rising WR, clears at a rising CLR
|
|
||||||
| 'monitor' // a screen of pixels, one bit each: a rising WR sets the pixel at X, Y to D; a rising CLR clears it
|
|
||||||
| 'rgbmonitor' // the same in eight colours: R, G, B instead of D
|
|
||||||
| 'keyboard' // the keys you type: the first waiting one on D0–D7, RDY while one waits, a rising NEXT takes it
|
|
||||||
| 'bench' // a table of tests: drives the circuit from its outputs, checks what comes back on its inputs
|
|
||||||
| 'scope' // logic analyzer: the signals on its inputs over time, drawn on its box
|
|
||||||
|
|
||||||
export type NodeKind = BuiltinKind | 'chip'
|
export type NodeKind = BuiltinKind | 'chip'
|
||||||
|
|
||||||
|
|
@ -56,8 +48,6 @@ export interface CircuitNode {
|
||||||
autoLabel?: boolean
|
autoLabel?: boolean
|
||||||
/** Number of wires in the cable of a bundle or split. */
|
/** Number of wires in the cable of a bundle or split. */
|
||||||
bits?: number
|
bits?: number
|
||||||
/** Port: the connector type (id in the project's connectors). */
|
|
||||||
conn?: string
|
|
||||||
/** Rows of a panel, top to bottom. */
|
/** Rows of a panel, top to bottom. */
|
||||||
rows?: PanelRow[]
|
rows?: PanelRow[]
|
||||||
/** Panel docked to a component: the id of that chip node. Its rows follow the chip's input pins. */
|
/** Panel docked to a component: the id of that chip node. Its rows follow the chip's input pins. */
|
||||||
|
|
@ -66,8 +56,6 @@ export interface CircuitNode {
|
||||||
skip?: string[]
|
skip?: string[]
|
||||||
/** Cable end plugged straight into a part: the id of that part. It sits on the part's pins and moves with it. */
|
/** Cable end plugged straight into a part: the id of that part. It sits on the part's pins and moves with it. */
|
||||||
plug?: string
|
plug?: string
|
||||||
/** Part latched straight onto another: the id of that part. Its shared pins touch, and it moves with it. */
|
|
||||||
latch?: string
|
|
||||||
/** Grid rows from one wire of a cable end to the next. Empty: 1. */
|
/** Grid rows from one wire of a cable end to the next. Empty: 1. */
|
||||||
pitch?: number
|
pitch?: number
|
||||||
/** Cable end plugged into pins that are not evenly spaced: each wire's row below the first. */
|
/** Cable end plugged into pins that are not evenly spaced: each wire's row below the first. */
|
||||||
|
|
@ -80,50 +68,6 @@ export interface CircuitNode {
|
||||||
inner?: boolean
|
inner?: boolean
|
||||||
/** Pixel: the screen it belongs to on the component's box; pixels without one make the main screen. */
|
/** Pixel: the screen it belongs to on the component's box; pixels without one make the main screen. */
|
||||||
screen?: string
|
screen?: string
|
||||||
/** Terminal: characters wide and lines; monitors: pixels wide and high. Empty: the part's starting size. */
|
|
||||||
dims?: [number, number]
|
|
||||||
/** Pixel with three inputs, red, green and blue: eight colours. */
|
|
||||||
rgb?: boolean
|
|
||||||
/** Test bench: its columns and tests. */
|
|
||||||
bench?: Bench
|
|
||||||
/** Logic analyzer: its channels. */
|
|
||||||
scope?: { cols: ScopeCol[] }
|
|
||||||
/** Component: its connector ports (port node ids inside) shown split on this box, with a pin per line to wire by hand. */
|
|
||||||
splitPorts?: string[]
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A test bench (see lib/logic/bench). */
|
|
||||||
export interface Bench {
|
|
||||||
/** Its columns: each a group of pins, as many bits as it has. */
|
|
||||||
cols?: BenchCol[]
|
|
||||||
rows: BenchRow[]
|
|
||||||
/** Left from the first version, which tested the component it was docked to: that chip node. Turned into columns and wires on loading. */
|
|
||||||
on?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface BenchCol {
|
|
||||||
/** Stays when the column is renamed, so its wires stay too. */
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
bits: number
|
|
||||||
/** 'drive': output pins the bench sets; 'check': input pins it reads and checks. */
|
|
||||||
dir: 'drive' | 'check'
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A channel of a logic analyzer: as many input pins as bits, read as one number. */
|
|
||||||
export interface ScopeCol {
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
bits: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface BenchRow {
|
|
||||||
/** Cells of the drive columns by column id: a number, P for a pulse; empty leaves it. */
|
|
||||||
set?: Record<string, string>
|
|
||||||
/** Cells of the check columns by column id: the number it should read; empty for any. */
|
|
||||||
expect?: Record<string, string>
|
|
||||||
/** N ticks before the check, or ≤N to wait up to N. */
|
|
||||||
ticks?: string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const PANEL_CONTROLS = ['switch', 'button', 'clock'] as const
|
export const PANEL_CONTROLS = ['switch', 'button', 'clock'] as const
|
||||||
|
|
@ -191,29 +135,6 @@ export interface ComponentDef {
|
||||||
wide?: { base: string; n: number }
|
wide?: { base: string; n: number }
|
||||||
/** The component's box drawn by hand; empty: laid out automatically. */
|
/** The component's box drawn by hand; empty: laid out automatically. */
|
||||||
design?: FaceDesign
|
design?: FaceDesign
|
||||||
/** Set when the component came from the public library (or was published there from here). */
|
|
||||||
from?: LibraryOrigin
|
|
||||||
/** Signals watched in the logic analyzer, top to bottom. */
|
|
||||||
probes?: Probe[]
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A signal watched in the logic analyzer: a pin of a part (a cable pin reads the whole cable). */
|
|
||||||
export interface Probe {
|
|
||||||
node: string
|
|
||||||
pin: string
|
|
||||||
/** A name of its own for the analyzer. */
|
|
||||||
label?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Where a component of the public library came from: the entry, its version and who published it. */
|
|
||||||
export interface LibraryOrigin {
|
|
||||||
/** Id of the library entry. */
|
|
||||||
id: string
|
|
||||||
version: number
|
|
||||||
/** The publisher's name at the time; empty for anonymous. */
|
|
||||||
author: string
|
|
||||||
/** Came along inside the entry (a part it uses), rather than being the entry itself. */
|
|
||||||
inside?: true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const FACE_INKS = ['muted', 'text', 'red', 'yellow', 'green', 'blue'] as const
|
export const FACE_INKS = ['muted', 'text', 'red', 'yellow', 'green', 'blue'] as const
|
||||||
|
|
@ -244,12 +165,6 @@ export interface FaceDesign {
|
||||||
rotate?: Record<string, number>
|
rotate?: Record<string, number>
|
||||||
/** Row of a pin on its edge (by pin key); pins without one follow the pin above. */
|
/** Row of a pin on its edge (by pin key); pins without one follow the pin above. */
|
||||||
pinAt?: Record<string, number>
|
pinAt?: Record<string, number>
|
||||||
/** Pins in this order down their edges (keys); pins not listed come after, in their usual order. */
|
|
||||||
pinOrder?: string[]
|
|
||||||
/** Screens shown pixel by pixel, each pixel placed on its own (screen keys, as in place). */
|
|
||||||
split?: string[]
|
|
||||||
/** The box takes the size its pins, name and things on it need, instead of w and h. */
|
|
||||||
fit?: boolean
|
|
||||||
shapes?: FaceShape[]
|
shapes?: FaceShape[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -303,42 +218,6 @@ export interface Project {
|
||||||
mode?: 'campaign' | 'challenges'
|
mode?: 'campaign' | 'challenges'
|
||||||
/** Puzzles opened from links or the weekly puzzle; their components carry `challenge: <puzzle id>`. */
|
/** Puzzles opened from links or the weekly puzzle; their components carry `challenge: <puzzle id>`. */
|
||||||
puzzles?: PuzzleSpec[]
|
puzzles?: PuzzleSpec[]
|
||||||
/** Connector types made in this project (HDMI, RJ45, your own buses): their lines and colour. */
|
|
||||||
connectors?: ConnectorType[]
|
|
||||||
/** What each circuit held when it was last open (latches, flip-flops, memory), by circuit id. Empty: it starts from all zeros. */
|
|
||||||
state?: Record<string, HeldState>
|
|
||||||
/** The assembler tool: instruction set, program and where it goes. */
|
|
||||||
asm?: AsmDoc
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The assembler's instruction set and program (see lib/asm). */
|
|
||||||
export interface AsmDoc {
|
|
||||||
/** The instruction set, one instruction per line. */
|
|
||||||
table: string
|
|
||||||
/** The program. */
|
|
||||||
source: string
|
|
||||||
/** Bits per memory word. */
|
|
||||||
width: number
|
|
||||||
/** Circuit whose input panels the words go into. */
|
|
||||||
target?: string
|
|
||||||
/** Each panel's top row is the highest bit (else bit 0). */
|
|
||||||
msbTop?: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The bits a circuit holds, like the contents of a memory chip: the NANDs on
|
|
||||||
* feedback loops that are 1, and the clocks that are high. Everything else
|
|
||||||
* follows from the inputs. Gates are known by their path through the chips
|
|
||||||
* ("chipNode/chipNode/nand"); one that no longer exists is ignored.
|
|
||||||
*/
|
|
||||||
export interface HeldState {
|
|
||||||
/** Node ids on the gates' paths, each once. */
|
|
||||||
names: string[]
|
|
||||||
/** The gates that are 1, separated by spaces: "<levels shared with the gate before>:<index>.<index>…" in base 36 (see state.ts). */
|
|
||||||
on: string
|
|
||||||
/** Keys of the clocks that are high. */
|
|
||||||
clocks?: string[]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A puzzle someone published: what to build, without their solution. */
|
/** A puzzle someone published: what to build, without their solution. */
|
||||||
|
|
@ -354,22 +233,3 @@ export interface PuzzleSpec {
|
||||||
/** Transistors in the author's own solution. */
|
/** Transistors in the author's own solution. */
|
||||||
author?: number
|
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
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,34 +0,0 @@
|
||||||
// Getting around the circuits: the way back shown in the top bar, folded
|
|
||||||
// when it is long, and how to reach a circuit picked in the search box.
|
|
||||||
|
|
||||||
import { matchScore } from './match'
|
|
||||||
|
|
||||||
/** The names after Main: the last `keep` stay in the bar, the ones before fold into "…". */
|
|
||||||
export function foldCrumbs<T>(path: T[], keep: number): { folded: T[]; shown: T[] } {
|
|
||||||
const n = Math.max(1, keep)
|
|
||||||
if (path.length <= n) return { folded: [], shown: path }
|
|
||||||
return { folded: path.slice(0, path.length - n), shown: path.slice(-n) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* How to get to circuit `id` from where you are: Main starts the way anew,
|
|
||||||
* one on the way here goes back to it (its step in `nav`), any other opens
|
|
||||||
* one step further in.
|
|
||||||
*/
|
|
||||||
export function wayTo(nav: string[], mainId: string, id: string): 'main' | 'open' | number {
|
|
||||||
if (id === mainId) return 'main'
|
|
||||||
const back = nav.indexOf(id)
|
|
||||||
return back >= 0 ? back : 'open'
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Circuits whose name matches what was typed, best first; nothing typed, none. */
|
|
||||||
export function circuitsNamed<T extends { name: string }>(defs: T[], query: string, limit = 5): T[] {
|
|
||||||
const q = query.trim().toLowerCase()
|
|
||||||
if (!q) return []
|
|
||||||
return defs
|
|
||||||
.map(d => ({ d, score: matchScore(d.name, q) }))
|
|
||||||
.filter(x => x.score > 0)
|
|
||||||
.sort((a, b) => b.score - a.score || a.d.name.length - b.d.name.length)
|
|
||||||
.slice(0, limit)
|
|
||||||
.map(x => x.d)
|
|
||||||
}
|
|
||||||
|
|
@ -1,9 +1,6 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
const ed = useEditor()
|
const ed = useEditor()
|
||||||
onMounted(() => {
|
onMounted(() => ed.syncUrl())
|
||||||
ed.firstPage()
|
|
||||||
ed.syncUrl()
|
|
||||||
})
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,7 @@
|
||||||
// A share link: /p/<id> opens that project (or your own copy of it).
|
// A share link: /p/<id> opens that project (or your own copy of it).
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const ed = useEditor()
|
const ed = useEditor()
|
||||||
// Only when the app was loaded with it: going back or forward to it later just shows that entry.
|
onMounted(() => ed.openLink(String(route.params.id)))
|
||||||
onMounted(() => (ed.firstPage() ? ed.openLink(String(route.params.id)) : ed.syncUrl()))
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,7 @@
|
||||||
// A puzzle link: /puzzle/<id> adds that puzzle to the open project and opens it.
|
// A puzzle link: /puzzle/<id> adds that puzzle to the open project and opens it.
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const ed = useEditor()
|
const ed = useEditor()
|
||||||
// Only when the app was loaded with it: going back or forward to it later just shows that entry.
|
onMounted(() => ed.openPuzzle(String(route.params.id)))
|
||||||
onMounted(() => (ed.firstPage() ? ed.openPuzzle(String(route.params.id)) : ed.syncUrl()))
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
|
|
||||||
|
|
@ -1,14 +0,0 @@
|
||||||
// Take an entry out of the library. Needs its edit key. Components already
|
|
||||||
// added to projects stay where they are.
|
|
||||||
export default defineEventHandler(async event => {
|
|
||||||
rateLimit(event, 'library', 30, 10 * 60_000)
|
|
||||||
const id = getRouterParam(event, 'id')
|
|
||||||
const key = getHeader(event, 'x-edit-key')
|
|
||||||
await locked('library', async () => {
|
|
||||||
const record = await findEntry(id)
|
|
||||||
if (!keyMatches(key, record.keyHash)) throw createError({ statusCode: 403, message: 'This component belongs to someone else' })
|
|
||||||
await libraryStorage().removeItem(entryKey(record.meta.id))
|
|
||||||
await libraryStorage().setItem('index', (await libraryIndex()).filter(m => m.id !== record.meta.id))
|
|
||||||
})
|
|
||||||
return { ok: true }
|
|
||||||
})
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
// One library entry with everything it uses, ready to add to a project.
|
|
||||||
// With ?meta only what it is, to look for a newer version.
|
|
||||||
export default defineEventHandler(async event => {
|
|
||||||
const record = await findEntry(getRouterParam(event, 'id'))
|
|
||||||
const entry = publicMeta(record.meta, await playerNames())
|
|
||||||
setHeader(event, 'cache-control', 'no-store')
|
|
||||||
return 'meta' in getQuery(event) ? { entry } : { entry, bundle: record.bundle }
|
|
||||||
})
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
// Publish a new version of a library entry. Needs the edit key from the
|
|
||||||
// first publish; the entry keeps its id and publisher, its version goes up.
|
|
||||||
import { describeBundle } from '../../../app/lib/logic/library'
|
|
||||||
|
|
||||||
export default defineEventHandler(async event => {
|
|
||||||
rateLimit(event, 'library', 30, 10 * 60_000)
|
|
||||||
const id = getRouterParam(event, 'id')
|
|
||||||
const { bundle } = await readLibraryBody(event)
|
|
||||||
const key = getHeader(event, 'x-edit-key')
|
|
||||||
const meta = await locked('library', async () => {
|
|
||||||
const record = await findEntry(id)
|
|
||||||
if (!keyMatches(key, record.keyHash)) throw createError({ statusCode: 403, message: 'This component belongs to someone else' })
|
|
||||||
const meta: LibraryItem = { ...record.meta, ...describeBundle(bundle), version: record.meta.version + 1, updated: Date.now() }
|
|
||||||
await libraryStorage().setItem(entryKey(meta.id), { ...record, meta, bundle })
|
|
||||||
await libraryStorage().setItem('index', (await libraryIndex()).map(m => (m.id === meta.id ? meta : m)))
|
|
||||||
return meta
|
|
||||||
})
|
|
||||||
return { id: meta.id, version: meta.version }
|
|
||||||
})
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
// Everybody's published components, newest first. ?q= narrows them to the
|
|
||||||
// ones whose name, description, group or author has every word typed.
|
|
||||||
export default defineEventHandler(async event => {
|
|
||||||
const q = getQuery(event).q
|
|
||||||
const names = await playerNames()
|
|
||||||
const list = (await libraryIndex()).map(m => publicMeta(m, names))
|
|
||||||
setHeader(event, 'cache-control', 'no-store')
|
|
||||||
return { entries: searchLibrary(list, typeof q === 'string' ? q.slice(0, 100) : '').slice(0, 500), total: list.length }
|
|
||||||
})
|
|
||||||
|
|
@ -1,24 +0,0 @@
|
||||||
// Publish a component to the library, with everything it uses. The server
|
|
||||||
// counts its transistors and pins itself, so the listing can be trusted.
|
|
||||||
// Returns its id and the edit key that updates or removes it later.
|
|
||||||
import { describeBundle } from '../../../app/lib/logic/library'
|
|
||||||
|
|
||||||
export default defineEventHandler(async event => {
|
|
||||||
rateLimit(event, 'library', 30, 10 * 60_000)
|
|
||||||
const { player, bundle } = await readLibraryBody(event)
|
|
||||||
const storage = libraryStorage()
|
|
||||||
const key = newEditKey()
|
|
||||||
const meta = await locked('library', async () => {
|
|
||||||
const index = await libraryIndex()
|
|
||||||
if (index.length >= MAX_ENTRIES) throw createError({ statusCode: 507, message: 'The library is full for now' })
|
|
||||||
let id = newShareId()
|
|
||||||
while (await storage.hasItem(entryKey(id))) id = newShareId()
|
|
||||||
const now = Date.now()
|
|
||||||
const meta: LibraryItem = { id, ...describeBundle(bundle), version: 1, created: now, updated: now, player }
|
|
||||||
await storage.setItem(entryKey(id), { meta, bundle, keyHash: hashKey(key) })
|
|
||||||
await storage.setItem('index', [meta, ...index])
|
|
||||||
return meta
|
|
||||||
})
|
|
||||||
setResponseStatus(event, 201)
|
|
||||||
return { id: meta.id, key, version: meta.version }
|
|
||||||
})
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { LIMITS, toProject } from '../../../../../app/lib/logic/project'
|
import { toProject } from '../../../../../app/lib/logic/project'
|
||||||
import type { CloudMeta } from '../../../../utils/accounts'
|
import type { CloudMeta } from '../../../../utils/accounts'
|
||||||
// Save a project to the account. `baseRev` is the revision the device last
|
// Save a project to the account. `baseRev` is the revision the device last
|
||||||
// had; if another device saved in between, this answers 409 with the newer
|
// had; if another device saved in between, this answers 409 with the newer
|
||||||
|
|
@ -9,7 +9,7 @@ export default defineEventHandler(async event => {
|
||||||
const id = getRouterParam(event, 'id')
|
const id = getRouterParam(event, 'id')
|
||||||
if (!isProjectId(id)) throw createError({ statusCode: 400, message: 'Bad project id' })
|
if (!isProjectId(id)) throw createError({ statusCode: 400, message: 'Bad project id' })
|
||||||
const raw = await readRawBody(event, 'utf8')
|
const raw = await readRawBody(event, 'utf8')
|
||||||
if (!raw || raw.length > 2_100_000 + LIMITS.state) throw createError({ statusCode: 413, message: 'Project too large' })
|
if (!raw || raw.length > 2_100_000) throw createError({ statusCode: 413, message: 'Project too large' })
|
||||||
let body: { project?: unknown; baseRev?: unknown; force?: unknown; link?: unknown; snapshot?: unknown }
|
let body: { project?: unknown; baseRev?: unknown; force?: unknown; link?: unknown; snapshot?: unknown }
|
||||||
try {
|
try {
|
||||||
body = JSON.parse(raw)
|
body = JSON.parse(raw)
|
||||||
|
|
|
||||||
|
|
@ -1,32 +0,0 @@
|
||||||
import { LIMITS, toProject } from '../../../../../app/lib/logic/project'
|
|
||||||
// Keep a device's own version of a project as a savegame, without making it
|
|
||||||
// the current one. Used when another device saved something newer: the newer
|
|
||||||
// save wins, and this one stays restorable from the project's savegames.
|
|
||||||
export default defineEventHandler(async event => {
|
|
||||||
rateLimit(event, 'save', 1200, 10 * 60_000)
|
|
||||||
const user = await requireUser(event)
|
|
||||||
const id = getRouterParam(event, 'id')
|
|
||||||
if (!isProjectId(id)) throw createError({ statusCode: 400, message: 'Bad project id' })
|
|
||||||
const raw = await readRawBody(event, 'utf8')
|
|
||||||
if (!raw || raw.length > 2_100_000 + LIMITS.state) throw createError({ statusCode: 413, message: 'Project too large' })
|
|
||||||
let body: { project?: unknown; baseRev?: unknown }
|
|
||||||
try {
|
|
||||||
body = JSON.parse(raw)
|
|
||||||
} catch {
|
|
||||||
throw createError({ statusCode: 400, message: 'Not valid JSON' })
|
|
||||||
}
|
|
||||||
let project
|
|
||||||
try {
|
|
||||||
project = toProject(body.project)
|
|
||||||
} catch (e) {
|
|
||||||
throw createError({ statusCode: 400, message: (e as Error).message })
|
|
||||||
}
|
|
||||||
return withLock(user.id, async () => {
|
|
||||||
const index = await readIndex(user.id)
|
|
||||||
if (!index.projects.some(p => p.id === id)) throw createError({ statusCode: 404, message: 'Project not found' })
|
|
||||||
const rev = typeof body.baseRev === 'number' && Number.isInteger(body.baseRev) ? body.baseRev : 0
|
|
||||||
await keepVersion(user.id, id, { project, rev, at: Date.now(), name: project.name }, true)
|
|
||||||
setResponseStatus(event, 201)
|
|
||||||
return { kept: true }
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -4,7 +4,7 @@ import { join, resolve } from 'node:path'
|
||||||
export default defineNitroPlugin(() => {
|
export default defineNitroPlugin(() => {
|
||||||
const root = resolve(process.cwd(), 'data')
|
const root = resolve(process.cwd(), 'data')
|
||||||
const storage = useStorage()
|
const storage = useStorage()
|
||||||
for (const name of ['shares', 'users', 'sessions', 'accounts', 'puzzles', 'library']) {
|
for (const name of ['shares', 'users', 'sessions', 'accounts', 'puzzles']) {
|
||||||
storage.mount(name, safeFsDriver({ base: join(root, name) }))
|
storage.mount(name, safeFsDriver({ base: join(root, name) }))
|
||||||
}
|
}
|
||||||
void removeStaleTemp(root)
|
void removeStaleTemp(root)
|
||||||
|
|
|
||||||
|
|
@ -1,70 +0,0 @@
|
||||||
// The public component library, as JSON files under data/library:
|
|
||||||
// entries:<id> holds a published component with everything it uses, index
|
|
||||||
// the list everyone browses. Publishers have no account here, just the
|
|
||||||
// random player id kept in their browser (as on the leaderboards) and an
|
|
||||||
// edit key per entry, which only their browser has; only its hash is stored.
|
|
||||||
|
|
||||||
import type { H3Event } from 'h3'
|
|
||||||
import { cleanBundle, LIBRARY_LIMITS, type LibraryBundle, type LibraryMeta } from '../../app/lib/logic/library'
|
|
||||||
|
|
||||||
/** An entry in the index: its meta with the publisher's player id instead of their name. */
|
|
||||||
export type LibraryItem = Omit<LibraryMeta, 'author'> & { player: string }
|
|
||||||
|
|
||||||
export interface LibraryRecord {
|
|
||||||
meta: LibraryItem
|
|
||||||
bundle: LibraryBundle
|
|
||||||
keyHash: string
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Entries the library holds at most, so the index stays small enough to read on every visit. */
|
|
||||||
export const MAX_ENTRIES = 20_000
|
|
||||||
|
|
||||||
export const libraryStorage = () => useStorage('library')
|
|
||||||
export const entryKey = (id: string) => `entries:${id}`
|
|
||||||
|
|
||||||
export async function libraryIndex(): Promise<LibraryItem[]> {
|
|
||||||
return (await libraryStorage().getItem<LibraryItem[]>('index')) ?? []
|
|
||||||
}
|
|
||||||
|
|
||||||
/** An entry as everyone sees it: the author by the name they chose, never their player id. */
|
|
||||||
export function publicMeta(item: LibraryItem, names: Record<string, string>): LibraryMeta {
|
|
||||||
const { player, ...meta } = item
|
|
||||||
return { ...meta, author: names[player] ?? '' }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Entries whose name, description, group or author contain every word of the query, newest first. */
|
|
||||||
export function searchLibrary(list: LibraryMeta[], query: string): LibraryMeta[] {
|
|
||||||
const words = query.toLowerCase().split(/\s+/).filter(Boolean)
|
|
||||||
return list
|
|
||||||
.filter(m => {
|
|
||||||
const text = `${m.name} ${m.description} ${m.group} ${m.author}`.toLowerCase()
|
|
||||||
return words.every(w => text.includes(w))
|
|
||||||
})
|
|
||||||
.sort((a, b) => b.updated - a.updated)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The publisher and their component, checked and cleaned like any project. */
|
|
||||||
export async function readLibraryBody(event: H3Event): Promise<{ player: string; bundle: LibraryBundle }> {
|
|
||||||
const raw = await readRawBody(event, 'utf8')
|
|
||||||
if (!raw) throw createError({ statusCode: 400, message: 'Empty request' })
|
|
||||||
if (raw.length > LIBRARY_LIMITS.bytes) throw createError({ statusCode: 413, message: 'Too large for the library (1 MB at most)' })
|
|
||||||
let body: { player?: unknown }
|
|
||||||
try {
|
|
||||||
body = JSON.parse(raw)
|
|
||||||
} catch {
|
|
||||||
throw createError({ statusCode: 400, message: 'Not valid JSON' })
|
|
||||||
}
|
|
||||||
if (!isPlayer(body.player)) throw createError({ statusCode: 400, message: 'Missing player' })
|
|
||||||
try {
|
|
||||||
return { player: body.player, bundle: cleanBundle(body) }
|
|
||||||
} catch (e) {
|
|
||||||
throw createError({ statusCode: 400, message: (e as Error).message })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The entry behind an API id, or a 404. */
|
|
||||||
export async function findEntry(id: string | undefined): Promise<LibraryRecord> {
|
|
||||||
const record = isShareId(id) ? await libraryStorage().getItem<LibraryRecord>(entryKey(id)) : null
|
|
||||||
if (!record) throw createError({ statusCode: 404, message: 'Not in the library (any more)' })
|
|
||||||
return record
|
|
||||||
}
|
|
||||||
|
|
@ -50,7 +50,7 @@ export function rateLimit(event: H3Event, bucket: string, max: number, windowMs:
|
||||||
export async function readProjectBody(event: H3Event): Promise<Project> {
|
export async function readProjectBody(event: H3Event): Promise<Project> {
|
||||||
const raw = await readRawBody(event, 'utf8')
|
const raw = await readRawBody(event, 'utf8')
|
||||||
if (!raw) throw createError({ statusCode: 400, message: 'Empty request' })
|
if (!raw) throw createError({ statusCode: 400, message: 'Empty request' })
|
||||||
if (raw.length > LIMITS.bytes + LIMITS.state) throw createError({ statusCode: 413, message: 'Project too large to share' })
|
if (raw.length > LIMITS.bytes) throw createError({ statusCode: 413, message: 'Project too large to share' })
|
||||||
let body: { project?: unknown }
|
let body: { project?: unknown }
|
||||||
try {
|
try {
|
||||||
body = JSON.parse(raw)
|
body = JSON.parse(raw)
|
||||||
|
|
|
||||||
|
|
@ -1,103 +0,0 @@
|
||||||
import { describe, expect, it } from 'vitest'
|
|
||||||
import { assemble, EXAMPLE, loadIntoPanels, memoryPanels, parseTable } from '../app/lib/asm'
|
|
||||||
|
|
||||||
const TABLE = `
|
|
||||||
LDA 0001 addr:4
|
|
||||||
ADD 0010 addr:4
|
|
||||||
LDI 0101 value:4
|
|
||||||
JMP 0110 addr:4
|
|
||||||
OUT 1110
|
|
||||||
HLT 1111
|
|
||||||
LONG 00000001 value:8 ; two words at 8 bits
|
|
||||||
`
|
|
||||||
const asm = (src: string, width = 8, table = TABLE) => assemble(src, table, width)
|
|
||||||
|
|
||||||
describe('assembler', () => {
|
|
||||||
it('the example assembles without errors', () => {
|
|
||||||
const r = assemble(EXAMPLE.source, EXAMPLE.table, EXAMPLE.width)
|
|
||||||
expect(r.errors).toEqual([])
|
|
||||||
// LDI 0, ADD three(6), OUT, JC done(5), JMP loop(1), HLT, 3
|
|
||||||
expect(r.image).toEqual([0x50, 0x26, 0xe0, 0x75, 0x61, 0xf0, 3])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('opcode then operands from the top bit; bits left over are 0', () => {
|
|
||||||
const r = asm('LDA 3\nOUT\nHLT')
|
|
||||||
expect(r.errors).toEqual([])
|
|
||||||
expect(r.image).toEqual([0x13, 0xe0, 0xf0])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('labels before they are defined, constants, .org, .word with strings and characters, .fill', () => {
|
|
||||||
const r = asm(`
|
|
||||||
N = 2
|
|
||||||
.org 1
|
|
||||||
start: LDA data+N ; forward label plus a constant
|
|
||||||
JMP start
|
|
||||||
.org 0x8
|
|
||||||
data: .word 1, 'A', "Hi", -1
|
|
||||||
.fill 2, $FF`)
|
|
||||||
expect(r.errors).toEqual([])
|
|
||||||
expect(r.labels.get('start')).toBe(1)
|
|
||||||
expect(r.labels.get('data')).toBe(8)
|
|
||||||
expect(r.image).toEqual([0, 0x1a, 0x61, 0, 0, 0, 0, 0, 1, 65, 72, 105, 0xff, 0xff, 0xff])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('an instruction longer than a word takes several words', () => {
|
|
||||||
const r = asm('LONG 200\nHLT')
|
|
||||||
expect(r.errors).toEqual([])
|
|
||||||
expect(r.image).toEqual([1, 200, 0xf0])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('wider words: 12 bits', () => {
|
|
||||||
const r = asm('LDA 15', 12)
|
|
||||||
expect(r.image).toEqual([0x1f0])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('says what is wrong and on which line', () => {
|
|
||||||
const r = asm('LDA 16\nFOO 1\nADD\nLDA nowhere\nx: OUT\nx: HLT\n.org 0\nOUT')
|
|
||||||
const at = (line: number) => r.errors.filter(e => e.where === 'source' && e.line === line).map(e => e.text)
|
|
||||||
expect(at(1)[0]).toMatch(/does not fit in 4 bits/)
|
|
||||||
expect(at(2)[0]).toMatch(/not in the instruction set/)
|
|
||||||
expect(at(3)[0]).toMatch(/takes addr/)
|
|
||||||
expect(at(4)[0]).toMatch(/not a label/)
|
|
||||||
expect(at(6)[0]).toMatch(/defined twice/)
|
|
||||||
expect(at(8)[0]).toMatch(/also written by line 1/)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a broken table says so', () => {
|
|
||||||
const t = parseTable('LDA 0102 addr:4\nADD 0010 addr\nADD 0011\nADD 0100')
|
|
||||||
expect(t.errors.map(e => e.line)).toEqual([1, 2, 4])
|
|
||||||
expect(parseTable('X 0xA').ops.get('X')!.bits).toBe('1010')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('comments do not cut quoted text', () => {
|
|
||||||
const r = asm('.word ";", \';\' ; comment')
|
|
||||||
expect(r.errors).toEqual([])
|
|
||||||
expect(r.image).toEqual([59, 59])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('loading words into panels of switches', () => {
|
|
||||||
const panel = (id: string, x: number, y: number, rows = 4) => ({ id, kind: 'panel' as const, x, y, rows: Array.from({ length: rows }, (_, i) => ({ id: `r${i}`, type: 'switch' as const })) })
|
|
||||||
const def = (nodes: ReturnType<typeof panel>[]) => ({ id: 'rom', name: 'ROM', symbol: 'box' as const, nodes, wires: [] })
|
|
||||||
const bits = (p: ReturnType<typeof panel>) => p.rows.map(r => ((r as { on?: boolean }).on ? 1 : 0)).join('')
|
|
||||||
|
|
||||||
it('in reading order, row i is bit i; panels left over go to 0', () => {
|
|
||||||
// Two rows of panels, the second slightly out of line.
|
|
||||||
const ps = [panel('c', 10, 0), panel('a', 0, 1), panel('d', 0, 8), panel('e', 5, 9), panel('b', 5, 0)]
|
|
||||||
const d = def(ps)
|
|
||||||
expect(memoryPanels(d).map(n => n.id)).toEqual(['a', 'b', 'c', 'd', 'e'])
|
|
||||||
ps[3]!.rows[0]!.on = true
|
|
||||||
const r = loadIntoPanels(d, [1, 2, 0xc, 5], 4)
|
|
||||||
expect(r).toEqual({ ok: true, panels: 4, cleared: 1 })
|
|
||||||
const by = (id: string) => bits(ps.find(p => p.id === id)!)
|
|
||||||
expect([by('a'), by('b'), by('c'), by('d'), by('e')]).toEqual(['1000', '0100', '0011', '1010', '0000'])
|
|
||||||
loadIntoPanels(d, [1], 4, true)
|
|
||||||
expect(by('a')).toBe('0001')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('refuses what does not fit', () => {
|
|
||||||
expect(loadIntoPanels(def([panel('a', 0, 0)]), [1, 2], 4).ok).toBe(false)
|
|
||||||
expect(loadIntoPanels(def([panel('a', 0, 0, 3)]), [1], 4).ok).toBe(false)
|
|
||||||
expect(loadIntoPanels(def([]), [1], 4).ok).toBe(false)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,97 +0,0 @@
|
||||||
import { describe, expect, it } from 'vitest'
|
|
||||||
import { benchFor, checkCols, combinationRows, driveCols, groupPins, parseCell, parseTicks, recordExpected, runBench, upgradeBenches } from '../app/lib/logic/bench'
|
|
||||||
import { benchLayout } from '../app/lib/logic/benchLayout'
|
|
||||||
import { compile } from '../app/lib/logic/compile'
|
|
||||||
import { shapeOf } from '../app/lib/logic/geometry'
|
|
||||||
import { createProject, lookup, uid } from '../app/lib/logic/ops'
|
|
||||||
import type { CircuitNode, ComponentDef, Project } from '../app/lib/logic/types'
|
|
||||||
|
|
||||||
/** A circuit with one placed example component and a bench wired to all its pins. */
|
|
||||||
function rig(chipId: string): { p: Project; def: ComponentDef; bench: CircuitNode } {
|
|
||||||
const p = createProject({ examples: true })
|
|
||||||
const bench: CircuitNode = { id: 'tb', kind: 'bench', x: 0, y: 0, bench: { cols: [], rows: [] } }
|
|
||||||
const chip: CircuitNode = { id: 'u', kind: 'chip', chip: chipId, x: 20, y: 0 }
|
|
||||||
const def: ComponentDef = { id: 'rig', name: 'Rig', symbol: 'box', nodes: [bench, chip], wires: [] }
|
|
||||||
p.components.push(def)
|
|
||||||
for (const w of benchFor(def, bench, chip, lookup(p)(chipId)!)) def.wires.push({ id: uid('w'), ...w })
|
|
||||||
return { p, def, bench }
|
|
||||||
}
|
|
||||||
const col = (b: CircuitNode, name: string) => b.bench!.cols!.find(c => c.name === name)!.id
|
|
||||||
|
|
||||||
describe('test bench cells', () => {
|
|
||||||
it('A0…An make one group; other pins stay single', () => {
|
|
||||||
expect(groupPins([{ key: 'a1', label: 'A1' }, { key: 'a0', label: 'A0' }, { key: 'c', label: 'Cin' }, { key: 'x2', label: 'X2' }])).toEqual([
|
|
||||||
{ name: 'A', keys: ['a0', 'a1'] },
|
|
||||||
{ name: 'Cin', keys: ['c'] },
|
|
||||||
{ name: 'X2', keys: ['x2'] },
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('numbers in three bases, P, don’t care, what does not fit; ticks', () => {
|
|
||||||
expect(parseCell('0x0C', 4, true)).toBe(12)
|
|
||||||
expect(parseCell('0b1100', 4, true)).toBe(12)
|
|
||||||
expect(parseCell('-1', 4, false)).toBe(15)
|
|
||||||
expect(parseCell('p', 1, true)).toBe('P')
|
|
||||||
expect(parseCell('x', 1, false)).toBeNull()
|
|
||||||
expect(parseCell('16', 4, true)).toHaveProperty('error')
|
|
||||||
expect(parseCell('P', 1, false)).toHaveProperty('error')
|
|
||||||
expect(parseTicks('≤100')).toEqual({ n: 100, wait: true })
|
|
||||||
expect(parseTicks('soon')).toHaveProperty('error')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('a wired test bench', () => {
|
|
||||||
it('has pins: check columns on the left, drive columns on the right', () => {
|
|
||||||
const { p, bench } = rig('ex-ha')
|
|
||||||
const shape = shapeOf(bench, lookup(p))
|
|
||||||
expect(shape.inputs.map(x => x.label)).toEqual(checkCols(bench.bench).map(c => c.name))
|
|
||||||
expect(shape.outputs.map(x => x.label)).toEqual(driveCols(bench.bench).map(c => c.name))
|
|
||||||
expect(shape.outputs.every(x => x.dx === benchLayout(bench).w)).toBe(true)
|
|
||||||
const nl = compile(lookup(p), 'rig')
|
|
||||||
expect(nl.sources.size).toBe(shape.outputs.length)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a truth table: every combination, taken, passing; a wrong row fails', () => {
|
|
||||||
const { p, bench } = rig('ex-ha')
|
|
||||||
const rows = combinationRows(bench.bench!)
|
|
||||||
if ('error' in rows) throw new Error(rows.error)
|
|
||||||
expect(rows.length).toBe(4)
|
|
||||||
bench.bench!.rows = rows
|
|
||||||
bench.bench!.rows = recordExpected(runBench(lookup(p), 'rig', 'tb'), rows)
|
|
||||||
// Half adder, A B → S C: 1 + 1 is S 0, C 1.
|
|
||||||
const last = bench.bench!.rows[3]!
|
|
||||||
expect([last.expect![col(bench, 'S')], last.expect![col(bench, 'C')]]).toEqual(['0', '1'])
|
|
||||||
expect(runBench(lookup(p), 'rig', 'tb')).toMatchObject({ pass: 4, fail: 0 })
|
|
||||||
last.expect![col(bench, 'C')] = '0'
|
|
||||||
const r = runBench(lookup(p), 'rig', 'tb')
|
|
||||||
expect(r.fail).toBe(1)
|
|
||||||
expect(r.rows[3]).toMatchObject({ ok: false })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a counter: pulses, ticks, and waiting until it gets there', () => {
|
|
||||||
const { p, bench } = rig('ex-cnt4')
|
|
||||||
const clk = col(bench, 'CLK')
|
|
||||||
const q = col(bench, 'Q')
|
|
||||||
bench.bench!.rows = [{ set: { [clk]: 'P' } }, { set: { [clk]: 'P' }, ticks: '2' }, { set: { [clk]: 'P' }, ticks: '≤50', expect: { [q]: '9' } }]
|
|
||||||
const r = runBench(lookup(p), 'rig', 'tb')
|
|
||||||
expect(r.rows[1]!.got[q]).toBe(3)
|
|
||||||
expect(r.rows[2]).toMatchObject({ ok: true, ticks: 6 })
|
|
||||||
bench.bench!.rows = [{ set: { [clk]: 'P' }, ticks: '≤3', expect: { [q]: '9' } }]
|
|
||||||
expect(runBench(lookup(p), 'rig', 'tb').rows[0]).toMatchObject({ ok: false, error: 'Not within 3 ticks' })
|
|
||||||
bench.bench!.rows = [{ set: { [clk]: 'P' }, ticks: '100' }]
|
|
||||||
expect(runBench(lookup(p), 'rig', 'tb', 10).error).toMatch(/Stopped after 10 ticks/)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a bench from the first version (docked, keyed by names) gets columns and wires', () => {
|
|
||||||
const p = createProject({ examples: true })
|
|
||||||
const chip: CircuitNode = { id: 'u', kind: 'chip', chip: 'ex-ha', x: 20, y: 0 }
|
|
||||||
const old: CircuitNode = { id: 'tb', kind: 'bench', x: 0, y: 0, bench: { on: 'u', rows: [{ set: { A: '1', B: '1' }, expect: { S: '0', C: '1' } }] } }
|
|
||||||
const def: ComponentDef = { id: 'rig', name: 'Rig', symbol: 'box', nodes: [old, chip], wires: [] }
|
|
||||||
p.components.push(def)
|
|
||||||
upgradeBenches(def, lookup(p))
|
|
||||||
expect(old.bench!.on).toBeUndefined()
|
|
||||||
expect(old.bench!.cols!.map(c => `${c.dir}:${c.name}`)).toEqual(['drive:A', 'drive:B', 'check:S', 'check:C'])
|
|
||||||
expect(def.wires.length).toBe(4)
|
|
||||||
expect(runBench(lookup(p), 'rig', 'tb')).toMatchObject({ pass: 1, fail: 0 })
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,153 +0,0 @@
|
||||||
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)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,58 +0,0 @@
|
||||||
import { describe, expect, it } from 'vitest'
|
|
||||||
import { charLabel, ENCODINGS, formatAs, FORMATS, parseAs, parseWords, signed, type ConvertOptions } from '../app/lib/convert'
|
|
||||||
|
|
||||||
const o: ConvertOptions = { enc: 'utf8', word: 8, endian: 'big' }
|
|
||||||
const conv = (input: string, from: (typeof FORMATS)[number], to: (typeof FORMATS)[number], opts: Partial<ConvertOptions> = {}) => {
|
|
||||||
const b = parseAs(input, from, { ...o, ...opts })
|
|
||||||
if (!b.ok) throw new Error(b.error)
|
|
||||||
const out = formatAs(b.value, to, { ...o, ...opts })
|
|
||||||
if (!out.ok) throw new Error(out.error)
|
|
||||||
return out.value
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('converter', () => {
|
|
||||||
it('text to hex, binary, decimal, octal and Base64, and back', () => {
|
|
||||||
expect(conv('Hi!', 'text', 'hex')).toBe('48 69 21')
|
|
||||||
expect(conv('Hi!', 'text', 'bin')).toBe('01001000 01101001 00100001')
|
|
||||||
expect(conv('Hi!', 'text', 'dec')).toBe('72 105 33')
|
|
||||||
expect(conv('Hi!', 'text', 'oct')).toBe('110 151 41')
|
|
||||||
expect(conv('Hi!', 'text', 'base64')).toBe('SGkh')
|
|
||||||
for (const f of FORMATS) expect(conv(conv('Hällo €', 'text', f), f, 'text')).toBe('Hällo €')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('every encoding round-trips what it can encode', () => {
|
|
||||||
for (const enc of ENCODINGS) {
|
|
||||||
const s = enc === 'ascii' ? 'Hello' : enc === 'latin1' ? 'Grüße' : 'Grüße 😀'
|
|
||||||
expect(conv(conv(s, 'text', 'hex', { enc }), 'hex', 'text', { enc })).toBe(s)
|
|
||||||
}
|
|
||||||
expect(conv('Hé', 'text', 'hex', { enc: 'utf16le' })).toBe('48 00 E9 00')
|
|
||||||
expect(conv('😀', 'text', 'hex', { enc: 'utf32be' })).toBe('00 01 F6 00')
|
|
||||||
expect(parseAs('é', 'text', { ...o, enc: 'ascii' }).ok).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('hex and binary accept prefixes, separators and long runs', () => {
|
|
||||||
expect(conv('0x48,0x69 $21', 'hex', 'text')).toBe('Hi!')
|
|
||||||
expect(conv('486921', 'hex', 'dec')).toBe('72 105 33')
|
|
||||||
expect(conv('0b0100_1000', 'bin', 'hex')).toBe('48')
|
|
||||||
expect(parseWords('ABC', 'hex', 8).ok).toBe(false)
|
|
||||||
expect(parseWords('256', 'dec', 8).ok).toBe(false)
|
|
||||||
expect(parseWords('zz', 'hex', 8).ok).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('words of 16 and 32 bits, in either byte order', () => {
|
|
||||||
expect(conv('1234', 'hex', 'hex', { word: 16 })).toBe('1234')
|
|
||||||
expect(conv('1234', 'hex', 'dec', { word: 16 })).toBe('4660')
|
|
||||||
const le = parseAs('1234', 'hex', { ...o, word: 16, endian: 'little' })
|
|
||||||
expect(le.ok && [...le.value]).toEqual([0x34, 0x12])
|
|
||||||
expect(conv('DEADBEEF', 'hex', 'dec', { word: 32 })).toBe('3735928559')
|
|
||||||
expect(conv('Hi!', 'text', 'hex', { word: 16 })).toBe('4869 2100')
|
|
||||||
expect(signed(0xff, 8)).toBe(-1)
|
|
||||||
expect(signed(0x7f, 8)).toBe(127)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('control characters have names', () => {
|
|
||||||
expect(charLabel(10)).toBe('LF')
|
|
||||||
expect(charLabel(65)).toBe('A')
|
|
||||||
expect(charLabel(1)).toBe('^01')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,176 +0,0 @@
|
||||||
// The terminal and the keyboard: the text a terminal keeps, the codes keys
|
|
||||||
// type, and both running in the real editor, a button strobing them.
|
|
||||||
|
|
||||||
import * as vue from 'vue'
|
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
||||||
import { compile } from '../app/lib/logic/compile'
|
|
||||||
import { DATA_KEYS, keyCode, putChar } from '../app/lib/logic/devices'
|
|
||||||
import { clampSize, displayPins, displaySize, ratioText } from '../app/lib/logic/displays'
|
|
||||||
import { createProject, lookup } from '../app/lib/logic/ops'
|
|
||||||
import { Simulator } from '../app/lib/logic/sim'
|
|
||||||
import { saveProject, setCurrentId } from '../app/lib/logic/storage'
|
|
||||||
import type { ComponentDef, Project } from '../app/lib/logic/types'
|
|
||||||
|
|
||||||
const type = (s: string, cols = 32) => [...s].reduce((lines, c) => putChar(lines, c.charCodeAt(0), cols), [''])
|
|
||||||
|
|
||||||
describe('terminal text', () => {
|
|
||||||
it('prints, breaks lines, goes back, clears', () => {
|
|
||||||
expect(type('Hi\nyou')).toEqual(['Hi', 'you'])
|
|
||||||
expect(type('abc\b\bX')).toEqual(['aX'])
|
|
||||||
expect(type('abcdef', 4)).toEqual(['abcd', 'ef'])
|
|
||||||
expect(type('a\tb')).toEqual(['a b'])
|
|
||||||
expect(type('one\rtwo')).toEqual(['two'])
|
|
||||||
expect(type('junk\fok')).toEqual(['ok'])
|
|
||||||
expect(type('\x01\x07x')).toEqual(['x'])
|
|
||||||
expect(putChar(['é'], 0xe9)).toEqual(['éé'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keys type their codes', () => {
|
|
||||||
expect(keyCode({ key: 'a' })).toBe(97)
|
|
||||||
expect(keyCode({ key: 'Enter' })).toBe(10)
|
|
||||||
expect(keyCode({ key: 'Backspace' })).toBe(8)
|
|
||||||
expect(keyCode({ key: 'c', ctrlKey: true })).toBe(3)
|
|
||||||
expect(keyCode({ key: 'ArrowUp' })).toBeNull()
|
|
||||||
expect(keyCode({ key: '😀' })).toBeNull()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
/** A keyboard wired straight to a terminal; button W writes the waiting key and takes it, C clears. */
|
|
||||||
function echoProject(): Project {
|
|
||||||
const p = createProject({ examples: false })
|
|
||||||
const def: ComponentDef = {
|
|
||||||
id: 'echo',
|
|
||||||
name: 'Echo',
|
|
||||||
symbol: 'box',
|
|
||||||
nodes: [
|
|
||||||
{ id: 'kb', kind: 'keyboard', x: 0, y: 0 },
|
|
||||||
{ id: 'tm', kind: 'terminal', x: 12, y: 0 },
|
|
||||||
{ id: 'w', kind: 'button', x: 0, y: 14, label: 'W' },
|
|
||||||
{ id: 'c', kind: 'button', x: 0, y: 16, label: 'C' },
|
|
||||||
],
|
|
||||||
wires: [
|
|
||||||
...DATA_KEYS.map(k => ({ id: `d-${k}`, from: { node: 'kb', pin: k }, to: { node: 'tm', pin: k } })),
|
|
||||||
{ id: 'wr', from: { node: 'w', pin: 'q' }, to: { node: 'tm', pin: 'wr' } },
|
|
||||||
{ id: 'nx', from: { node: 'w', pin: 'q' }, to: { node: 'kb', pin: 'next' } },
|
|
||||||
{ id: 'cl', from: { node: 'c', pin: 'q' }, to: { node: 'tm', pin: 'clr' } },
|
|
||||||
],
|
|
||||||
}
|
|
||||||
p.components.push(def)
|
|
||||||
p.openId = def.id
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
let store: Map<string, string>
|
|
||||||
beforeEach(() => {
|
|
||||||
store = new Map()
|
|
||||||
vi.stubGlobal('localStorage', {
|
|
||||||
getItem: (k: string) => store.get(k) ?? null,
|
|
||||||
setItem: (k: string, v: string) => void store.set(k, String(v)),
|
|
||||||
removeItem: (k: string) => void store.delete(k),
|
|
||||||
})
|
|
||||||
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'] })
|
|
||||||
})
|
|
||||||
afterEach(() => {
|
|
||||||
vi.useRealTimers()
|
|
||||||
vi.unstubAllGlobals()
|
|
||||||
})
|
|
||||||
|
|
||||||
async function openEditor(p: Project) {
|
|
||||||
saveProject({ id: 'p1', name: p.name, updated: Date.now() }, p)
|
|
||||||
setCurrentId('p1')
|
|
||||||
const on = () => {}
|
|
||||||
vi.stubGlobal('window', { addEventListener: on })
|
|
||||||
vi.stubGlobal('document', { addEventListener: on, visibilityState: 'visible' })
|
|
||||||
vi.stubGlobal('location', { pathname: '/', origin: 'http://localhost' })
|
|
||||||
vi.stubGlobal('history', { state: null, replaceState() {} })
|
|
||||||
for (const k of ['ref', 'computed', 'reactive', 'shallowRef', 'toRaw', 'watch', 'nextTick'] as const) vi.stubGlobal(k, vue[k])
|
|
||||||
vi.resetModules()
|
|
||||||
const { useEditor } = await import('../app/composables/useEditor')
|
|
||||||
return useEditor()
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('keyboard and terminal in the editor', () => {
|
|
||||||
it('a rising WR writes the waiting key; NEXT takes it; CLR clears', async () => {
|
|
||||||
const ed = await openEditor(echoProject())
|
|
||||||
vi.advanceTimersByTime(100)
|
|
||||||
const click = (label: string) => {
|
|
||||||
const n = ed.def.value.nodes.find(x => x.label === label)!
|
|
||||||
ed.press(n, true)
|
|
||||||
ed.step()
|
|
||||||
ed.press(n, false)
|
|
||||||
ed.step()
|
|
||||||
}
|
|
||||||
ed.typeInto('kb')
|
|
||||||
for (const c of 'Hi!') ed.typeKey(c.charCodeAt(0))
|
|
||||||
ed.typeKey(10)
|
|
||||||
ed.typeKey('o'.charCodeAt(0))
|
|
||||||
ed.sim.value!.run()
|
|
||||||
expect(ed.val('kb', 'rdy')).toBe(1)
|
|
||||||
for (let i = 0; i < 5; i++) click('W')
|
|
||||||
expect(ed.screens.value.get('tm')).toEqual(['Hi!', 'o'])
|
|
||||||
expect(ed.keyQueues.value.get('kb')).toEqual([])
|
|
||||||
expect(ed.val('kb', 'rdy')).toBe(0)
|
|
||||||
// Nothing waiting: a strobe writes code 0, which shows nothing.
|
|
||||||
click('W')
|
|
||||||
expect(ed.screens.value.get('tm')).toEqual(['Hi!', 'o'])
|
|
||||||
click('C')
|
|
||||||
expect(ed.screens.value.get('tm')).toEqual([''])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('inside a component a keyboard gives 0 and a terminal does nothing', () => {
|
|
||||||
const p = echoProject()
|
|
||||||
p.components.push({ id: 'outer', name: 'Outer', symbol: 'box', nodes: [{ id: 'e', kind: 'chip', chip: 'echo', x: 0, y: 0 }], wires: [] })
|
|
||||||
const s = new Simulator(compile(lookup(p), 'outer'))
|
|
||||||
s.run()
|
|
||||||
expect(s.nl.sources.size).toBe(0)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('monitors', () => {
|
|
||||||
it('pins follow the size: as many X and Y bits as it needs; turning swaps them', () => {
|
|
||||||
const n = { id: 'm', kind: 'monitor' as const, x: 0, y: 0, dims: [64, 32] as [number, number] }
|
|
||||||
expect(displayPins(n).map(p => p.label)).toEqual(['X0', 'X1', 'X2', 'X3', 'X4', 'X5', 'Y0', 'Y1', 'Y2', 'Y3', 'Y4', 'D', 'WR', 'CLR'])
|
|
||||||
expect(displayPins({ ...n, kind: 'rgbmonitor', dims: [5, 3] }).map(p => p.label)).toEqual(['X0', 'X1', 'X2', 'Y0', 'Y1', 'R', 'G', 'B', 'WR', 'CLR'])
|
|
||||||
expect(ratioText(64, 32)).toBe('2:1')
|
|
||||||
expect(ratioText(1920, 1080)).toBe('16:9')
|
|
||||||
expect(ratioText(127, 3)).toBe('42.33:1')
|
|
||||||
expect(clampSize('monitor', 500, 0)).toEqual([128, 2])
|
|
||||||
// An old terminal (no size) keeps its 32 × 10 and its pins.
|
|
||||||
expect(displaySize({ id: 't', kind: 'terminal', x: 0, y: 0 })).toEqual([32, 10])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a rising WR sets the pixel at X, Y to D; CLR clears; resizing keeps what fits', async () => {
|
|
||||||
const p = createProject({ examples: false })
|
|
||||||
const sw = (id: string, y: number) => ({ id, kind: 'input' as const, x: 0, y, label: id.toUpperCase() })
|
|
||||||
p.components.push({
|
|
||||||
id: 'mon',
|
|
||||||
name: 'Mon',
|
|
||||||
symbol: 'box',
|
|
||||||
nodes: [sw('x0', 0), sw('x1', 2), sw('y0', 4), sw('y1', 6), sw('d', 8), { id: 'w', kind: 'button', x: 0, y: 10, label: 'W' }, { id: 'c', kind: 'button', x: 0, y: 12, label: 'C' }, { id: 'm', kind: 'monitor', x: 10, y: 0, dims: [4, 4] }],
|
|
||||||
wires: [...['x0', 'x1', 'y0', 'y1', 'd'].map(k => ({ id: `w${k}`, from: { node: k, pin: 'q' }, to: { node: 'm', pin: k } })), { id: 'ww', from: { node: 'w', pin: 'q' }, to: { node: 'm', pin: 'wr' } }, { id: 'wc', from: { node: 'c', pin: 'q' }, to: { node: 'm', pin: 'clr' } }],
|
|
||||||
})
|
|
||||||
p.openId = 'mon'
|
|
||||||
const ed = await openEditor(p)
|
|
||||||
vi.advanceTimersByTime(100)
|
|
||||||
const node = (id: string) => ed.def.value.nodes.find(n => n.id === id)!
|
|
||||||
const click = (id: string) => {
|
|
||||||
ed.press(node(id), true)
|
|
||||||
ed.step()
|
|
||||||
ed.press(node(id), false)
|
|
||||||
ed.step()
|
|
||||||
}
|
|
||||||
// x = 3, y = 2, d = 1
|
|
||||||
for (const k of ['x0', 'x1', 'y1', 'd']) ed.toggleInput(node(k))
|
|
||||||
click('w')
|
|
||||||
const px = () => [...ed.frames.value.get('m')!.px]
|
|
||||||
expect(px().indexOf(1)).toBe(2 * 4 + 3)
|
|
||||||
expect(px().filter(v => v).length).toBe(1)
|
|
||||||
ed.setDims('m', 8, 3)
|
|
||||||
expect(ed.frames.value.get('m')!.px.length).toBe(24)
|
|
||||||
expect(px().indexOf(1)).toBe(2 * 8 + 3)
|
|
||||||
click('c')
|
|
||||||
expect(px().some(v => v)).toBe(false)
|
|
||||||
ed.turnDisplay('m')
|
|
||||||
expect(node('m').dims).toEqual([3, 8])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,244 +0,0 @@
|
||||||
import { describe, expect, it } from 'vitest'
|
|
||||||
import { LANE } from '../app/lib/logic/cables'
|
|
||||||
import { cableBits, GRID, shapeOf, type Pt, type Shape } from '../app/lib/logic/geometry'
|
|
||||||
import { latchedTo } from '../app/lib/logic/latch'
|
|
||||||
import { moveParts, moveStart } from '../app/lib/logic/move'
|
|
||||||
import { createProject, lookup } from '../app/lib/logic/ops'
|
|
||||||
import { circuitRoutes, type Routed } from '../app/lib/logic/routing'
|
|
||||||
import type { CircuitNode, ComponentDef, Wire } from '../app/lib/logic/types'
|
|
||||||
|
|
||||||
interface Circuit {
|
|
||||||
def: ComponentDef
|
|
||||||
shapes: Map<string, Shape>
|
|
||||||
}
|
|
||||||
|
|
||||||
function circuit(nodes: CircuitNode[], wires: Wire[]): Circuit {
|
|
||||||
const p = createProject({ examples: false })
|
|
||||||
const def: ComponentDef = { id: 'root', name: 'Root', symbol: 'box', nodes, wires }
|
|
||||||
p.components.push(def)
|
|
||||||
const get = lookup(p)
|
|
||||||
return { def, shapes: new Map(nodes.map(n => [n.id, shapeOf(n, get)])) }
|
|
||||||
}
|
|
||||||
|
|
||||||
const part = (id: string, kind: CircuitNode['kind'], x: number, y: number, more: Partial<CircuitNode> = {}): CircuitNode => ({ id, kind, x, y, ...more })
|
|
||||||
const wire = (id: string, from: string, to: string, pts?: Pt[]): Wire => {
|
|
||||||
const [fn, fp] = from.split('.')
|
|
||||||
const [tn, tp] = to.split('.')
|
|
||||||
return { id, from: { node: fn!, pin: fp! }, to: { node: tn!, pin: tp! }, ...(pts ? { pts } : {}) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Drawn width of a cable in pixels, as the canvas draws it: a ribbon's sleeve with its outline. */
|
|
||||||
const widthOf = (c: Circuit) => (id: string) => {
|
|
||||||
const w = c.def.wires.find(x => x.id === id)
|
|
||||||
const from = w && c.def.nodes.find(n => n.id === w.from.node)
|
|
||||||
return from?.kind === 'bundle' ? cableBits(from) * LANE * GRID + 6 : undefined
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Moves parts the way the canvas does: in steps from where they started, as a drag goes. */
|
|
||||||
function drag(c: Circuit, ids: string[], steps: Pt[], picked: string[] = []) {
|
|
||||||
const start = moveStart(c.def, new Set(ids), picked)
|
|
||||||
for (const [dx, dy] of steps) moveParts(c.def, start, dx, dy, c.shapes, { widthOf: widthOf(c) })
|
|
||||||
}
|
|
||||||
|
|
||||||
const routes = (c: Circuit) => circuitRoutes(c.def, c.shapes, { widthOf: widthOf(c) })
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Lines drawn over or under a part, as "wire>part": a line counts as wide
|
|
||||||
* as it is drawn, and only its ends may touch a part, on their own pins.
|
|
||||||
*/
|
|
||||||
function underParts(c: Circuit, rs: Routed[]): string[] {
|
|
||||||
const out: string[] = []
|
|
||||||
for (const r of rs) {
|
|
||||||
const p = r.draw
|
|
||||||
for (let i = 0; i < p.length - 1; i++) {
|
|
||||||
let [ax, ay] = p[i]!
|
|
||||||
let [bx, by] = p[i + 1]!
|
|
||||||
// Pins that touch (a latched part): nothing is drawn.
|
|
||||||
if (ax === bx && ay === by) continue
|
|
||||||
const dx = Math.sign(bx - ax)
|
|
||||||
const dy = Math.sign(by - ay)
|
|
||||||
// The ends on the wire's own pins touch their parts.
|
|
||||||
if (i === 0) [ax, ay] = [ax + dx * r.h, ay + dy * r.h]
|
|
||||||
if (i === p.length - 2) [bx, by] = [bx - dx * r.h, by - dy * r.h]
|
|
||||||
if ((bx - ax) * dx < 0 || (by - ay) * dy < 0) continue
|
|
||||||
const m = r.h - 1e-6
|
|
||||||
for (const n of c.def.nodes) {
|
|
||||||
if (n.kind === 'note') continue
|
|
||||||
const b = c.shapes.get(n.id)!.body
|
|
||||||
const x0 = n.x + b.x - m
|
|
||||||
const x1 = n.x + b.x + b.w + m
|
|
||||||
const y0 = n.y + b.y - m
|
|
||||||
const y1 = n.y + b.y + b.h + m
|
|
||||||
const lx = Math.min(ax, bx)
|
|
||||||
const hx = Math.max(ax, bx)
|
|
||||||
const ly = Math.min(ay, by)
|
|
||||||
const hy = Math.max(ay, by)
|
|
||||||
if (ly < y1 && hy > y0 && lx < x1 && hx > x0) out.push(`${r.id}>${n.id}`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Lines of different signals drawn on or against each other (or routed so, `grid`), as "wire/wire". */
|
|
||||||
function touching(rs: Routed[], grid = false): string[] {
|
|
||||||
const segs: { id: string; net: string; h: number; horizontal: boolean; c: number; lo: number; hi: number }[] = []
|
|
||||||
for (const r of rs) {
|
|
||||||
const p = grid ? r.grid : r.draw
|
|
||||||
for (let i = 0; i < p.length - 1; i++) {
|
|
||||||
const [ax, ay] = p[i]!
|
|
||||||
const [bx, by] = p[i + 1]!
|
|
||||||
if (ax === bx && ay === by) continue
|
|
||||||
const horizontal = ay === by
|
|
||||||
segs.push({ id: r.id, net: r.net, h: r.h, horizontal, c: horizontal ? ay : ax, lo: horizontal ? Math.min(ax, bx) : Math.min(ay, by), hi: horizontal ? Math.max(ax, bx) : Math.max(ay, by) })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const out: string[] = []
|
|
||||||
for (let i = 0; i < segs.length; i++) {
|
|
||||||
for (let j = i + 1; j < segs.length; j++) {
|
|
||||||
const s = segs[i]!
|
|
||||||
const t = segs[j]!
|
|
||||||
if (s.net === t.net || s.horizontal !== t.horizontal || Math.abs(s.c - t.c) >= s.h + t.h - 1e-9) continue
|
|
||||||
if (Math.min(s.hi, t.hi) - Math.max(s.lo, t.lo) > 1e-9) out.push(`${s.id}/${t.id}`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
const shifted = (route: Pt[], dx: number, dy: number) => route.map(([x, y]) => [x + dx, y + dy])
|
|
||||||
const routeOf = (rs: Routed[], id: string) => rs.find(r => r.id === id)!.grid
|
|
||||||
|
|
||||||
describe('dragging parts', () => {
|
|
||||||
it('a wire to a part that moves a little keeps its hand-placed corners, stretched to the pin', () => {
|
|
||||||
const c = circuit([part('s', 'input', 0, 0), part('l', 'output', 12, 6)], [wire('w', 's.q', 'l.a', [[5, 0], [5, 6]])])
|
|
||||||
drag(c, ['l'], [[0, -2]])
|
|
||||||
expect(c.def.wires[0]!.pts).toEqual([[5, 0], [5, 4]])
|
|
||||||
expect(routeOf(routes(c), 'w')).toEqual([[2, 0], [5, 0], [5, 4], [12, 4]])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a wire whose part moves past its hand-placed corners comes into the pin from the left, not through the part', () => {
|
|
||||||
const c = circuit([part('s', 'input', 0, 0), part('g', 'nand', 14, 0)], [wire('w', 's.q', 'g.a', [[6, 0], [6, 4], [11, 4], [11, 0]])])
|
|
||||||
drag(c, ['g'], [[-2, 0], [-5, 0]])
|
|
||||||
const rs = routes(c)
|
|
||||||
expect(underParts(c, rs)).toEqual([])
|
|
||||||
expect(routeOf(rs, 'w').at(-1)).toEqual([9, 0])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('parts moved together keep the wires between them; wires to parts that stay go around what is in the way', () => {
|
|
||||||
const c = circuit(
|
|
||||||
[
|
|
||||||
part('i1', 'input', 0, 0),
|
|
||||||
part('i2', 'input', 0, 4),
|
|
||||||
part('g1', 'nand', 10, 0),
|
|
||||||
part('g2', 'nand', 20, 3),
|
|
||||||
part('o', 'output', 32, 4),
|
|
||||||
// A part that stays, beside where the moved parts go.
|
|
||||||
part('x', 'nand', 3, 7),
|
|
||||||
],
|
|
||||||
[
|
|
||||||
wire('w1', 'i1.q', 'g1.a'),
|
|
||||||
wire('w2', 'i2.q', 'g1.b', [[5, 4], [5, 2]]),
|
|
||||||
wire('w3', 'g1.q', 'g2.a', [[17, 1], [17, 3]]),
|
|
||||||
wire('w4', 'g1.q', 'g2.b'),
|
|
||||||
wire('w5', 'g2.q', 'o.a'),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
const before = routes(c)
|
|
||||||
drag(c, ['g1', 'g2'], [[0, 3], [1, 6], [0, 8]])
|
|
||||||
const rs = routes(c)
|
|
||||||
expect(underParts(c, rs)).toEqual([])
|
|
||||||
expect(touching(rs)).toEqual([])
|
|
||||||
// Between the two moved parts: the same shape, moved along.
|
|
||||||
expect(routeOf(rs, 'w3')).toEqual(shifted(routeOf(before, 'w3'), 0, 8))
|
|
||||||
expect(routeOf(rs, 'w4')).toEqual(shifted(routeOf(before, 'w4'), 0, 8))
|
|
||||||
expect(c.def.wires.find(w => w.id === 'w3')!.pts).toEqual([[17, 9], [17, 11]])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a wire whose stretched corners would run along another signal lets go of them', () => {
|
|
||||||
const c = circuit(
|
|
||||||
[part('s1', 'input', -2, 0), part('l1', 'output', 30, 0), part('s2', 'input', 0, 12), part('l2', 'output', 30, 9)],
|
|
||||||
[wire('w1', 's1.q', 'l1.a', [[10, 0], [10, 6], [20, 6], [20, 0]]), wire('w2', 's2.q', 'l2.a', [[4, 12], [4, 9], [16, 9]])],
|
|
||||||
)
|
|
||||||
drag(c, ['l2'], [[0, -3]])
|
|
||||||
const rs = routes(c)
|
|
||||||
expect(touching(rs, true)).toEqual([])
|
|
||||||
expect(underParts(c, rs)).toEqual([])
|
|
||||||
// The other wire is left as it was.
|
|
||||||
expect(c.def.wires[0]!.pts).toEqual([[10, 0], [10, 6], [20, 6], [20, 0]])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('everything moved at once keeps every corner, even of wires that already shared a line', () => {
|
|
||||||
const c = circuit(
|
|
||||||
[part('s1', 'input', -2, 0), part('l1', 'output', 10, 0), part('s2', 'input', -2, 4), part('l2', 'output', 10, 4)],
|
|
||||||
[wire('a', 's1.q', 'l1.a', [[2, 0], [2, 4], [8, 4], [8, 0]]), wire('b', 's2.q', 'l2.a', [[1, 4], [9, 4]])],
|
|
||||||
)
|
|
||||||
drag(c, ['s1', 'l1', 's2', 'l2'], [[3, 5]], ['a', 'b'])
|
|
||||||
expect(c.def.wires.map(w => w.pts)).toEqual([shifted([[2, 0], [2, 4], [8, 4], [8, 0]], 3, 5), shifted([[1, 4], [9, 4]], 3, 5)])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a wire moved on its own goes where it is put', () => {
|
|
||||||
const c = circuit([part('s', 'input', 0, 0), part('l', 'output', 12, 6)], [wire('w', 's.q', 'l.a', [[5, 0], [5, 6]])])
|
|
||||||
drag(c, [], [[1, 0]], ['w'])
|
|
||||||
expect(c.def.wires[0]!.pts).toEqual([[6, 0], [6, 6]])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a part moved onto a wire that stays: the wire lets go of the corners under it', () => {
|
|
||||||
const c = circuit(
|
|
||||||
[part('a', 'input', 0, 0), part('b', 'output', 30, 0), part('p', 'nand', 12, -10)],
|
|
||||||
[wire('w', 'a.q', 'b.a', [[8, 0], [8, 6], [20, 6], [20, 0]])],
|
|
||||||
)
|
|
||||||
drag(c, ['p'], [[0, 15]])
|
|
||||||
const rs = routes(c)
|
|
||||||
expect(underParts(c, rs)).toEqual([])
|
|
||||||
expect(touching(rs)).toEqual([])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('what shows while dragging is what stays: corners let go on the way come back', () => {
|
|
||||||
const make = () =>
|
|
||||||
circuit([part('a', 'input', 0, 0), part('b', 'output', 30, 0), part('p', 'nand', 12, -10)], [wire('w', 'a.q', 'b.a', [[8, 0], [8, 6], [20, 6], [20, 0]])])
|
|
||||||
const c = make()
|
|
||||||
// Down over the wire's dip and on below it.
|
|
||||||
drag(c, ['p'], [[0, 5], [0, 15], [0, 16], [0, 20]])
|
|
||||||
const once = make()
|
|
||||||
drag(once, ['p'], [[0, 20]])
|
|
||||||
expect(c.def).toEqual(once.def)
|
|
||||||
expect(c.def.wires[0]!.pts).toEqual([[8, 0], [8, 6], [20, 6], [20, 0]])
|
|
||||||
expect(underParts(c, routes(c))).toEqual([])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a cable keeps clear of parts by its full width', () => {
|
|
||||||
// An 8-wire cable with a hand-placed hump; a part sits below where its end goes.
|
|
||||||
const c = circuit(
|
|
||||||
[part('bu', 'bundle', 0, 0, { bits: 8 }), part('sp', 'split', 30, 0, { bits: 8 }), part('x', 'nand', 18, 12)],
|
|
||||||
[wire('c', 'bu.q', 'sp.a', [[5, 3], [5, 10], [14, 10], [14, 3]])],
|
|
||||||
)
|
|
||||||
drag(c, ['sp'], [[0, 8]])
|
|
||||||
const rs = routes(c)
|
|
||||||
expect(rs[0]!.h).toBeGreaterThan(0.5)
|
|
||||||
expect(underParts(c, rs)).toEqual([])
|
|
||||||
// A plain wire there passes the part with room to spare and keeps its corners.
|
|
||||||
const plain = circuit(
|
|
||||||
[part('s', 'input', -1, 3), part('l', 'output', 30, 3), part('x', 'nand', 18, 12)],
|
|
||||||
[wire('w', 's.q', 'l.a', [[5, 3], [5, 10], [14, 10], [14, 3]])],
|
|
||||||
)
|
|
||||||
drag(plain, ['l'], [[0, 8]])
|
|
||||||
expect(plain.def.wires[0]!.pts?.length).toBeGreaterThan(1)
|
|
||||||
expect(underParts(plain, routes(plain))).toEqual([])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a part latched onto another moves with it, and its wires to parts that stay settle the same way', () => {
|
|
||||||
const c = circuit(
|
|
||||||
[part('g', 'nand', 10, 0), part('o', 'output', 14, 1, { latch: 'g' }), part('l', 'lamp', 30, 1), part('x', 'nand', 18, 3)],
|
|
||||||
[wire('in', 'g.q', 'o.a'), wire('w', 'o.q', 'l.a', [[20, 1], [20, -4], [26, -4], [26, 1]])],
|
|
||||||
)
|
|
||||||
const ids = new Set(['g'])
|
|
||||||
for (const n of latchedTo(c.def, ids)) ids.add(n.id)
|
|
||||||
drag(c, [...ids], [[0, 6]])
|
|
||||||
const o = c.def.nodes.find(n => n.id === 'o')!
|
|
||||||
expect([o.x, o.y]).toEqual([14, 7])
|
|
||||||
const rs = routes(c)
|
|
||||||
expect(routeOf(rs, 'in')).toEqual([[14, 7], [14, 7]])
|
|
||||||
expect(underParts(c, rs)).toEqual([])
|
|
||||||
expect(touching(rs)).toEqual([])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
import { compile } from '../app/lib/logic/compile'
|
import { compile } from '../app/lib/logic/compile'
|
||||||
import { faceCandidates, pixelKey, screenLayouts, shapeOf, splitScreens } from '../app/lib/logic/geometry'
|
import { faceCandidates, screenLayouts, shapeOf } from '../app/lib/logic/geometry'
|
||||||
import { matchScore } from '../app/lib/match'
|
import { matchScore } from '../app/lib/match'
|
||||||
import { createProject, lookup } from '../app/lib/logic/ops'
|
import { createProject, lookup } from '../app/lib/logic/ops'
|
||||||
import { toProject } from '../app/lib/logic/project'
|
import { toProject } from '../app/lib/logic/project'
|
||||||
|
|
@ -159,86 +159,3 @@ describe('finding parts', () => {
|
||||||
expect(matchScore('Lamp', 'xyz')).toBe(0)
|
expect(matchScore('Lamp', 'xyz')).toBe(0)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('the box designer, more', () => {
|
|
||||||
/** A 2×2 screen of pixels and two inputs, in a component placed once in another. */
|
|
||||||
function screened() {
|
|
||||||
const p = createProject({ examples: false })
|
|
||||||
const inner: ComponentDef = {
|
|
||||||
id: 'inner',
|
|
||||||
name: 'Scr',
|
|
||||||
symbol: 'box',
|
|
||||||
nodes: [
|
|
||||||
{ id: 'a', kind: 'input', x: 0, y: 0, label: 'A' },
|
|
||||||
{ id: 'b', kind: 'input', x: 0, y: 1, label: 'B' },
|
|
||||||
{ id: 'p1', kind: 'pixel', x: 6, y: 0 },
|
|
||||||
{ id: 'p2', kind: 'pixel', x: 8, y: 0 },
|
|
||||||
{ id: 'p3', kind: 'pixel', x: 6, y: 2 },
|
|
||||||
{ id: 'p4', kind: 'pixel', x: 8, y: 2 },
|
|
||||||
],
|
|
||||||
wires: [],
|
|
||||||
}
|
|
||||||
p.components.push(inner)
|
|
||||||
return { p, inner, get: lookup(p), node: { id: 'c', kind: 'chip' as const, chip: 'inner', x: 0, y: 0 } }
|
|
||||||
}
|
|
||||||
|
|
||||||
it('splitting a screen into pixels moves nothing, also sized and turned', () => {
|
|
||||||
const [screen] = screenLayouts(screened().inner)
|
|
||||||
for (const rotate of [undefined, 90, 180, 270]) {
|
|
||||||
const it = { ...screen!, x: 1, y: 1, scale: 2, ...(rotate ? { rotate } : {}) }
|
|
||||||
const pixels = splitScreens([it], new Set([it.key]))
|
|
||||||
expect(pixels).toHaveLength(4)
|
|
||||||
// The four pixels cover exactly the screen's turned square: 2 × 2 pixels of 1 × 2 = a 4 × 4 square at 1, 1.
|
|
||||||
const xs = pixels.map(px => px.x).sort((a, b) => a - b)
|
|
||||||
const ys = pixels.map(px => px.y).sort((a, b) => a - b)
|
|
||||||
expect([xs[0], xs[3], ys[0], ys[3]]).toEqual([1, 3, 1, 3])
|
|
||||||
expect(pixels.every(px => px.scale === 2 && px.w === 1 && px.key === pixelKey(px.id) && px.screenOf === it.key)).toBe(true)
|
|
||||||
}
|
|
||||||
// Turned a quarter, the top left pixel goes to the top right.
|
|
||||||
const turned = splitScreens([{ ...screen!, x: 0, y: 0, rotate: 90 }], new Set([screen!.key]))
|
|
||||||
expect(turned.find(px => px.id === 'p1')).toMatchObject({ x: 1, y: 0 })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('pins can change order on their edge', () => {
|
|
||||||
const { inner, get, node } = screened()
|
|
||||||
const before = shapeOf(node, get).inputs.map(p => [p.key, p.dy])
|
|
||||||
inner.design = { w: 6, h: 4, pinOrder: ['b', 'a'] }
|
|
||||||
const after = shapeOf(node, get).inputs
|
|
||||||
expect(after.find(p => p.key === 'b')!.dy).toBe(before[0]![1])
|
|
||||||
expect(after.find(p => p.key === 'a')!.dy).toBe(before[1]![1])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a fitted box grows and shrinks with what is on it; a set one keeps its size', () => {
|
|
||||||
const { inner, get, node } = screened()
|
|
||||||
inner.design = { w: 20, h: 20, fit: true, place: { screen: { x: 1, y: 1 } } }
|
|
||||||
const small = shapeOf(node, get).body
|
|
||||||
expect(small.w).toBeLessThan(20)
|
|
||||||
inner.design.place!.screen = { x: 12, y: 1 }
|
|
||||||
expect(shapeOf(node, get).body.w).toBeGreaterThan(small.w + 8)
|
|
||||||
delete inner.design.fit
|
|
||||||
inner.design.place!.screen = { x: 1, y: 1 }
|
|
||||||
expect(shapeOf(node, get).body.w).toBe(20)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a display of a part inside shows in a free spot inside the box, not below it', () => {
|
|
||||||
const { p } = screened()
|
|
||||||
const outer: ComponentDef = {
|
|
||||||
id: 'outer',
|
|
||||||
name: 'Outer',
|
|
||||||
symbol: 'box',
|
|
||||||
nodes: [
|
|
||||||
{ id: 'x', kind: 'chip', chip: 'inner', x: 0, y: 0 },
|
|
||||||
...['i0', 'i1', 'i2', 'i3', 'i4', 'i5'].map((id, k) => ({ id, kind: 'input' as const, x: -6, y: k, label: id })),
|
|
||||||
],
|
|
||||||
wires: [],
|
|
||||||
design: { w: 10, h: 7, fit: true, show: ['x/screen'] },
|
|
||||||
}
|
|
||||||
p.components.push(outer)
|
|
||||||
const shape = shapeOf({ id: 'o', kind: 'chip', chip: 'outer', x: 0, y: 0 }, lookup(p))
|
|
||||||
const scr = shape.face!.find(f => f.key === 'x/screen')!
|
|
||||||
expect(scr.y + scr.h).toBeLessThanOrEqual(shape.body.y + shape.body.h)
|
|
||||||
// The six inputs make it six rows high; the screen fits beside their names.
|
|
||||||
expect(shape.body.h).toBeLessThan(7)
|
|
||||||
expect(scr.from).toBe('Scr')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,99 +0,0 @@
|
||||||
// Dumps a conformance corpus from the TypeScript implementation: for a set of
|
|
||||||
// circuits, the netlist shape, the transistor counts, the truth tables and the
|
|
||||||
// puzzle scores exactly as the TS computes them today.
|
|
||||||
//
|
|
||||||
// The Laravel port is validated against this file, so "the PHP agrees with the
|
|
||||||
// TS" becomes a test instead of a claim.
|
|
||||||
//
|
|
||||||
// pnpm vitest run tests/golden-vectors.test.ts (writes tests/fixtures/golden.json)
|
|
||||||
|
|
||||||
import { writeFileSync } from 'node:fs'
|
|
||||||
import { resolve } from 'node:path'
|
|
||||||
import { it } from 'vitest'
|
|
||||||
import { exampleLibrary, starterCircuit } from '../app/lib/logic/examples'
|
|
||||||
import { compile } from '../app/lib/logic/compile'
|
|
||||||
import { nandCounts, stats, truthTable, TRANSISTORS_PER_NAND } from '../app/lib/logic/analyze'
|
|
||||||
import { describeCircuit, makePuzzle, scoreSolution, weeklyPuzzle, weekKey, rng } from '../app/lib/logic/puzzles'
|
|
||||||
import { toProject, LIMITS } from '../app/lib/logic/project'
|
|
||||||
import type { ComponentDef } from '../app/lib/logic/types'
|
|
||||||
|
|
||||||
const components: ComponentDef[] = [...exampleLibrary(), starterCircuit()]
|
|
||||||
const get = (id: string) => components.find(d => d.id === id)
|
|
||||||
|
|
||||||
const circuits = components.map(def => {
|
|
||||||
const nl = compile(get, def.id)
|
|
||||||
const nands = nandCounts(components).get(def.id) ?? 0
|
|
||||||
const table = truthTable(get, def.id)
|
|
||||||
return {
|
|
||||||
id: def.id,
|
|
||||||
name: def.name,
|
|
||||||
nands,
|
|
||||||
transistors: nands * TRANSISTORS_PER_NAND,
|
|
||||||
netlist: {
|
|
||||||
errors: nl.errors,
|
|
||||||
gates: nl.gates?.length ?? null,
|
|
||||||
sources: nl.sources ? Object.keys(nl.sources).sort() : null,
|
|
||||||
sinks: nl.sinks ? Object.keys(nl.sinks).sort() : null,
|
|
||||||
},
|
|
||||||
stats: nl.errors.length ? null : stats(nl),
|
|
||||||
describe: (() => { try { return describeCircuit(get, def.id) } catch (e) { return { error: (e as Error).message } } })(),
|
|
||||||
truth: 'error' in table ? table : { inputs: table.inputs, outputs: table.outputs, rows: table.rows },
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// Every circuit scored against a puzzle made from itself: must pass, and the
|
|
||||||
// transistor count must match. This exercises compile + Simulator + scoring.
|
|
||||||
const selfScores = components.map(def => {
|
|
||||||
try {
|
|
||||||
const spec = { ...makePuzzle(components, def.id, def.name, ''), id: `self:${def.id}` }
|
|
||||||
return { id: def.id, spec, score: scoreSolution(components, def.id, spec) }
|
|
||||||
} catch (e) {
|
|
||||||
return { id: def.id, spec: null, score: { error: (e as Error).message } }
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// Cross scoring: each circuit against every other circuit's puzzle. Most fail,
|
|
||||||
// and the failure messages are part of the contract the port has to reproduce.
|
|
||||||
const crossScores: unknown[] = []
|
|
||||||
for (const a of components) {
|
|
||||||
for (const b of components) {
|
|
||||||
if (a.id === b.id) continue
|
|
||||||
try {
|
|
||||||
const spec = { ...makePuzzle(components, b.id, b.name, ''), id: `x:${b.id}` }
|
|
||||||
crossScores.push({ solution: a.id, puzzle: b.id, score: scoreSolution(components, a.id, spec) })
|
|
||||||
} catch { /* puzzles can't be made from every circuit; skip those */ }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The weekly puzzle is generated from the ISO week and must be identical in PHP.
|
|
||||||
const weeks = ['2026-01', '2026-07', '2026-26', '2026-43', '2026-45', '2026-52']
|
|
||||||
.map(key => ({ key, puzzle: weeklyPuzzle(key) }))
|
|
||||||
|
|
||||||
// The seeded RNG drives the weekly puzzle, so pin its sequence directly.
|
|
||||||
const rngRuns = [1, 42, 1337, 2026_43].map(seed => {
|
|
||||||
const r = rng(seed)
|
|
||||||
return { seed, values: Array.from({ length: 12 }, () => r()) }
|
|
||||||
})
|
|
||||||
|
|
||||||
const out = {
|
|
||||||
note: 'Generated from the TypeScript implementation. The PHP port must reproduce this exactly.',
|
|
||||||
generatedFrom: 'tests/golden-vectors.test.ts',
|
|
||||||
limits: { project: LIMITS, transistorsPerNand: TRANSISTORS_PER_NAND },
|
|
||||||
weekKeyOf: ['2026-01-01', '2026-06-15', '2026-11-11', '2026-12-31']
|
|
||||||
.map(d => ({ date: d, key: weekKey(new Date(d + 'T12:00:00Z')) })),
|
|
||||||
components: toProject({ name: 'golden', components }).components,
|
|
||||||
circuits,
|
|
||||||
selfScores,
|
|
||||||
crossScores,
|
|
||||||
weeks,
|
|
||||||
rngRuns,
|
|
||||||
}
|
|
||||||
|
|
||||||
it('writes the golden vectors', () => {
|
|
||||||
const path = resolve(import.meta.dirname, 'fixtures/golden.json')
|
|
||||||
writeFileSync(path, JSON.stringify(out, null, 1))
|
|
||||||
console.log(
|
|
||||||
`golden.json: ${circuits.length} circuits, ${selfScores.length} self scores, ` +
|
|
||||||
`${crossScores.length} cross scores, ${weeks.length} weeks`,
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
@ -1,85 +0,0 @@
|
||||||
import { describe, expect, it } from 'vitest'
|
|
||||||
import { shapeOf } from '../app/lib/logic/geometry'
|
|
||||||
import { latchedTo, latchInto, latchLayout, latchTarget, syncLatches } from '../app/lib/logic/latch'
|
|
||||||
import { createProject, lookup } from '../app/lib/logic/ops'
|
|
||||||
import type { ComponentDef, Project } from '../app/lib/logic/types'
|
|
||||||
|
|
||||||
/** A 4-bit counter's outputs (the example component) feeding a hex display placed further right. */
|
|
||||||
function setup(order = [0, 1, 2, 3]): { p: Project; def: ComponentDef } {
|
|
||||||
const p = createProject({ examples: true })
|
|
||||||
const counter = p.components.find(d => d.id === 'ex-counter4') ?? p.components.find(d => /counter/i.test(d.name))!
|
|
||||||
const def: ComponentDef = { id: 'root', name: 'Root', symbol: 'box', nodes: [{ id: 'c', kind: 'chip', chip: counter.id, x: 0, y: 0 }, { id: 'h', kind: 'hex', x: 20, y: 3 }], wires: [] }
|
|
||||||
const outs = shapeOf(def.nodes[0]!, lookup(p)).outputs.slice(0, 4)
|
|
||||||
outs.forEach((o, i) => def.wires.push({ id: `w${i}`, from: { node: 'c', pin: o.key }, to: { node: 'h', pin: `b${order[i]}` } }))
|
|
||||||
p.components.push(def)
|
|
||||||
return { p, def }
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('latching a part onto another', () => {
|
|
||||||
it('a display wired to four outputs in order latches onto them: its inputs on their pins', () => {
|
|
||||||
const { p, def } = setup()
|
|
||||||
const get = lookup(p)
|
|
||||||
const hex = def.nodes[1]!
|
|
||||||
expect(latchTarget(def, hex, get)?.id).toBe('c')
|
|
||||||
expect(latchInto(def, hex, 'c', get)).toBe(true)
|
|
||||||
expect(hex.latch).toBe('c')
|
|
||||||
const chip = def.nodes[0]!
|
|
||||||
const outs = shapeOf(chip, get).outputs.slice(0, 4)
|
|
||||||
const ins = shapeOf(hex, get).inputs
|
|
||||||
outs.forEach((o, i) => {
|
|
||||||
expect(hex.x + ins[i]!.dx).toBe(chip.x + o.dx)
|
|
||||||
expect(hex.y + ins[i]!.dy).toBe(chip.y + o.dy)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('wired in another order it does not fit, so it does not latch', () => {
|
|
||||||
const { p, def } = setup([1, 0, 2, 3])
|
|
||||||
expect(latchTarget(def, def.nodes[1]!, lookup(p))).toBeUndefined()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a pin that would land on a pin it is not wired to keeps it from latching', () => {
|
|
||||||
const { p, def } = setup()
|
|
||||||
// Only three of the four outputs are wired: the fourth input would sit on an output without a wire.
|
|
||||||
def.wires = def.wires.filter(w => w.id !== 'w3')
|
|
||||||
const get = lookup(p)
|
|
||||||
expect(latchLayout(def, def.nodes[1]!, def.nodes[0]!, get)).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('parts whose shared pins already touch latch by themselves, the smaller onto the larger', () => {
|
|
||||||
const { p, def } = setup()
|
|
||||||
const get = lookup(p)
|
|
||||||
const hex = def.nodes[1]!
|
|
||||||
const lay = latchLayout(def, hex, def.nodes[0]!, get)!
|
|
||||||
hex.x = lay.x
|
|
||||||
hex.y = lay.y
|
|
||||||
syncLatches(p)
|
|
||||||
expect(hex.latch).toBe('c')
|
|
||||||
expect(def.nodes[0]!.latch).toBeUndefined()
|
|
||||||
expect(latchedTo(def, new Set(['c'])).map(n => n.id)).toEqual(['h'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a latched part stays on its part\'s pins when that part moves', () => {
|
|
||||||
const { p, def } = setup()
|
|
||||||
const get = lookup(p)
|
|
||||||
const hex = def.nodes[1]!
|
|
||||||
latchInto(def, hex, 'c', get)
|
|
||||||
const dx = hex.x - def.nodes[0]!.x
|
|
||||||
def.nodes[0]!.x += 7
|
|
||||||
syncLatches(p)
|
|
||||||
expect(hex.x - def.nodes[0]!.x).toBe(dx)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a switch feeding a component input from the left latches onto it', () => {
|
|
||||||
const { p, def } = setup()
|
|
||||||
const get = lookup(p)
|
|
||||||
const chip = def.nodes[0]!
|
|
||||||
const pin = shapeOf(chip, get).inputs[0]!
|
|
||||||
def.nodes.push({ id: 's', kind: 'input', x: -10, y: 5 })
|
|
||||||
def.wires.push({ id: 'ws', from: { node: 's', pin: 'q' }, to: { node: 'c', pin: pin.key } })
|
|
||||||
const sw = def.nodes[2]!
|
|
||||||
expect(latchTarget(def, sw, get)?.id).toBe('c')
|
|
||||||
latchInto(def, sw, 'c', get)
|
|
||||||
const out = shapeOf(sw, get).outputs[0]!
|
|
||||||
expect([sw.x + out.dx, sw.y + out.dy]).toEqual([chip.x + pin.dx, chip.y + pin.dy])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,95 +0,0 @@
|
||||||
// The library's API handlers, run against stand-ins for Nitro's request
|
|
||||||
// helpers and an in-memory store: publish, update, list, read, remove.
|
|
||||||
import { beforeAll, describe, expect, it } from 'vitest'
|
|
||||||
import { libraryBundle } from '../app/lib/logic/library'
|
|
||||||
import { createProject } from '../app/lib/logic/ops'
|
|
||||||
|
|
||||||
interface FakeEvent {
|
|
||||||
body?: string
|
|
||||||
params?: Record<string, string>
|
|
||||||
headers?: Record<string, string>
|
|
||||||
query?: Record<string, string>
|
|
||||||
status?: number
|
|
||||||
}
|
|
||||||
type Handler = (e: FakeEvent) => Promise<Record<string, unknown>>
|
|
||||||
|
|
||||||
const stores = new Map<string, Map<string, unknown>>()
|
|
||||||
const g = globalThis as Record<string, unknown>
|
|
||||||
const handlers: Record<string, Handler> = {}
|
|
||||||
|
|
||||||
beforeAll(async () => {
|
|
||||||
Object.assign(g, {
|
|
||||||
defineEventHandler: (fn: Handler) => fn,
|
|
||||||
createError: ({ statusCode, message }: { statusCode: number; message: string }) => Object.assign(new Error(message), { statusCode }),
|
|
||||||
readRawBody: async (e: FakeEvent) => e.body,
|
|
||||||
readBody: async (e: FakeEvent) => JSON.parse(e.body ?? 'null'),
|
|
||||||
getRouterParam: (e: FakeEvent, k: string) => e.params?.[k],
|
|
||||||
getHeader: (e: FakeEvent, k: string) => e.headers?.[k],
|
|
||||||
getQuery: (e: FakeEvent) => e.query ?? {},
|
|
||||||
getRequestIP: () => '127.0.0.1',
|
|
||||||
setHeader: () => {},
|
|
||||||
setResponseStatus: (e: FakeEvent, s: number) => (e.status = s),
|
|
||||||
useStorage: (name: string) => {
|
|
||||||
if (!stores.has(name)) stores.set(name, new Map())
|
|
||||||
const m = stores.get(name)!
|
|
||||||
return {
|
|
||||||
getItem: async (k: string) => structuredClone(m.get(k) ?? null),
|
|
||||||
setItem: async (k: string, v: unknown) => void m.set(k, structuredClone(v)),
|
|
||||||
hasItem: async (k: string) => m.has(k),
|
|
||||||
removeItem: async (k: string) => void m.delete(k),
|
|
||||||
}
|
|
||||||
},
|
|
||||||
})
|
|
||||||
// The server's own helpers, auto-imported there.
|
|
||||||
for (const mod of [await import('../server/utils/shares'), await import('../server/utils/puzzles'), await import('../server/utils/library')]) Object.assign(g, mod)
|
|
||||||
handlers.post = (await import('../server/api/library/index.post')).default as unknown as Handler
|
|
||||||
handlers.list = (await import('../server/api/library/index.get')).default as unknown as Handler
|
|
||||||
handlers.get = (await import('../server/api/library/[id].get')).default as unknown as Handler
|
|
||||||
handlers.put = (await import('../server/api/library/[id].put')).default as unknown as Handler
|
|
||||||
handlers.delete = (await import('../server/api/library/[id].delete')).default as unknown as Handler
|
|
||||||
handlers.name = (await import('../server/api/players/name.post')).default as unknown as Handler
|
|
||||||
})
|
|
||||||
|
|
||||||
const ADA = 'player-ada-000001'
|
|
||||||
const call = (h: string, e: FakeEvent) => handlers[h]!(e)
|
|
||||||
|
|
||||||
describe('library API', () => {
|
|
||||||
it('publishes, lists, updates and removes an entry; only the key holder may change it', async () => {
|
|
||||||
const p = createProject({ examples: true })
|
|
||||||
await call('name', { body: JSON.stringify({ player: ADA, name: 'Ada' }) })
|
|
||||||
const made = await call('post', { body: JSON.stringify({ player: ADA, ...libraryBundle(p, 'ex-fa') }) })
|
|
||||||
expect(made).toMatchObject({ version: 1 })
|
|
||||||
const id = made.id as string
|
|
||||||
const key = made.key as string
|
|
||||||
|
|
||||||
const list = await call('list', { query: { q: 'adder ada' } })
|
|
||||||
expect(list.total).toBe(1)
|
|
||||||
const [entry] = list.entries as Record<string, unknown>[]
|
|
||||||
// Two half adders (XOR of 4 NANDs, AND of 2) and an OR of 3: 15 NANDs.
|
|
||||||
expect(entry).toMatchObject({ id, name: 'Full Adder', author: 'Ada', transistors: 60, inputs: 3, outputs: 2, inNames: ['A', 'B', 'Cin'], outNames: ['S', 'Cout'], uses: 5, version: 1 })
|
|
||||||
expect(JSON.stringify(list)).not.toContain(ADA)
|
|
||||||
expect((await call('list', { query: { q: 'counter' } })).entries).toEqual([])
|
|
||||||
|
|
||||||
const full = await call('get', { params: { id } })
|
|
||||||
expect((full.bundle as { root: string }).root).toBe('ex-fa')
|
|
||||||
expect(await call('get', { params: { id }, query: { meta: '' } })).not.toHaveProperty('bundle')
|
|
||||||
|
|
||||||
const next = JSON.stringify({ player: ADA, ...libraryBundle(p, 'ex-fa') })
|
|
||||||
await expect(call('put', { params: { id }, headers: { 'x-edit-key': 'wrong' }, body: next })).rejects.toMatchObject({ statusCode: 403 })
|
|
||||||
expect(await call('put', { params: { id }, headers: { 'x-edit-key': key }, body: next })).toEqual({ id, version: 2 })
|
|
||||||
expect(((await call('list', {})).entries as { version: number }[])[0]!.version).toBe(2)
|
|
||||||
|
|
||||||
await expect(call('delete', { params: { id }, headers: { 'x-edit-key': 'wrong' } })).rejects.toMatchObject({ statusCode: 403 })
|
|
||||||
await call('delete', { params: { id }, headers: { 'x-edit-key': key } })
|
|
||||||
expect((await call('list', {})).total).toBe(0)
|
|
||||||
await expect(call('get', { params: { id } })).rejects.toMatchObject({ statusCode: 404 })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('refuses requests without a player, broken components and oversized ones', async () => {
|
|
||||||
const p = createProject({ examples: true })
|
|
||||||
const bundle = libraryBundle(p, 'ex-ha')
|
|
||||||
await expect(call('post', { body: JSON.stringify(bundle) })).rejects.toMatchObject({ statusCode: 400 })
|
|
||||||
await expect(call('post', { body: JSON.stringify({ player: ADA, root: 'ex-ha', components: [] }) })).rejects.toMatchObject({ statusCode: 400 })
|
|
||||||
await expect(call('post', { body: JSON.stringify({ player: ADA, ...bundle, pad: 'x'.repeat(1_000_001) }) })).rejects.toMatchObject({ statusCode: 413 })
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,450 +0,0 @@
|
||||||
import { describe, expect, it } from 'vitest'
|
|
||||||
import { nandCounts, truthTable } from '../app/lib/logic/analyze'
|
|
||||||
import { cleanBundle, closure, describeBundle, importBundle, importProblem, LIBRARY_LIMITS, libraryBundle, ownedEntry, publishProblem, type LibraryMeta } from '../app/lib/logic/library'
|
|
||||||
import { createProject, duplicateComponent, lookup, startChallenge } from '../app/lib/logic/ops'
|
|
||||||
import { parseProject, toProject } from '../app/lib/logic/project'
|
|
||||||
import { libraryKeys, setLibraryKey } from '../app/lib/logic/storage'
|
|
||||||
import { CHALLENGES } from '../app/lib/logic/challenges'
|
|
||||||
import type { ComponentDef, LibraryOrigin, Project, Wire } from '../app/lib/logic/types'
|
|
||||||
import { publicMeta, searchLibrary, type LibraryItem } from '../server/utils/library'
|
|
||||||
|
|
||||||
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] } })
|
|
||||||
const origin: LibraryOrigin = { id: 'Lib12345', version: 1, author: 'Ada' }
|
|
||||||
|
|
||||||
/** The rows of a component's truth table, as text. */
|
|
||||||
function rows(p: Project, id: string) {
|
|
||||||
const t = truthTable(lookup(p), id)
|
|
||||||
return 'error' in t ? t.error : t.rows.map(r => `${r.ins.join('')}|${r.outs.join('')}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Ada's project: the examples, a link of her own and a part that sends two lines over it. */
|
|
||||||
function adasProject(): Project {
|
|
||||||
const p = createProject({ examples: true })
|
|
||||||
p.connectors = [{ id: 'k1', name: 'Link', color: 'blue', lines: [{ name: 'D0' }, { name: 'D1' }] }]
|
|
||||||
const sender: ComponentDef = {
|
|
||||||
id: 'csend',
|
|
||||||
name: 'Sender',
|
|
||||||
symbol: 'box',
|
|
||||||
nodes: [
|
|
||||||
{ id: 'a', kind: 'input', x: 0, y: 0, label: 'A' },
|
|
||||||
{ id: 'b', kind: 'input', x: 0, y: 2, label: 'B' },
|
|
||||||
{ id: 'x', kind: 'chip', chip: 'ex-xor', x: 6, y: 0 },
|
|
||||||
{ id: 'tx', kind: 'portout', conn: 'k1', x: 20, y: 0 },
|
|
||||||
],
|
|
||||||
wires: [w('w1', ['a', 'q'], ['x', 'a']), w('w2', ['b', 'q'], ['x', 'b']), w('w3', ['x', 'q'], ['tx', 'l0']), w('w4', ['a', 'q'], ['tx', 'l1'])],
|
|
||||||
}
|
|
||||||
p.components.push(sender)
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
/** What a library entry hands out: the bundle, cleaned as the server does. */
|
|
||||||
const published = (p: Project, id: string) => cleanBundle(JSON.parse(JSON.stringify(libraryBundle(p, id))))
|
|
||||||
|
|
||||||
describe('library: what goes along', () => {
|
|
||||||
it('lists a component after everything it uses, each once, itself last', () => {
|
|
||||||
const p = createProject({ examples: true })
|
|
||||||
const order = closure(lookup(p), 'ex-add4').map(d => d.id)
|
|
||||||
expect(order.at(-1)).toBe('ex-add4')
|
|
||||||
expect(new Set(order).size).toBe(order.length)
|
|
||||||
expect([...order].sort()).toEqual(['ex-add4', 'ex-and', 'ex-fa', 'ex-ha', 'ex-not', 'ex-or', 'ex-xor'])
|
|
||||||
const get = lookup(p)
|
|
||||||
for (const [i, id] of order.entries()) {
|
|
||||||
for (const n of get(id)!.nodes) if (n.kind === 'chip') expect(order.indexOf(n.chip!), `${id} uses ${n.chip}`).toBeLessThan(i)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
it('carries the connector types its ports use, without challenge marks', () => {
|
|
||||||
const p = adasProject()
|
|
||||||
p.connectors!.push({ id: 'k2', name: 'Unused', lines: [{ name: 'X' }] })
|
|
||||||
p.components.find(d => d.id === 'ex-xor')!.challenge = 'xor'
|
|
||||||
const b = libraryBundle(p, 'csend')
|
|
||||||
expect(b.root).toBe('csend')
|
|
||||||
expect(b.components.map(d => d.id)).toEqual(['ex-xor', 'csend'])
|
|
||||||
expect(b.connectors?.map(c => c.id)).toEqual(['k1'])
|
|
||||||
expect(b.components.some(d => d.challenge)).toBe(false)
|
|
||||||
// The project itself keeps its marks.
|
|
||||||
expect(p.components.find(d => d.id === 'ex-xor')!.challenge).toBe('xor')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keeps challenges and puzzle solutions private, at any depth', () => {
|
|
||||||
const p = createProject({ examples: true })
|
|
||||||
const not = startChallenge(p, CHALLENGES.find(c => c.id === 'not')!)
|
|
||||||
expect(publishProblem(p, not.id)).toMatch(/private/)
|
|
||||||
expect(publishProblem(p, 'ex-add4')).toBeNull()
|
|
||||||
// A solution anywhere inside stays private too, a challenge's or a puzzle's.
|
|
||||||
p.components.find(d => d.id === 'ex-xor')!.challenge = 'xor'
|
|
||||||
expect(publishProblem(p, 'ex-add4')).toMatch(/challenge "XOR"/)
|
|
||||||
p.components.find(d => d.id === 'ex-xor')!.challenge = 'pz:abc123'
|
|
||||||
expect(publishProblem(p, 'ex-add4')).toMatch(/puzzle "XOR"/)
|
|
||||||
p.components.push({ id: 'empty', name: 'Empty', symbol: 'box', nodes: [], wires: [] })
|
|
||||||
expect(publishProblem(p, 'empty')).toMatch(/nothing/)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('does not publish a solved challenge wrapped in a component of its own', () => {
|
|
||||||
const p = createProject({ examples: false, campaign: true })
|
|
||||||
const not = startChallenge(p, CHALLENGES.find(c => c.id === 'not')!)
|
|
||||||
not.nodes.push({ id: 'g', kind: 'nand', x: 8, y: 0 })
|
|
||||||
p.solved.push('not')
|
|
||||||
p.components.push({ id: 'wrap', name: 'Wrap', symbol: 'box', nodes: [{ id: 'c', kind: 'chip', chip: not.id, x: 0, y: 0 }], wires: [] })
|
|
||||||
expect(publishProblem(p, 'wrap')).toMatch(/challenge "NOT", which stays private/)
|
|
||||||
expect(publishProblem(p, not.id)).toMatch(/private/)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('library: checks on the server', () => {
|
|
||||||
it('keeps only what the component uses and counts it honestly', () => {
|
|
||||||
const p = adasProject()
|
|
||||||
const raw = { ...libraryBundle(p, 'csend'), components: p.components }
|
|
||||||
const b = cleanBundle(JSON.parse(JSON.stringify(raw)))
|
|
||||||
expect(b.components.map(d => d.id)).toEqual(closure(lookup(p), 'csend').map(d => d.id))
|
|
||||||
const meta = describeBundle(b)
|
|
||||||
expect(meta.transistors).toBe(nandCounts(p.components).get('csend')! * 4)
|
|
||||||
expect(meta).toMatchObject({ name: 'Sender', inputs: 2, outputs: 0, inNames: ['A', 'B'], outNames: [], uses: 1, connectors: 1 })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keeps the listing small whatever is sent', () => {
|
|
||||||
const p = createProject({ examples: true })
|
|
||||||
const b = JSON.parse(JSON.stringify(libraryBundle(p, 'ex-not')))
|
|
||||||
const root = b.components.find((d: ComponentDef) => d.id === 'ex-not')
|
|
||||||
root.group = 'g'.repeat(50_000)
|
|
||||||
root.description = 'd'.repeat(50_000)
|
|
||||||
root.nodes.find((n: { kind: string }) => n.kind === 'input').label = 'x'.repeat(500_000)
|
|
||||||
for (let i = 0; i < 200; i++) root.nodes.push({ id: `o${i}`, kind: 'output', x: 30, y: i, label: 'y'.repeat(1000) })
|
|
||||||
const clean = cleanBundle(b)
|
|
||||||
expect(clean.components.find(d => d.id === 'ex-not')!.group).toHaveLength(LIBRARY_LIMITS.group)
|
|
||||||
const meta = describeBundle(clean)
|
|
||||||
expect(meta).toMatchObject({ inputs: 1, outputs: 201 })
|
|
||||||
expect(meta.outNames).toHaveLength(LIBRARY_LIMITS.pinNames)
|
|
||||||
expect(meta.inNames[0]).toHaveLength(LIBRARY_LIMITS.pinName)
|
|
||||||
expect(JSON.stringify(meta).length).toBeLessThan(2000)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('drops corner points a wire could not be drawn with', () => {
|
|
||||||
const p = createProject({ examples: true })
|
|
||||||
const b = JSON.parse(JSON.stringify(libraryBundle(p, 'ex-ha')))
|
|
||||||
const ha = b.components.find((d: ComponentDef) => d.id === 'ex-ha')
|
|
||||||
const bent = ha.wires.filter((x: Wire) => x.pts)
|
|
||||||
expect(bent.length).toBeGreaterThan(1)
|
|
||||||
bent[0].pts = [null]
|
|
||||||
bent[1].pts = [[1, 'x']]
|
|
||||||
const clean = cleanBundle(b).components.find(d => d.id === 'ex-ha')!
|
|
||||||
expect(clean.wires.find(x => x.id === bent[0].id)!.pts).toBeUndefined()
|
|
||||||
expect(clean.wires.find(x => x.id === bent[1].id)!.pts).toBeUndefined()
|
|
||||||
// Corners that are fine stay, as in projects loaded from a file or link.
|
|
||||||
expect(clean.wires.filter(x => x.pts)).toHaveLength(bent.length - 2)
|
|
||||||
expect(toProject(JSON.parse(JSON.stringify(p))).components.find(d => d.id === 'ex-ha')!.wires).toEqual(p.components.find(d => d.id === 'ex-ha')!.wires)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('refuses missing parts, parts that contain themselves and broken nodes', () => {
|
|
||||||
const p = createProject({ examples: true })
|
|
||||||
const b = libraryBundle(p, 'ex-ha')
|
|
||||||
expect(() => cleanBundle({ ...b, components: b.components.filter(d => d.id !== 'ex-xor') })).toThrow(/Missing component/)
|
|
||||||
const loop = JSON.parse(JSON.stringify(b))
|
|
||||||
loop.components.find((d: ComponentDef) => d.id === 'ex-xor').nodes.push({ id: 'me', kind: 'chip', chip: 'ex-ha', x: 0, y: 9 })
|
|
||||||
expect(() => cleanBundle(loop)).toThrow(/contains itself/)
|
|
||||||
const broken = JSON.parse(JSON.stringify(b))
|
|
||||||
broken.components[0].nodes[0].x = 'left'
|
|
||||||
expect(() => cleanBundle(broken)).toThrow(/broken/)
|
|
||||||
expect(() => cleanBundle({ root: 'nope', components: b.components })).toThrow(/missing/)
|
|
||||||
expect(() => cleanBundle('hello')).toThrow()
|
|
||||||
})
|
|
||||||
|
|
||||||
/** Components l0 … l<depth>, each holding `n` of the one below; l0 is one NAND. */
|
|
||||||
function tower(depth: number, n: number) {
|
|
||||||
const components: ComponentDef[] = [{ id: 'l0', name: 'L0', symbol: 'box', nodes: [{ id: 'g', kind: 'nand', x: 0, y: 0 }], wires: [] }]
|
|
||||||
for (let i = 1; i <= depth; i++) {
|
|
||||||
const nodes = Array.from({ length: n }, (_, k) => ({ id: `c${k}`, kind: 'chip' as const, chip: `l${i - 1}`, x: 0, y: 4 * k }))
|
|
||||||
components.push({ id: `l${i}`, name: `L${i}`, symbol: 'box', nodes, wires: [] })
|
|
||||||
}
|
|
||||||
return { root: `l${depth}`, components }
|
|
||||||
}
|
|
||||||
|
|
||||||
it('refuses nesting deeper than the simulator goes, and parts too huge to run, without building them', () => {
|
|
||||||
expect(() => cleanBundle(tower(63, 1))).not.toThrow()
|
|
||||||
expect(() => cleanBundle(tower(64, 1))).toThrow(/Nesting deeper than 64/)
|
|
||||||
// 10^12 NANDs once opened up: refused at once.
|
|
||||||
const t = performance.now()
|
|
||||||
expect(() => cleanBundle(tower(12, 10))).toThrow(/Too large to run/)
|
|
||||||
expect(performance.now() - t).toBeLessThan(1000)
|
|
||||||
expect(describeBundle(cleanBundle(tower(6, 10))).transistors).toBe(4_000_000)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('library: adding an entry to a project', () => {
|
|
||||||
it('brings everything with new ids, wired to each other, computing the same', () => {
|
|
||||||
const ada = adasProject()
|
|
||||||
const bob = createProject({ examples: false })
|
|
||||||
const res = importBundle(bob, published(ada, 'csend'), origin)
|
|
||||||
expect(res.added).toBe(closure(lookup(ada), 'csend').length)
|
|
||||||
const root = bob.components.find(d => d.id === res.root)!
|
|
||||||
expect(root.name).toBe('Sender')
|
|
||||||
expect(root.id).not.toBe('csend')
|
|
||||||
// Every component it uses is here, under its new id.
|
|
||||||
const get = lookup(bob)
|
|
||||||
for (const d of closure(get, root.id)) for (const n of d.nodes) if (n.kind === 'chip') expect(get(n.chip!), n.chip).toBeTruthy()
|
|
||||||
expect(closure(get, root.id)).toHaveLength(res.added)
|
|
||||||
expect(nandCounts(bob.components).get(root.id)).toBe(nandCounts(ada.components).get('csend'))
|
|
||||||
const xor = closure(get, root.id).find(d => d.name === 'XOR')!
|
|
||||||
expect(rows(bob, xor.id)).toEqual(rows(ada, 'ex-xor'))
|
|
||||||
// The connector type came along and the port uses it.
|
|
||||||
expect(bob.connectors).toEqual([{ id: 'k1', name: 'Link', color: 'blue', lines: [{ name: 'D0' }, { name: 'D1' }] }])
|
|
||||||
expect(root.nodes.find(n => n.kind === 'portout')!.conn).toBe('k1')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('marks the entry, and what came along with it', () => {
|
|
||||||
const bob = createProject({ examples: false })
|
|
||||||
const res = importBundle(bob, published(createProject({ examples: true }), 'ex-ha'), origin)
|
|
||||||
const added = bob.components.slice(-res.added)
|
|
||||||
expect(added.find(d => d.id === res.root)!.from).toEqual(origin)
|
|
||||||
for (const d of added.filter(d => d.id !== res.root)) expect(d.from).toEqual({ ...origin, inside: true })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('makes a copy of an added component your own, without the mark', () => {
|
|
||||||
const bob = createProject({ examples: false })
|
|
||||||
const res = importBundle(bob, published(createProject({ examples: true }), 'ex-xor'), origin)
|
|
||||||
expect(duplicateComponent(bob, res.root)!.from).toBeUndefined()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('marks what comes in only by the entry it came with, never by marks the publisher sent', () => {
|
|
||||||
const ada = createProject({ examples: true })
|
|
||||||
ada.components.find(d => d.id === 'ex-xor')!.from = { id: 'Xor00001', version: 3, author: 'Cy' }
|
|
||||||
expect(libraryBundle(ada, 'ex-ha').components.some(d => d.from)).toBe(false)
|
|
||||||
// Eve sends a part claiming to be Cy's entry; the server drops the claim.
|
|
||||||
const forged = JSON.parse(JSON.stringify(libraryBundle(ada, 'ex-ha')))
|
|
||||||
forged.components[0].from = { id: 'Xor00001', version: 3, author: 'Cy' }
|
|
||||||
const b = cleanBundle(forged)
|
|
||||||
expect(b.components.some(d => d.from)).toBe(false)
|
|
||||||
// And adding never keeps a mark that came with the bundle.
|
|
||||||
forged.components[0].from = { id: 'Xor00001', version: 3, author: 'Cy' }
|
|
||||||
const bob = createProject({ examples: false })
|
|
||||||
importBundle(bob, forged, origin)
|
|
||||||
for (const d of bob.components.filter(d => d.from)) expect(d.from!.id).toBe(origin.id)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('uses what is here in the same form, and adds nothing for the same entry twice', () => {
|
|
||||||
const ada = createProject({ examples: true })
|
|
||||||
const bob = createProject({ examples: true })
|
|
||||||
const before = bob.components.length
|
|
||||||
// Bob has the examples: the half adder and all it uses are his already.
|
|
||||||
const first = importBundle(bob, published(ada, 'ex-ha'), origin)
|
|
||||||
expect(first).toEqual({ root: 'ex-ha', added: 0 })
|
|
||||||
expect(bob.components).toHaveLength(before)
|
|
||||||
|
|
||||||
const carl = createProject({ examples: false })
|
|
||||||
const a = importBundle(carl, published(ada, 'ex-fa'), origin)
|
|
||||||
const again = importBundle(carl, published(ada, 'ex-fa'), { ...origin, version: 2 })
|
|
||||||
expect(again).toEqual({ root: a.root, added: 0 })
|
|
||||||
expect(carl.components.find(d => d.id === a.root)!.from).toEqual({ ...origin, version: 2 })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('gives a name that is taken by something else a number', () => {
|
|
||||||
const ada = createProject({ examples: true })
|
|
||||||
const bob = createProject({ examples: true })
|
|
||||||
// Bob's NOT differs from Ada's: hers comes in as "NOT 2", with what uses it pointing at hers.
|
|
||||||
ada.components.find(d => d.id === 'ex-not')!.nodes[0]!.x += 1
|
|
||||||
const res = importBundle(bob, published(ada, 'ex-and'), origin)
|
|
||||||
expect(res.added).toBe(2)
|
|
||||||
const and = bob.components.find(d => d.id === res.root)!
|
|
||||||
expect(and.name).toBe('AND 2')
|
|
||||||
const not = bob.components.find(d => d.id === and.nodes.find(n => n.kind === 'chip')!.chip)!
|
|
||||||
expect(not.name).toBe('NOT 2')
|
|
||||||
expect(not.id).not.toBe('ex-not')
|
|
||||||
expect(rows(bob, and.id)).toEqual(rows(ada, 'ex-and'))
|
|
||||||
})
|
|
||||||
|
|
||||||
it('joins connector types with the same lines, and keeps different ones apart', () => {
|
|
||||||
const ada = adasProject()
|
|
||||||
const same = createProject({ examples: true })
|
|
||||||
same.connectors = [{ id: 'mine', name: 'link', lines: [{ name: 'D0' }, { name: 'D1' }] }]
|
|
||||||
const a = importBundle(same, published(ada, 'csend'), origin)
|
|
||||||
expect(same.connectors).toHaveLength(1)
|
|
||||||
expect(same.components.find(d => d.id === a.root)!.nodes.find(n => n.kind === 'portout')!.conn).toBe('mine')
|
|
||||||
|
|
||||||
const other = createProject({ examples: true })
|
|
||||||
other.connectors = [{ id: 'k1', name: 'Link', lines: [{ name: 'TX' }, { name: 'RX', back: true }] }]
|
|
||||||
const b = importBundle(other, published(ada, 'csend'), origin)
|
|
||||||
expect(other.connectors).toHaveLength(2)
|
|
||||||
const added = other.connectors[1]!
|
|
||||||
expect(added.id).not.toBe('k1')
|
|
||||||
expect(added.name).toBe('Link 2')
|
|
||||||
expect(other.components.find(d => d.id === b.root)!.nodes.find(n => n.kind === 'portout')!.conn).toBe(added.id)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('updates a component in place to a newer version, where it is used too', () => {
|
|
||||||
const ada = createProject({ examples: true })
|
|
||||||
const bob = createProject({ examples: false })
|
|
||||||
const v1 = importBundle(bob, published(ada, 'ex-and'), origin)
|
|
||||||
const main = bob.components.find(d => d.id === 'main')!
|
|
||||||
main.nodes.push({ id: 'u', kind: 'chip', chip: v1.root, x: 10, y: 10 })
|
|
||||||
// Version 2: AND became OR (same pins), now built from Ada's OR.
|
|
||||||
const and = ada.components.find(d => d.id === 'ex-and')!
|
|
||||||
const or = ada.components.find(d => d.id === 'ex-or')!
|
|
||||||
and.nodes = structuredClone(or.nodes)
|
|
||||||
and.wires = structuredClone(or.wires)
|
|
||||||
const v2 = importBundle(bob, published(ada, 'ex-and'), { ...origin, version: 2 }, v1.root)
|
|
||||||
expect(v2.root).toBe(v1.root)
|
|
||||||
const updated = bob.components.find(d => d.id === v1.root)!
|
|
||||||
expect(updated.name).toBe('AND')
|
|
||||||
expect(updated.from).toEqual({ ...origin, version: 2 })
|
|
||||||
expect(rows(bob, v1.root)).toEqual(rows(ada, 'ex-or'))
|
|
||||||
expect(main.nodes.find(n => n.id === 'u')!.chip).toBe(v1.root)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('clears away what came along with the old version, and the new parts take its names', () => {
|
|
||||||
const ada = createProject({ examples: true })
|
|
||||||
const bob = createProject({ examples: false })
|
|
||||||
const v1 = importBundle(bob, published(ada, 'ex-ha'), origin)
|
|
||||||
const oldXor = bob.components.find(d => d.name === 'XOR')!
|
|
||||||
// Version 2: Ada drew her XOR differently.
|
|
||||||
ada.components.find(d => d.id === 'ex-xor')!.nodes[0]!.y += 1
|
|
||||||
importBundle(bob, published(ada, 'ex-ha'), { ...origin, version: 2 }, v1.root)
|
|
||||||
expect(bob.components.map(d => d.name).sort()).toEqual(['AND', 'Half Adder', 'Main', 'NOT', 'XOR'])
|
|
||||||
expect(bob.components.some(d => d.id === oldXor.id)).toBe(false)
|
|
||||||
expect(rows(bob, v1.root)).toEqual(rows(ada, 'ex-ha'))
|
|
||||||
// Updated again: still no "XOR 2".
|
|
||||||
ada.components.find(d => d.id === 'ex-xor')!.nodes[0]!.y += 1
|
|
||||||
importBundle(bob, published(ada, 'ex-ha'), { ...origin, version: 3 }, v1.root)
|
|
||||||
expect(bob.components.map(d => d.name).sort()).toEqual(['AND', 'Half Adder', 'Main', 'NOT', 'XOR'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keeps an old part that is used elsewhere', () => {
|
|
||||||
const ada = createProject({ examples: true })
|
|
||||||
const bob = createProject({ examples: false })
|
|
||||||
const v1 = importBundle(bob, published(ada, 'ex-ha'), origin)
|
|
||||||
const oldXor = bob.components.find(d => d.name === 'XOR')!
|
|
||||||
bob.components.find(d => d.id === 'main')!.nodes.push({ id: 'x', kind: 'chip', chip: oldXor.id, x: 20, y: 0 })
|
|
||||||
ada.components.find(d => d.id === 'ex-xor')!.nodes[0]!.y += 1
|
|
||||||
importBundle(bob, published(ada, 'ex-ha'), { ...origin, version: 2 }, v1.root)
|
|
||||||
expect(bob.components.find(d => d.id === oldXor.id)!.name).toBe('XOR')
|
|
||||||
expect(bob.components.some(d => d.name === 'XOR 2')).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('never reuses another entry’s component, so updating one entry leaves the others as they were', () => {
|
|
||||||
const ada = createProject({ examples: true })
|
|
||||||
const bob = createProject({ examples: false })
|
|
||||||
// Bob has Ada's XOR entry; Carl's half adder holds an XOR exactly like it.
|
|
||||||
const xor = importBundle(bob, published(ada, 'ex-xor'), origin)
|
|
||||||
const carl = importBundle(bob, published(ada, 'ex-ha'), { id: 'Carl0001', version: 1, author: 'Carl' })
|
|
||||||
const carlsXor = closure(lookup(bob), carl.root).find(d => d.name.startsWith('XOR'))!
|
|
||||||
expect(carlsXor.id).not.toBe(xor.root)
|
|
||||||
expect(carlsXor.from).toEqual({ id: 'Carl0001', version: 1, author: 'Carl', inside: true })
|
|
||||||
// Ada's XOR, version 2, is an OR now: Carl's half adder still adds.
|
|
||||||
const v2 = createProject({ examples: true })
|
|
||||||
const x = v2.components.find(d => d.id === 'ex-xor')!
|
|
||||||
const or = v2.components.find(d => d.id === 'ex-or')!
|
|
||||||
Object.assign(x, { nodes: structuredClone(or.nodes), wires: structuredClone(or.wires) })
|
|
||||||
importBundle(bob, published(v2, 'ex-xor'), { ...origin, version: 2 }, xor.root)
|
|
||||||
expect(rows(bob, xor.root)).toEqual(rows(ada, 'ex-or'))
|
|
||||||
expect(rows(bob, carl.root)).toEqual(rows(ada, 'ex-ha'))
|
|
||||||
})
|
|
||||||
|
|
||||||
it('never reuses the component being updated inside its own new version', () => {
|
|
||||||
const bob = createProject({ examples: false })
|
|
||||||
const ada = createProject({ examples: true })
|
|
||||||
// The entry was Ada's NOT; its next version is her AND, which uses a NOT exactly like the one Bob has.
|
|
||||||
const res = importBundle(bob, published(ada, 'ex-not'), origin)
|
|
||||||
const v2 = importBundle(bob, published(ada, 'ex-and'), { ...origin, version: 2 }, res.root)
|
|
||||||
const get = lookup(bob)
|
|
||||||
expect(closure(get, v2.root).filter(d => d.id === v2.root)).toHaveLength(1)
|
|
||||||
expect(get(v2.root)!.nodes.some(n => n.chip === v2.root)).toBe(false)
|
|
||||||
expect(rows(bob, v2.root)).toEqual(rows(ada, 'ex-and'))
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('library: campaign and old projects', () => {
|
|
||||||
it('adds nothing to a campaign, however far it is', () => {
|
|
||||||
const campaign = createProject({ examples: false, campaign: true })
|
|
||||||
expect(importProblem(campaign)).toMatch(/campaign/)
|
|
||||||
campaign.solved.push(...CHALLENGES.map(c => c.id))
|
|
||||||
expect(importProblem(campaign)).toMatch(/campaign/)
|
|
||||||
expect(importProblem(createProject({ examples: true }))).toBeNull()
|
|
||||||
expect(importProblem({ ...createProject({ examples: false }), mode: 'challenges' })).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('loads projects without library marks as before, and drops broken marks', () => {
|
|
||||||
const p = createProject({ examples: true })
|
|
||||||
const plain = toProject(JSON.parse(JSON.stringify(p)))
|
|
||||||
expect(plain.components.some(d => 'from' in d)).toBe(false)
|
|
||||||
expect(plain).toEqual(JSON.parse(JSON.stringify(p)))
|
|
||||||
const marked = JSON.parse(JSON.stringify(p))
|
|
||||||
marked.components[1].from = { id: 'Lib12345', version: 2, author: 'Ada', inside: true, extra: 1 }
|
|
||||||
marked.components[2].from = { id: '../etc', version: 1, author: 'x' }
|
|
||||||
marked.components[3].from = { id: 'Lib12345', version: 0 }
|
|
||||||
const q = parseProject(JSON.stringify(marked))
|
|
||||||
expect(q.components[1]!.from).toEqual({ id: 'Lib12345', version: 2, author: 'Ada', inside: true })
|
|
||||||
expect(q.components[2]!.from).toBeUndefined()
|
|
||||||
expect(q.components[3]!.from).toBeUndefined()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('library keys in the browser', () => {
|
|
||||||
it('keeps what was published from here, and reads anything broken as nothing', () => {
|
|
||||||
const map = new Map<string, string>()
|
|
||||||
globalThis.localStorage = { getItem: k => map.get(k) ?? null, setItem: (k, v) => void map.set(k, v), removeItem: k => void map.delete(k) } as Storage
|
|
||||||
expect(libraryKeys()).toEqual({})
|
|
||||||
setLibraryKey('Lib12345', { key: 'secret', project: 'p1', def: 'c1' })
|
|
||||||
setLibraryKey('Lib67890', { key: 'other', project: 'p1', def: 'c2' })
|
|
||||||
setLibraryKey('Lib67890', null)
|
|
||||||
expect(libraryKeys()).toEqual({ Lib12345: { key: 'secret', project: 'p1', def: 'c1' } })
|
|
||||||
map.set('logigate:library-keys', '[1, 2]')
|
|
||||||
expect(libraryKeys()).toEqual({})
|
|
||||||
map.set('logigate:library-keys', 'not json')
|
|
||||||
expect(libraryKeys()).toEqual({})
|
|
||||||
})
|
|
||||||
|
|
||||||
it('owns an entry only where it was published from, whatever a component’s mark says', () => {
|
|
||||||
const keys = { Lib12345: { key: 'secret', project: 'p1', def: 'c1' } }
|
|
||||||
expect(ownedEntry(keys, 'p1', 'c1')).toBe('Lib12345')
|
|
||||||
// The same component in another project, or another component here, is not it.
|
|
||||||
expect(ownedEntry(keys, 'p2', 'c1')).toBeUndefined()
|
|
||||||
expect(ownedEntry(keys, 'p1', 'c2')).toBeUndefined()
|
|
||||||
// A part that came in claiming to be Ada's entry stays someone else's: adding
|
|
||||||
// Eve's entry marks it as Eve's, and only the key record counts anyway.
|
|
||||||
const ada = createProject({ examples: true })
|
|
||||||
const forged = JSON.parse(JSON.stringify(libraryBundle(ada, 'ex-and')))
|
|
||||||
forged.components[0].from = { id: 'Lib12345', version: 1, author: 'Ada' }
|
|
||||||
const p = createProject({ examples: false })
|
|
||||||
const res = importBundle(p, cleanBundle(forged), { id: 'Eve00001', version: 1, author: 'Eve' })
|
|
||||||
for (const d of closure(lookup(p), res.root)) {
|
|
||||||
expect(d.from!.id).toBe('Eve00001')
|
|
||||||
expect(ownedEntry(keys, 'p1', d.id)).toBeUndefined()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('library listing', () => {
|
|
||||||
const item = (id: string, name: string, updated: number, player: string, description = ''): LibraryItem => ({
|
|
||||||
id,
|
|
||||||
name,
|
|
||||||
description,
|
|
||||||
group: '',
|
|
||||||
version: 1,
|
|
||||||
created: 0,
|
|
||||||
updated,
|
|
||||||
transistors: 8,
|
|
||||||
inputs: 1,
|
|
||||||
outputs: 1,
|
|
||||||
inNames: ['A'],
|
|
||||||
outNames: ['Q'],
|
|
||||||
uses: 0,
|
|
||||||
connectors: 0,
|
|
||||||
player,
|
|
||||||
})
|
|
||||||
const names = { 'player-ada-0001': 'Ada' }
|
|
||||||
const list = [item('a1', 'Adder 8', 10, 'player-ada-0001', 'ripple carry'), item('a2', 'ALU', 30, 'player-bob-0002'), item('a3', 'Shifter', 20, 'player-ada-0001')].map(m =>
|
|
||||||
publicMeta(m, names),
|
|
||||||
)
|
|
||||||
|
|
||||||
it('shows authors by their name, never their player id', () => {
|
|
||||||
expect(list[0]!.author).toBe('Ada')
|
|
||||||
expect(list[1]!.author).toBe('')
|
|
||||||
expect(JSON.stringify(list)).not.toContain('player-')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('finds every word in name, description or author, newest first', () => {
|
|
||||||
expect(searchLibrary(list, '').map((m: LibraryMeta) => m.id)).toEqual(['a2', 'a3', 'a1'])
|
|
||||||
expect(searchLibrary(list, 'ada').map(m => m.id)).toEqual(['a3', 'a1'])
|
|
||||||
expect(searchLibrary(list, 'Carry ADA').map(m => m.id)).toEqual(['a1'])
|
|
||||||
expect(searchLibrary(list, 'nothing')).toEqual([])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,198 +0,0 @@
|
||||||
// Going into components and out again with the browser's back and forward
|
|
||||||
// (the mouse's side buttons): every step is a browser history entry. Runs
|
|
||||||
// the real composable in a stand-in browser with its own history.
|
|
||||||
|
|
||||||
import * as vue from 'vue'
|
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
||||||
import { createProject } from '../app/lib/logic/ops'
|
|
||||||
import { saveProject, setCurrentId, type ProjectMeta } from '../app/lib/logic/storage'
|
|
||||||
import type { Project } from '../app/lib/logic/types'
|
|
||||||
|
|
||||||
/** Top holds Mid, Mid holds Leaf. */
|
|
||||||
function nested(name = 'Nested'): Project {
|
|
||||||
const p = createProject({ examples: false })
|
|
||||||
p.name = name
|
|
||||||
p.components = [
|
|
||||||
{ id: 'top', name: 'Top', symbol: 'box', nodes: [{ id: 'm', kind: 'chip', chip: 'mid', x: 0, y: 0 }], wires: [] },
|
|
||||||
{ id: 'mid', name: 'Mid', symbol: 'box', nodes: [{ id: 'l', kind: 'chip', chip: 'leaf', x: 0, y: 0 }], wires: [] },
|
|
||||||
{ id: 'leaf', name: 'Leaf', symbol: 'box', nodes: [{ id: 'g', kind: 'nand', x: 0, y: 0 }], wires: [] },
|
|
||||||
]
|
|
||||||
p.openId = 'top'
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
function stored(p: Project, id: string): ProjectMeta {
|
|
||||||
const m: ProjectMeta = { id, name: p.name, updated: Date.now() }
|
|
||||||
saveProject(m, p)
|
|
||||||
return m
|
|
||||||
}
|
|
||||||
|
|
||||||
/** This browser: its storage and its tab's history, kept across reloads. */
|
|
||||||
let store: Map<string, string>
|
|
||||||
let entries: unknown[]
|
|
||||||
let at: number
|
|
||||||
|
|
||||||
/** A tab with the editor open, on the history entry `at`. */
|
|
||||||
async function openTab() {
|
|
||||||
const events = new Map<string, ((e: unknown) => void)[]>()
|
|
||||||
const on = (type: string, f: (e: unknown) => void) => events.set(type, [...(events.get(type) ?? []), f])
|
|
||||||
const fire = (type: string, e: unknown = {}) => events.get(type)?.forEach(f => f(e))
|
|
||||||
const history = {
|
|
||||||
get state() {
|
|
||||||
return entries[at] ?? null
|
|
||||||
},
|
|
||||||
pushState(s: unknown) {
|
|
||||||
entries.splice(at + 1)
|
|
||||||
entries.push(structuredClone(s))
|
|
||||||
at++
|
|
||||||
},
|
|
||||||
replaceState(s: unknown) {
|
|
||||||
entries[at] = structuredClone(s)
|
|
||||||
},
|
|
||||||
back() {
|
|
||||||
if (at === 0) return
|
|
||||||
at--
|
|
||||||
fire('popstate', { state: history.state })
|
|
||||||
},
|
|
||||||
forward() {
|
|
||||||
if (at === entries.length - 1) return
|
|
||||||
at++
|
|
||||||
fire('popstate', { state: history.state })
|
|
||||||
},
|
|
||||||
}
|
|
||||||
vi.stubGlobal('window', { addEventListener: on })
|
|
||||||
vi.stubGlobal('document', { addEventListener: on, visibilityState: 'visible' })
|
|
||||||
vi.stubGlobal('location', { pathname: '/', origin: 'http://localhost' })
|
|
||||||
vi.stubGlobal('history', history)
|
|
||||||
for (const k of ['ref', 'computed', 'reactive', 'shallowRef', 'toRaw', 'watch'] as const) vi.stubGlobal(k, vue[k])
|
|
||||||
vi.resetModules()
|
|
||||||
const { useEditor } = await import('../app/composables/useEditor')
|
|
||||||
const ed = useEditor()
|
|
||||||
ed.enterGame()
|
|
||||||
return {
|
|
||||||
ed,
|
|
||||||
history,
|
|
||||||
/** The open circuit and the crumbs to it. */
|
|
||||||
where: () => [...ed.nav.value, ed.def.value.id].join(' > '),
|
|
||||||
/** A press of the mouse's back button: whether the page stopped the browser going back. */
|
|
||||||
mouseBack() {
|
|
||||||
const e = { button: 3, defaultPrevented: false, preventDefault: () => (e.defaultPrevented = true) }
|
|
||||||
fire('mouseup', e)
|
|
||||||
if (!e.defaultPrevented) history.back()
|
|
||||||
return e.defaultPrevented
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
store = new Map()
|
|
||||||
entries = [null]
|
|
||||||
at = 0
|
|
||||||
vi.stubGlobal('localStorage', {
|
|
||||||
getItem: (k: string) => store.get(k) ?? null,
|
|
||||||
setItem: (k: string, v: string) => void store.set(k, String(v)),
|
|
||||||
removeItem: (k: string) => void store.delete(k),
|
|
||||||
})
|
|
||||||
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'] })
|
|
||||||
stored(nested(), 'p1')
|
|
||||||
setCurrentId('p1')
|
|
||||||
})
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
vi.useRealTimers()
|
|
||||||
vi.unstubAllGlobals()
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('the browser history walking the circuits', () => {
|
|
||||||
it('goes back and forward through the components as they were entered, crumbs and all', async () => {
|
|
||||||
const tab = await openTab()
|
|
||||||
tab.ed.open('mid')
|
|
||||||
tab.ed.open('leaf')
|
|
||||||
expect(tab.where()).toBe('top > mid > leaf')
|
|
||||||
tab.history.back()
|
|
||||||
expect(tab.where()).toBe('top > mid')
|
|
||||||
tab.history.back()
|
|
||||||
expect(tab.where()).toBe('top')
|
|
||||||
tab.history.forward()
|
|
||||||
expect(tab.where()).toBe('top > mid')
|
|
||||||
tab.history.forward()
|
|
||||||
expect(tab.where()).toBe('top > mid > leaf')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('takes Main and the crumbs as steps too, so back returns to where you were', async () => {
|
|
||||||
const tab = await openTab()
|
|
||||||
tab.ed.open('mid')
|
|
||||||
tab.ed.open('leaf')
|
|
||||||
tab.ed.goMain()
|
|
||||||
expect(tab.where()).toBe('top')
|
|
||||||
tab.history.back()
|
|
||||||
expect(tab.where()).toBe('top > mid > leaf')
|
|
||||||
tab.ed.goTo(1)
|
|
||||||
expect(tab.where()).toBe('top > mid')
|
|
||||||
tab.history.back()
|
|
||||||
expect(tab.where()).toBe('top > mid > leaf')
|
|
||||||
// Clicking Main while there writes no step.
|
|
||||||
tab.ed.goMain()
|
|
||||||
const steps = entries.length
|
|
||||||
tab.ed.goMain()
|
|
||||||
expect(entries.length).toBe(steps)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('forgets the steps ahead when you go somewhere new, like a browser', async () => {
|
|
||||||
const tab = await openTab()
|
|
||||||
tab.ed.open('mid')
|
|
||||||
tab.ed.open('leaf')
|
|
||||||
tab.history.back()
|
|
||||||
tab.history.back()
|
|
||||||
tab.ed.open('leaf')
|
|
||||||
tab.history.forward()
|
|
||||||
expect(tab.where()).toBe('top > leaf')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('opens the circuit of the entry after a reload, and after going back to an entry from before one', async () => {
|
|
||||||
let tab = await openTab()
|
|
||||||
tab.ed.open('mid')
|
|
||||||
tab.ed.open('leaf')
|
|
||||||
tab = await openTab()
|
|
||||||
expect(tab.where()).toBe('top > mid > leaf')
|
|
||||||
// Back from here loads the page anew on the entry before (the saved project has Leaf open).
|
|
||||||
at--
|
|
||||||
tab = await openTab()
|
|
||||||
expect(tab.where()).toBe('top > mid')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('stops the mouse back button on the first entry instead of leaving the editor', async () => {
|
|
||||||
const tab = await openTab()
|
|
||||||
tab.ed.open('mid')
|
|
||||||
expect(tab.mouseBack()).toBe(false)
|
|
||||||
expect(tab.where()).toBe('top')
|
|
||||||
expect(tab.mouseBack()).toBe(true)
|
|
||||||
expect(tab.where()).toBe('top')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('takes another project as a step: back opens the one before at the circuit it had open', async () => {
|
|
||||||
stored(nested('Other'), 'p2')
|
|
||||||
const tab = await openTab()
|
|
||||||
tab.ed.open('mid')
|
|
||||||
tab.ed.switchProject('p2')
|
|
||||||
expect(tab.ed.meta.value.id).toBe('p2')
|
|
||||||
tab.ed.open('leaf')
|
|
||||||
tab.history.back()
|
|
||||||
expect([tab.ed.meta.value.id, tab.where()]).toEqual(['p2', 'top'])
|
|
||||||
tab.history.back()
|
|
||||||
expect([tab.ed.meta.value.id, tab.where()]).toEqual(['p1', 'top > mid'])
|
|
||||||
tab.history.forward()
|
|
||||||
tab.history.forward()
|
|
||||||
expect([tab.ed.meta.value.id, tab.where()]).toEqual(['p2', 'top > leaf'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('passes over circuits that were deleted since', async () => {
|
|
||||||
const tab = await openTab()
|
|
||||||
tab.ed.open('mid')
|
|
||||||
tab.ed.open('leaf')
|
|
||||||
tab.ed.goMain()
|
|
||||||
tab.ed.project.value.components = tab.ed.project.value.components.filter(d => d.id !== 'leaf')
|
|
||||||
tab.history.back()
|
|
||||||
expect(tab.where()).toBe('top')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,61 +0,0 @@
|
||||||
import { describe, expect, it } from 'vitest'
|
|
||||||
import { circuitsNamed, foldCrumbs, wayTo } from '../app/lib/nav'
|
|
||||||
|
|
||||||
describe('the way back in the top bar', () => {
|
|
||||||
const path = ['Adder 4', 'Full Adder', 'Half Adder', 'XOR']
|
|
||||||
|
|
||||||
it('shows a short way whole', () => {
|
|
||||||
expect(foldCrumbs(path.slice(0, 2), 3)).toEqual({ folded: [], shown: ['Adder 4', 'Full Adder'] })
|
|
||||||
expect(foldCrumbs([], 2)).toEqual({ folded: [], shown: [] })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('folds the names before the last ones into the menu, in order', () => {
|
|
||||||
expect(foldCrumbs(path, 2)).toEqual({ folded: ['Adder 4', 'Full Adder'], shown: ['Half Adder', 'XOR'] })
|
|
||||||
expect(foldCrumbs(path, 3).folded).toEqual(['Adder 4'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('always keeps the circuit you are in', () => {
|
|
||||||
expect(foldCrumbs(path, 1)).toEqual({ folded: ['Adder 4', 'Full Adder', 'Half Adder'], shown: ['XOR'] })
|
|
||||||
expect(foldCrumbs(path, 0).shown).toEqual(['XOR'])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('getting to a circuit from the search box', () => {
|
|
||||||
it('starts anew at Main', () => {
|
|
||||||
expect(wayTo(['main', 'adder'], 'main', 'main')).toBe('main')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('goes back to a circuit on the way here', () => {
|
|
||||||
// Main → Adder 4 → Full Adder, now in Half Adder: Adder 4 is step 1 of the way.
|
|
||||||
expect(wayTo(['main', 'adder', 'full'], 'main', 'adder')).toBe(1)
|
|
||||||
expect(wayTo(['main', 'adder', 'full'], 'main', 'full')).toBe(2)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('opens any other one step further in', () => {
|
|
||||||
expect(wayTo(['main'], 'main', 'xor')).toBe('open')
|
|
||||||
expect(wayTo([], 'main', 'xor')).toBe('open')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('circuits found by name', () => {
|
|
||||||
const defs = [{ name: 'Main' }, { name: 'Half Adder' }, { name: 'Adder 4' }, { name: 'Full Adder' }, { name: 'XOR' }, { name: 'D Flip-Flop' }]
|
|
||||||
const names = (q: string, limit?: number) => circuitsNamed(defs, q, limit).map(d => d.name)
|
|
||||||
|
|
||||||
it('finds nothing before something is typed', () => {
|
|
||||||
expect(names('')).toEqual([])
|
|
||||||
expect(names(' ')).toEqual([])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('puts the best match first: the start of the name, then a word in it', () => {
|
|
||||||
expect(names('adder')).toEqual(['Adder 4', 'Half Adder', 'Full Adder'])
|
|
||||||
expect(names('XOR')).toEqual(['XOR'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('finds a name by its letters in order', () => {
|
|
||||||
expect(names('dff')).toEqual(['D Flip-Flop'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('lists at most the limit', () => {
|
|
||||||
expect(names('a', 2)).toHaveLength(2)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'
|
||||||
import { compile } from '../app/lib/logic/compile'
|
import { compile } from '../app/lib/logic/compile'
|
||||||
import { chipPins, panelOffsets } from '../app/lib/logic/geometry'
|
import { chipPins, panelOffsets } from '../app/lib/logic/geometry'
|
||||||
import { createProject, lookup } from '../app/lib/logic/ops'
|
import { createProject, lookup } from '../app/lib/logic/ops'
|
||||||
import { attachPanel, combineIntoPanel, insertPanelRow, mergePanels, movePanelRow } from '../app/lib/logic/panels'
|
import { attachPanel, combineIntoPanel, mergePanels } from '../app/lib/logic/panels'
|
||||||
import { Simulator } from '../app/lib/logic/sim'
|
import { Simulator } from '../app/lib/logic/sim'
|
||||||
import type { ComponentDef } from '../app/lib/logic/types'
|
import type { ComponentDef } from '../app/lib/logic/types'
|
||||||
|
|
||||||
|
|
@ -29,8 +29,8 @@ describe('merging input panels', () => {
|
||||||
expect(res.panel.attach).toBeUndefined()
|
expect(res.panel.attach).toBeUndefined()
|
||||||
const rows = res.panel.rows!
|
const rows = res.panel.rows!
|
||||||
expect(rows.map(r => r.label)).toEqual(['A0', 'B0', 'B1'])
|
expect(rows.map(r => r.label)).toEqual(['A0', 'B0', 'B1'])
|
||||||
// Packed: B1 was two rows under B0, now right below it.
|
// Spacing kept: B1 was two rows under B0.
|
||||||
expect(panelOffsets(rows)).toEqual([0, 1, 2])
|
expect(panelOffsets(rows)).toEqual([0, 1, 3])
|
||||||
// The wire from B1 now leaves the merged panel; the clashing row id got a new one.
|
// The wire from B1 now leaves the merged panel; the clashing row id got a new one.
|
||||||
const w2 = def.wires.find(w => w.id === 'w2')!
|
const w2 = def.wires.find(w => w.id === 'w2')!
|
||||||
expect(w2.from.node).toBe('p1')
|
expect(w2.from.node).toBe('p1')
|
||||||
|
|
@ -159,8 +159,8 @@ describe('combining parts into a panel', () => {
|
||||||
['B', 'switch', false, ''],
|
['B', 'switch', false, ''],
|
||||||
['GO', 'button', false, ''],
|
['GO', 'button', false, ''],
|
||||||
])
|
])
|
||||||
// Packed without gaps, though A and B were three rows apart.
|
// Spread-out parts keep their distance; B and GO were one row apart.
|
||||||
expect(panelOffsets(panel.rows!)).toEqual([0, 1, 2])
|
expect(panelOffsets(panel.rows!)).toEqual([0, 3, 4])
|
||||||
expect(def.wires[0]!.from).toEqual({ node: panel.id, pin: 'a' })
|
expect(def.wires[0]!.from).toEqual({ node: panel.id, pin: 'a' })
|
||||||
expect(res.renamed.get("a")).toBe(`${panel.id}:a`)
|
expect(res.renamed.get("a")).toBe(`${panel.id}:a`)
|
||||||
expect(def.nodes.some(n => ['a', 'b', 'go'].includes(n.id))).toBe(false)
|
expect(def.nodes.some(n => ['a', 'b', 'go'].includes(n.id))).toBe(false)
|
||||||
|
|
@ -190,44 +190,3 @@ describe('combining parts into a panel', () => {
|
||||||
expect(combineIntoPanel(def, ['s'], lookup(p))).toBeNull()
|
expect(combineIntoPanel(def, ['s'], lookup(p))).toBeNull()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('editing the rows of a free panel', () => {
|
|
||||||
const panel = () => ({
|
|
||||||
id: 'p',
|
|
||||||
kind: 'panel' as const,
|
|
||||||
x: 0,
|
|
||||||
y: 0,
|
|
||||||
rows: [
|
|
||||||
{ id: 'a', type: 'switch' as const },
|
|
||||||
{ id: 'b', type: 'button' as const, dy: 3 },
|
|
||||||
{ id: 'c', type: 'button' as const },
|
|
||||||
],
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a row added above another takes its place; the rest move down, gaps kept', () => {
|
|
||||||
const p = panel()
|
|
||||||
expect(panelOffsets(p.rows)).toEqual([0, 3, 4])
|
|
||||||
const r = insertPanelRow(p, 1)
|
|
||||||
expect(p.rows.map(x => x.id)).toEqual(['a', r.id, 'b', 'c'])
|
|
||||||
expect(panelOffsets(p.rows)).toEqual([0, 3, 4, 5])
|
|
||||||
expect(r.type).toBe('button')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('rows added above the first and below the last', () => {
|
|
||||||
const p = panel()
|
|
||||||
const top = insertPanelRow(p, 0)
|
|
||||||
expect(panelOffsets(p.rows)).toEqual([0, 1, 4, 5])
|
|
||||||
expect(top.type).toBe('switch')
|
|
||||||
const end = insertPanelRow(p, 99)
|
|
||||||
expect(p.rows.at(-1)!.id).toBe(end.id)
|
|
||||||
expect(panelOffsets(p.rows)).toEqual([0, 1, 4, 5, 6])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a dragged row trades places: the places and gaps stay', () => {
|
|
||||||
const p = panel()
|
|
||||||
expect(movePanelRow(p, 2, 0)).toBe(true)
|
|
||||||
expect(p.rows.map(x => x.id)).toEqual(['c', 'a', 'b'])
|
|
||||||
expect(panelOffsets(p.rows)).toEqual([0, 3, 4])
|
|
||||||
expect(movePanelRow(p, 1, 1)).toBe(false)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
|
||||||
|
|
@ -11,13 +11,9 @@ it('routes 400 crowded wires fast enough to redraw while dragging', () => {
|
||||||
inputs.push({ id: `w${i}`, net: `n${i % 150}`, a: [col * 3, row * 3], b: [col * 3 + 8 + (i % 5), row * 3 + ((i * 7) % 11) - 5] })
|
inputs.push({ id: `w${i}`, net: `n${i % 150}`, a: [col * 3, row * 3], b: [col * 3 + 8 + (i % 5), row * 3 + ((i * 7) % 11) - 5] })
|
||||||
if (i % 4 === 0) bodies.push({ x: col * 3 + 4, y: row * 3 - 1, w: 2, h: 2 })
|
if (i % 4 === 0) bodies.push({ x: col * 3 + 4, y: row * 3 - 1, w: 2, h: 2 })
|
||||||
}
|
}
|
||||||
// The best of three: other tests running at the same time can slow one run down.
|
|
||||||
let ms = Infinity
|
|
||||||
for (let k = 0; k < 3; k++) {
|
|
||||||
const t = performance.now()
|
const t = performance.now()
|
||||||
routeAll(inputs, bodies, [])
|
routeAll(inputs, bodies, [])
|
||||||
ms = Math.min(ms, performance.now() - t)
|
const ms = performance.now() - t
|
||||||
}
|
|
||||||
console.log(`routeAll(400 wires): ${ms.toFixed(1)} ms`)
|
console.log(`routeAll(400 wires): ${ms.toFixed(1)} ms`)
|
||||||
expect(ms).toBeLessThan(250)
|
expect(ms).toBeLessThan(250)
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
import { bundleWires, cableEnd, cableFromPins, cableIntoPins, cablePanel, nameTags, pinGroups, plugInto, plugLayout, syncCables } from '../app/lib/logic/cables'
|
import { bundleWires, cableFromPins, cableIntoPins, cablePanel, nameTags, pinGroups, plugInto, plugLayout, syncCables } from '../app/lib/logic/cables'
|
||||||
import { dropLinks, dropPins } from '../app/lib/logic/fit'
|
import { dropLinks, dropPins } from '../app/lib/logic/fit'
|
||||||
import { compile, rowSource } from '../app/lib/logic/compile'
|
import { compile, rowSource } from '../app/lib/logic/compile'
|
||||||
import { chipPins, panelOffsets, pinPos, shapeOf } from '../app/lib/logic/geometry'
|
import { chipPins, panelOffsets, pinPos, shapeOf } from '../app/lib/logic/geometry'
|
||||||
|
|
@ -303,7 +303,7 @@ describe('a cable straight off a part', () => {
|
||||||
expect(outs.map(g => g.label)).toEqual(['S0–S1', 'all 4 (S0–Cout)'])
|
expect(outs.map(g => g.label)).toEqual(['S0–S1', 'all 4 (S0–Cout)'])
|
||||||
})
|
})
|
||||||
|
|
||||||
it('from outputs: only a plug on the pins; the cable pulled out of it gets a free split with their names, then dropped onto the next part', () => {
|
it('from outputs: a bundle plugged on the pins, a free split with their names, then dropped onto the next part', () => {
|
||||||
const { p, def, outs } = adder()
|
const { p, def, outs } = adder()
|
||||||
const get = lookup(p)
|
const get = lookup(p)
|
||||||
// Take the lamps away: the outputs are free.
|
// Take the lamps away: the outputs are free.
|
||||||
|
|
@ -312,33 +312,24 @@ describe('a cable straight off a part', () => {
|
||||||
if (!res.ok) throw new Error(res.error)
|
if (!res.ok) throw new Error(res.error)
|
||||||
expect(res.bundle.plug).toBe('add')
|
expect(res.bundle.plug).toBe('add')
|
||||||
expect(touches(p, def, res.bundle)).toBe(true)
|
expect(touches(p, def, res.bundle)).toBe(true)
|
||||||
// Just the plug: no split, no cable yet.
|
|
||||||
expect(def.nodes.filter(n => n.kind === 'split')).toHaveLength(0)
|
|
||||||
expect(def.wires.some(w => w.from.node === res.bundle.id)).toBe(false)
|
|
||||||
syncCables(p)
|
syncCables(p)
|
||||||
expect(res.bundle.names).toEqual(['S0', 'S1', 'S2', 'S3'])
|
expect(res.split.names).toEqual(['S0', 'S1', 'S2', 'S3'])
|
||||||
// The cable pulled out and let go a few squares on.
|
expect(res.split.x).toBeGreaterThan(res.bundle.x)
|
||||||
const split = cableEnd(def, res.bundle.id, res.bundle.x + 7, res.bundle.y)!
|
|
||||||
expect(split.kind).toBe('split')
|
|
||||||
expect(split.bits).toBe(4)
|
|
||||||
expect(def.wires.filter(w => w.from.node === res.bundle.id && w.to.node === split.id).map(w => [w.from.pin, w.to.pin])).toEqual([['q', 'a']])
|
|
||||||
syncCables(p)
|
|
||||||
expect(split.names).toEqual(['S0', 'S1', 'S2', 'S3'])
|
|
||||||
// A second adder: drop the split right onto its A inputs.
|
// A second adder: drop the split right onto its A inputs.
|
||||||
def.nodes.push({ id: 'add2', kind: 'chip', chip: 'ex-add4', x: 60, y: 0 })
|
def.nodes.push({ id: 'add2', kind: 'chip', chip: 'ex-add4', x: 60, y: 0 })
|
||||||
const lay = (() => {
|
const lay = (() => {
|
||||||
const s = shapeOf(node(def, 'add2'), get).inputs[0]!
|
const s = shapeOf(node(def, 'add2'), get).inputs[0]!
|
||||||
return { x: 60 + s.dx - 1, y: s.dy }
|
return { x: 60 + s.dx - 1, y: s.dy }
|
||||||
})()
|
})()
|
||||||
split.x = lay.x
|
res.split.x = lay.x
|
||||||
split.y = lay.y
|
res.split.y = lay.y
|
||||||
const moved = dropPins(def, [split], n => shapeOf(n, get))
|
const moved = dropPins(def, [res.split], n => shapeOf(n, get))
|
||||||
const still = dropPins(def, def.nodes.filter(n => n !== split), n => shapeOf(n, get))
|
const still = dropPins(def, def.nodes.filter(n => n !== res.split), n => shapeOf(n, get))
|
||||||
const drop = dropLinks(moved, still, 0)!
|
const drop = dropLinks(moved, still, 0)!
|
||||||
expect(drop.links).toHaveLength(4)
|
expect(drop.links).toHaveLength(4)
|
||||||
def.wires.push(...drop.links.map((l, i) => ({ id: `d${i}`, ...l })))
|
def.wires.push(...drop.links.map((l, i) => ({ id: `d${i}`, ...l })))
|
||||||
syncCables(p)
|
syncCables(p)
|
||||||
expect(split.plug).toBe('add2')
|
expect(res.split.plug).toBe('add2')
|
||||||
// A0 of the first adder set: S0 = 1 arrives at A0 of the second, whose S0 shows it.
|
// A0 of the first adder set: S0 = 1 arrives at A0 of the second, whose S0 shows it.
|
||||||
def.nodes.push({ id: 'out', kind: 'lamp', x: 80, y: 0 })
|
def.nodes.push({ id: 'out', kind: 'lamp', x: 80, y: 0 })
|
||||||
def.wires.push({ id: 'o', from: { node: 'add2', pin: outs[0]! }, to: { node: 'out', pin: 'a' } })
|
def.wires.push({ id: 'o', from: { node: 'add2', pin: outs[0]! }, to: { node: 'out', pin: 'a' } })
|
||||||
|
|
@ -348,35 +339,17 @@ describe('a cable straight off a part', () => {
|
||||||
expect(s.pin('out', 'a')).toBe(1)
|
expect(s.pin('out', 'a')).toBe(1)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('into inputs: only a plug on the free pins, named after them; a bundle comes behind it when the cable is pulled out', () => {
|
it('into inputs: a split plugged on the free pins, a free bundle behind it', () => {
|
||||||
const { p, def, ins } = adder()
|
const { p, def, ins } = adder()
|
||||||
def.wires = def.wires.filter(w => w.to.node !== 'add')
|
def.wires = def.wires.filter(w => w.to.node !== 'add')
|
||||||
const res = cableIntoPins(def, 'add', ins.slice(4, 8), lookup(p))
|
const res = cableIntoPins(def, 'add', ins.slice(4, 8), lookup(p))
|
||||||
if (!res.ok) throw new Error(res.error)
|
if (!res.ok) throw new Error(res.error)
|
||||||
expect(res.split.plug).toBe('add')
|
expect(res.split.plug).toBe('add')
|
||||||
expect(touches(p, def, res.split)).toBe(true)
|
expect(touches(p, def, res.split)).toBe(true)
|
||||||
expect(def.nodes.filter(n => n.kind === 'bundle')).toHaveLength(0)
|
expect(res.bundle.x).toBeLessThan(res.split.x)
|
||||||
syncCables(p)
|
syncCables(p)
|
||||||
expect(res.split.names).toEqual(['B0', 'B1', 'B2', 'B3'])
|
expect(res.bundle.names).toEqual(['B0', 'B1', 'B2', 'B3'])
|
||||||
// Those inputs are taken now: no second plug on them.
|
// Those inputs are taken now: no second cable into them.
|
||||||
expect(cableIntoPins(def, 'add', ins.slice(4, 8), lookup(p)).ok).toBe(false)
|
expect(cableIntoPins(def, 'add', ins.slice(4, 8), lookup(p)).ok).toBe(false)
|
||||||
const bundle = cableEnd(def, res.split.id, res.split.x - 8, res.split.y)!
|
|
||||||
expect(bundle.kind).toBe('bundle')
|
|
||||||
expect(bundle.x).toBeLessThan(res.split.x)
|
|
||||||
syncCables(p)
|
|
||||||
expect(bundle.names).toEqual(['B0', 'B1', 'B2', 'B3'])
|
|
||||||
// A split has one cable: none more out of it.
|
|
||||||
expect(cableEnd(def, res.split.id, 0, 0)).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a bundle can have more cables pulled out of it, each to its own split', () => {
|
|
||||||
const { p, def, outs } = adder()
|
|
||||||
def.wires = def.wires.filter(w => w.from.node !== 'add')
|
|
||||||
const res = cableFromPins(def, 'add', outs.slice(0, 4), lookup(p))
|
|
||||||
if (!res.ok) throw new Error(res.error)
|
|
||||||
const a = cableEnd(def, res.bundle.id, 40, 0)!
|
|
||||||
const b = cableEnd(def, res.bundle.id, 40, 10)!
|
|
||||||
expect(def.wires.filter(w => w.from.node === res.bundle.id).map(w => w.to.node).sort()).toEqual([a.id, b.id].sort())
|
|
||||||
expect(cableEnd(def, 'add', 0, 0)).toBeNull()
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -1,365 +0,0 @@
|
||||||
import { describe, expect, it } from 'vitest'
|
|
||||||
import { cableFromPins, cableIntoPins } from '../app/lib/logic/cables'
|
|
||||||
import { checkCircuit, doublyFedLines } from '../app/lib/logic/check'
|
|
||||||
import { compile } from '../app/lib/logic/compile'
|
|
||||||
import { pinKindOf, shapeOf } from '../app/lib/logic/geometry'
|
|
||||||
import { pinName } from '../app/lib/logic/labels'
|
|
||||||
import { createProject, lineForWire, lookup, pruneWires, splitPort, unpackChip } from '../app/lib/logic/ops'
|
|
||||||
import { attachPanel, syncPanels } from '../app/lib/logic/panels'
|
|
||||||
import { toProject } from '../app/lib/logic/project'
|
|
||||||
import { Simulator } from '../app/lib/logic/sim'
|
|
||||||
import type { CircuitNode, 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] } })
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The "Mini HDMI" of the connector tests: D0 and D1 out → in, HPD back.
|
|
||||||
* Source sends A and B out of its out port and reports HPD; Sink shows the
|
|
||||||
* data as X and Y and drives HPD from H. Root places one of each, unwired.
|
|
||||||
*/
|
|
||||||
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 },
|
|
||||||
{ id: 'lamp', kind: 'lamp', x: 50, y: 0 },
|
|
||||||
],
|
|
||||||
wires: [w('r1', ['sa', 'q'], ['src', 'a']), w('r2', ['sb', 'q'], ['src', 'b']), w('r3', ['sh', 'q'], ['snk', 'h'])],
|
|
||||||
}
|
|
||||||
p.components.push(source, sink, root)
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
const node = (p: Project, def: string, id: string) => p.components.find(d => d.id === def)!.nodes.find(n => n.id === id)!
|
|
||||||
const root = (p: Project) => p.components.find(d => d.id === 'root')!
|
|
||||||
|
|
||||||
function run(p: Project, on: Record<string, boolean>) {
|
|
||||||
const s = new Simulator(compile(lookup(p), 'root'))
|
|
||||||
for (const [k, v] of Object.entries(on)) s.setSource(k, v)
|
|
||||||
s.run()
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('ports on a component box', () => {
|
|
||||||
it('sit at the very top of their side, above the single pins', () => {
|
|
||||||
const p = project()
|
|
||||||
// More single pins than before, so a port at the bottom would show.
|
|
||||||
node(p, 'sink', 'h').y = -4
|
|
||||||
p.components.find(d => d.id === 'sink')!.nodes.push({ id: 'k', kind: 'input', x: 10, y: 10, label: 'K' })
|
|
||||||
const get = lookup(p)
|
|
||||||
const snk = shapeOf({ id: 'n', kind: 'chip', chip: 'sink', x: 0, y: 0 }, get)
|
|
||||||
expect(snk.inputs.map(i => [i.key, i.dy])).toEqual([['rx', 0], ['h', 1], ['k', 2]])
|
|
||||||
const src = shapeOf({ id: 'n', kind: 'chip', chip: 'source', x: 0, y: 0 }, get)
|
|
||||||
expect(src.outputs.map(o => [o.key, o.dx, o.dy])).toEqual([['tx', src.body.w, 0], ['hpd', src.body.w, 1]])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('also at the top of a box drawn by hand', () => {
|
|
||||||
const p = project()
|
|
||||||
const sink = p.components.find(d => d.id === 'sink')!
|
|
||||||
sink.design = { w: 6, h: 3, pinAt: { h: 0, x: 2 } }
|
|
||||||
const s = shapeOf({ id: 'n', kind: 'chip', chip: 'sink', x: 0, y: 0 }, lookup(p))
|
|
||||||
expect(s.inputs.map(i => [i.key, i.dy])).toEqual([['rx', 0], ['h', 1]])
|
|
||||||
expect(s.outputs.map(o => [o.key, o.dx, o.dy])).toEqual([['x', 6, 2], ['y', 6, 3]])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('split, a port shows a pin per line right below its socket, each facing out of its side', () => {
|
|
||||||
const p = project()
|
|
||||||
const get = lookup(p)
|
|
||||||
const snk = shapeOf({ id: 'n', kind: 'chip', chip: 'sink', x: 0, y: 0, splitPorts: ['rx'] }, get)
|
|
||||||
// In port on the left: D0 and D1 come in (inputs), HPD goes back out (an output on the left).
|
|
||||||
expect(snk.inputs.map(i => [i.key, i.label, i.dx, i.dy, i.face])).toEqual([
|
|
||||||
['rx', 'IN', 0, 0, undefined],
|
|
||||||
['rx.l0', 'D0', 0, 1, -1],
|
|
||||||
['rx.l1', 'D1', 0, 2, -1],
|
|
||||||
['h', 'H', 0, 4, undefined],
|
|
||||||
])
|
|
||||||
expect(snk.outputs.find(o => o.key === 'rx.l2')).toMatchObject({ label: 'HPD', dx: 0, dy: 3, face: -1, port: 'rx' })
|
|
||||||
// Out port on the right: D0 and D1 go out, HPD comes back in (an input on the right).
|
|
||||||
const src = shapeOf({ id: 'n', kind: 'chip', chip: 'source', x: 0, y: 0, splitPorts: ['tx'] }, get)
|
|
||||||
const right = src.body.w
|
|
||||||
expect(src.outputs.map(o => [o.key, o.dx, o.dy, o.face])).toEqual([
|
|
||||||
['tx', right, 0, undefined],
|
|
||||||
['tx.l0', right, 1, 1],
|
|
||||||
['tx.l1', right, 2, 1],
|
|
||||||
['hpd', right, 4, undefined],
|
|
||||||
])
|
|
||||||
expect(src.inputs.find(i => i.key === 'tx.l2')).toMatchObject({ label: 'HPD', dx: right, dy: 3, face: 1 })
|
|
||||||
// Lines take single wires; the socket still takes the cable.
|
|
||||||
expect(pinKindOf(snk.inputs[1]!)).toBe('')
|
|
||||||
expect(pinKindOf(snk.inputs[0]!)).toBe('c:hdmi')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('split on a box drawn by hand, the lines follow the socket and push the pins below down', () => {
|
|
||||||
const p = project()
|
|
||||||
p.components.find(d => d.id === 'sink')!.design = { w: 6, h: 3, pinAt: { h: 1 } }
|
|
||||||
const s = shapeOf({ id: 'n', kind: 'chip', chip: 'sink', x: 0, y: 0, splitPorts: ['rx'] }, lookup(p))
|
|
||||||
expect(s.inputs.map(i => [i.key, i.dy])).toEqual([['rx', 0], ['rx.l0', 1], ['rx.l1', 2], ['h', 4]])
|
|
||||||
expect(s.outputs.find(o => o.key === 'rx.l2')).toMatchObject({ dx: 0, dy: 3 })
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a line wired from outside drives the inside, and a back line brings the inside out', () => {
|
|
||||||
const p = project()
|
|
||||||
node(p, 'root', 'snk').splitPorts = ['rx']
|
|
||||||
root(p).wires.push(w('d0', ['sa', 'q'], ['snk', 'rx.l0']), w('hp', ['snk', 'rx.l2'], ['lamp', 'a']))
|
|
||||||
for (const [a, h] of [[0, 0], [1, 0], [0, 1], [1, 1]] as const) {
|
|
||||||
const s = run(p, { sa: !!a, sh: !!h })
|
|
||||||
expect([s.pin('snk', 'x'), s.pin('snk', 'rx.l2'), s.pin('lamp', 'q')]).toEqual([a, h, h])
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
it('an out port split the same way: its lines leave on the right, the back line comes in there', () => {
|
|
||||||
const p = project()
|
|
||||||
node(p, 'root', 'src').splitPorts = ['tx']
|
|
||||||
root(p).wires.push(w('d1', ['src', 'tx.l1'], ['lamp', 'a']), w('hp', ['sh', 'q'], ['src', 'tx.l2']))
|
|
||||||
for (const [b, h] of [[0, 1], [1, 0], [1, 1]] as const) {
|
|
||||||
const s = run(p, { sb: !!b, sh: !!h })
|
|
||||||
expect([s.pin('lamp', 'q'), s.pin('src', 'hpd')]).toEqual([b, h])
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a cable on the socket and wires on the lines work together', () => {
|
|
||||||
const p = project()
|
|
||||||
node(p, 'root', 'snk').splitPorts = ['rx']
|
|
||||||
root(p).wires.push(w('cable', ['src', 'tx'], ['snk', 'rx']), w('hp', ['snk', 'rx.l2'], ['lamp', 'a']))
|
|
||||||
const s = run(p, { sa: true, sb: false, sh: true })
|
|
||||||
// The cable still carries every line; the line pins show what it carries.
|
|
||||||
expect([s.pin('snk', 'x'), s.pin('snk', 'y'), s.pin('src', 'hpd')]).toEqual([1, 0, 1])
|
|
||||||
expect([s.pin('snk', 'rx.l0'), s.pin('snk', 'rx.l1'), s.pin('lamp', 'q')]).toEqual([1, 0, 1])
|
|
||||||
expect(doublyFedLines(root(p), node(p, 'root', 'snk'), lookup(p))).toEqual([])
|
|
||||||
// A wire into a line the cable feeds as well: both drive it, and the check says so.
|
|
||||||
root(p).wires.push(w('d0', ['sb', 'q'], ['snk', 'rx.l0']))
|
|
||||||
expect(doublyFedLines(root(p), node(p, 'root', 'snk'), lookup(p))).toEqual(['rx.l0'])
|
|
||||||
expect(checkCircuit(root(p), lookup(p)).some(i => i.level === 'error' && i.text.includes('D0'))).toBe(true)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('passes split lines through a component that offers an inner part’s port as its own', () => {
|
|
||||||
const p = project()
|
|
||||||
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'])],
|
|
||||||
})
|
|
||||||
root(p).nodes.push({ id: 'bx', kind: 'chip', chip: 'box', x: 6, y: 20, splitPorts: ['p2'] })
|
|
||||||
root(p).wires.push(w('r9', ['sa', 'q'], ['bx', 'i']), w('l0', ['bx', 'p2.l0'], ['lamp', 'a']))
|
|
||||||
expect(run(p, { sa: true }).pin('lamp', 'q')).toBe(1)
|
|
||||||
expect(run(p, { sa: false }).pin('lamp', 'q')).toBe(0)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('joining a port again removes the wires on its lines and keeps the cable', () => {
|
|
||||||
const p = project()
|
|
||||||
const r = root(p)
|
|
||||||
expect(splitPort(p, r, 'snk', 'rx', true)).toBe(0)
|
|
||||||
expect(node(p, 'root', 'snk').splitPorts).toEqual(['rx'])
|
|
||||||
r.wires.push(w('cable', ['src', 'tx'], ['snk', 'rx']), w('d0', ['sa', 'q'], ['snk', 'rx.l0']), w('hp', ['snk', 'rx.l2'], ['lamp', 'a']))
|
|
||||||
expect(pruneWires(p)).toBe(false)
|
|
||||||
expect(splitPort(p, r, 'snk', 'rx', false)).toBe(2)
|
|
||||||
expect(node(p, 'root', 'snk').splitPorts).toBeUndefined()
|
|
||||||
expect(r.wires.map(x => x.id)).toEqual(['r1', 'r2', 'r3', 'cable'])
|
|
||||||
// No port of that name: nothing changes.
|
|
||||||
expect(splitPort(p, r, 'snk', 'nope', true)).toBe(0)
|
|
||||||
expect(node(p, 'root', 'snk').splitPorts).toBeUndefined()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a single wire dropped on a socket takes the first free line that runs its way', () => {
|
|
||||||
const p = project()
|
|
||||||
const r = root(p)
|
|
||||||
// Into the sink's in port: D0, then D1; from it: HPD.
|
|
||||||
expect(lineForWire(p, r, 'snk', 'rx', true)).toBe('rx.l0')
|
|
||||||
expect(lineForWire(p, r, 'snk', 'rx', false)).toBe('rx.l2')
|
|
||||||
r.wires.push(w('d0', ['sa', 'q'], ['snk', 'rx.l0']))
|
|
||||||
expect(lineForWire(p, r, 'snk', 'rx', true)).toBe('rx.l1')
|
|
||||||
r.wires.push(w('d1', ['sb', 'q'], ['snk', 'rx.l1']))
|
|
||||||
expect(lineForWire(p, r, 'snk', 'rx', true)).toBeNull()
|
|
||||||
// A line coming out can feed another wire.
|
|
||||||
r.wires.push(w('hp', ['snk', 'rx.l2'], ['lamp', 'a']))
|
|
||||||
expect(lineForWire(p, r, 'snk', 'rx', false)).toBe('rx.l2')
|
|
||||||
// The source's out port: its back line goes in, D0 comes out first.
|
|
||||||
expect(lineForWire(p, r, 'src', 'tx', true)).toBe('tx.l2')
|
|
||||||
expect(lineForWire(p, r, 'src', 'tx', false)).toBe('tx.l0')
|
|
||||||
expect(lineForWire(p, r, 'src', 'nope', true)).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('cleans up wires on lines whose port is no longer split', () => {
|
|
||||||
const p = project()
|
|
||||||
node(p, 'root', 'snk').splitPorts = ['rx']
|
|
||||||
root(p).wires.push(w('d0', ['sa', 'q'], ['snk', 'rx.l0']))
|
|
||||||
expect(pruneWires(p)).toBe(false)
|
|
||||||
delete node(p, 'root', 'snk').splitPorts
|
|
||||||
expect(pruneWires(p)).toBe(true)
|
|
||||||
expect(root(p).wires.some(x => x.id === 'd0')).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a typed cable never plugs into a line, a single wire never into a socket', () => {
|
|
||||||
const p = project()
|
|
||||||
node(p, 'root', 'snk').splitPorts = ['rx']
|
|
||||||
root(p).wires.push(w('bad1', ['src', 'tx'], ['snk', 'rx.l0']), w('bad2', ['sa', 'q'], ['snk', 'rx']))
|
|
||||||
expect(pruneWires(p)).toBe(true)
|
|
||||||
expect(root(p).wires.map(x => x.id)).toEqual(['r1', 'r2', 'r3'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('names a line pin after its line, keeps the setting through loading and leaves line pins off docked panels', () => {
|
|
||||||
const p = project()
|
|
||||||
const snk = node(p, 'root', 'snk')
|
|
||||||
snk.splitPorts = ['rx']
|
|
||||||
expect(pinName(snk, 'rx.l1', lookup(p))).toBe('D1')
|
|
||||||
const data = JSON.parse(JSON.stringify(p))
|
|
||||||
data.components.find((d: ComponentDef) => d.id === 'root').nodes.find((n: CircuitNode) => n.id === 'src').splitPorts = 'tx'
|
|
||||||
const back = toProject(data)
|
|
||||||
expect(node(back, 'root', 'snk').splitPorts).toEqual(['rx'])
|
|
||||||
expect(node(back, 'root', 'src').splitPorts).toBeUndefined()
|
|
||||||
// A docked input panel gets a switch for H only: the socket and the lines are the cable's.
|
|
||||||
root(p).wires = root(p).wires.filter(x => x.id !== 'r3')
|
|
||||||
const panel = attachPanel(p, root(p), 'snk')!
|
|
||||||
expect(panel.rows!.map(r => r.id)).toEqual(['h'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('with a cable in the socket, a dropped wire takes no line going in: the cable feeds those', () => {
|
|
||||||
const p = project()
|
|
||||||
const r = root(p)
|
|
||||||
r.wires.push(w('cable', ['src', 'tx'], ['snk', 'rx']))
|
|
||||||
// Into the sink's in port: D0 and D1 come through the cable. HPD can still be read.
|
|
||||||
expect(lineForWire(p, r, 'snk', 'rx', true)).toBeNull()
|
|
||||||
expect(lineForWire(p, r, 'snk', 'rx', false)).toBe('rx.l2')
|
|
||||||
// The source's out port: HPD comes back through the cable, D0 can still be read.
|
|
||||||
expect(lineForWire(p, r, 'src', 'tx', true)).toBeNull()
|
|
||||||
expect(lineForWire(p, r, 'src', 'tx', false)).toBe('tx.l0')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a line going in with neither a wire nor a cable is an open input', () => {
|
|
||||||
const p = project()
|
|
||||||
node(p, 'root', 'snk').splitPorts = ['rx']
|
|
||||||
root(p).wires.push(w('d0', ['sa', 'q'], ['snk', 'rx.l0']))
|
|
||||||
expect(checkCircuit(root(p), lookup(p)).some(i => i.level === 'warn' && i.text === 'Sink: D1 not connected (reads 0)')).toBe(true)
|
|
||||||
// A cable in the socket feeds D1.
|
|
||||||
root(p).wires = root(p).wires.filter(x => x.id !== 'd0')
|
|
||||||
root(p).wires.push(w('cable', ['src', 'tx'], ['snk', 'rx']))
|
|
||||||
expect(checkCircuit(root(p), lookup(p)).some(i => i.text.includes('not connected'))).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('splitting or joining a port leaves the pins of the other side where they are', () => {
|
|
||||||
const p = project()
|
|
||||||
const get = lookup(p)
|
|
||||||
for (const design of [undefined, { w: 6, h: 3 }]) {
|
|
||||||
p.components.find(d => d.id === 'source')!.design = design
|
|
||||||
const rows = (splitPorts?: string[]) => shapeOf({ id: 'n', kind: 'chip', chip: 'source', x: 0, y: 0, splitPorts }, get).inputs.filter(i => !i.port).map(i => [i.key, i.dy])
|
|
||||||
expect(rows(['tx'])).toEqual(rows())
|
|
||||||
}
|
|
||||||
// A side of single pins only is still centred when nothing is split.
|
|
||||||
p.components.find(d => d.id === 'source')!.design = undefined
|
|
||||||
p.components.find(d => d.id === 'source')!.nodes.push({ id: 'z', kind: 'output', x: 10, y: 10, label: 'Z' }, { id: 'z2', kind: 'output', x: 10, y: 12, label: 'Z2' })
|
|
||||||
expect(shapeOf({ id: 'n', kind: 'chip', chip: 'source', x: 0, y: 0 }, get).inputs.map(i => [i.key, i.dy])).toEqual([['a', 1], ['b', 2]])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('lists the pins of the usual edge first, so a wire dropped on the box takes those', () => {
|
|
||||||
const p = project()
|
|
||||||
const get = lookup(p)
|
|
||||||
const snk = shapeOf({ id: 'n', kind: 'chip', chip: 'sink', x: 0, y: 0, splitPorts: ['rx'] }, get)
|
|
||||||
expect(snk.outputs.map(o => o.key)).toEqual(['x', 'y', 'rx.l2'])
|
|
||||||
const src = shapeOf({ id: 'n', kind: 'chip', chip: 'source', x: 0, y: 0, splitPorts: ['tx'] }, get)
|
|
||||||
expect(src.inputs.map(i => i.key)).toEqual(['a', 'b', 'tx.l2'])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a cable onto split lines only takes those on their usual edge, so its end never sits in the box', () => {
|
|
||||||
const p = project()
|
|
||||||
p.connectors![0]!.lines = [{ name: 'D0' }, { name: 'D1' }, { name: 'RX0', back: true }, { name: 'RX1', back: true }]
|
|
||||||
const r = root(p)
|
|
||||||
const get = lookup(p)
|
|
||||||
node(p, 'root', 'src').splitPorts = ['tx']
|
|
||||||
node(p, 'root', 'snk').splitPorts = ['rx']
|
|
||||||
// RX0 and RX1 run back: into the source on its right edge, out of the sink on its left.
|
|
||||||
expect(cableIntoPins(r, 'src', ['tx.l2', 'tx.l3'], get).ok).toBe(false)
|
|
||||||
expect(cableFromPins(r, 'snk', ['rx.l2', 'rx.l3'], get).ok).toBe(false)
|
|
||||||
// D0 and D1 leave the source on the right and enter the sink on the left: there a cable fits.
|
|
||||||
const src = node(p, 'root', 'src')
|
|
||||||
const out = cableFromPins(r, 'src', ['tx.l0', 'tx.l1'], get)
|
|
||||||
expect(out.ok && out.bundle.x).toBe(src.x + shapeOf(src, get).body.w)
|
|
||||||
const into = cableIntoPins(r, 'snk', ['rx.l0', 'rx.l1'], get)
|
|
||||||
expect(into.ok && into.split.x).toBe(node(p, 'root', 'snk').x - 1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('unpacking joins wires on split lines to the parts inside', () => {
|
|
||||||
const p = project()
|
|
||||||
const r = root(p)
|
|
||||||
node(p, 'root', 'snk').splitPorts = ['rx']
|
|
||||||
r.nodes.push({ id: 'lamp2', kind: 'lamp', x: 50, y: 4 })
|
|
||||||
r.wires.push(w('d0', ['sa', 'q'], ['snk', 'rx.l0']), w('xl', ['snk', 'x'], ['lamp', 'a']), w('hp', ['snk', 'rx.l2'], ['lamp2', 'a']))
|
|
||||||
const res = unpackChip(p, 'root', 'snk')
|
|
||||||
expect(res.ok && res.dropped).toBe(0)
|
|
||||||
for (const [a, h] of [[0, 1], [1, 0]] as const) {
|
|
||||||
const s = run(p, { sa: !!a, sh: !!h })
|
|
||||||
expect([s.pin('lamp', 'q'), s.pin('lamp2', 'q')]).toEqual([a, h])
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
it('unpacking says how many wires on lines had nowhere to go', () => {
|
|
||||||
const p = project()
|
|
||||||
p.components.push({
|
|
||||||
id: 'box',
|
|
||||||
name: 'Box',
|
|
||||||
symbol: 'box',
|
|
||||||
nodes: [
|
|
||||||
{ id: 'inner', kind: 'chip', chip: 'source', x: 6, y: 0 },
|
|
||||||
{ id: 'p2', kind: 'portout', conn: 'hdmi', x: 30, y: 0 },
|
|
||||||
],
|
|
||||||
wires: [w('b2', ['inner', 'tx'], ['p2', 'bus'])],
|
|
||||||
})
|
|
||||||
// D0 of the box comes from a part inside through a cable: no single wire inside to join it to.
|
|
||||||
root(p).nodes.push({ id: 'bx', kind: 'chip', chip: 'box', x: 6, y: 20, splitPorts: ['p2'] })
|
|
||||||
root(p).wires.push(w('l0', ['bx', 'p2.l0'], ['lamp', 'a']))
|
|
||||||
const res = unpackChip(p, 'root', 'bx')
|
|
||||||
expect(res.ok && res.dropped).toBe(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a docked panel made before ports moved to the top loses its row for the socket and lines up again', () => {
|
|
||||||
const p = project()
|
|
||||||
const r = root(p)
|
|
||||||
r.wires = r.wires.filter(x => x.id !== 'r3')
|
|
||||||
// As docked by earlier releases: a row for H and one for the socket below it, the port at the bottom.
|
|
||||||
r.nodes.push({ id: 'pan', kind: 'panel', x: 24, y: 0, attach: 'snk', rows: [{ id: 'h', type: 'switch', dy: 0 }, { id: 'rx', type: 'switch', dy: 1 }] })
|
|
||||||
r.wires.push(w('ph', ['pan', 'h'], ['snk', 'h']))
|
|
||||||
syncPanels(p)
|
|
||||||
pruneWires(p)
|
|
||||||
const pan = node(p, 'root', 'pan')
|
|
||||||
expect(pan.rows!.map(x => x.id)).toEqual(['h'])
|
|
||||||
const h = shapeOf(node(p, 'root', 'snk'), lookup(p)).inputs.find(i => i.key === 'h')!
|
|
||||||
expect(pan.y).toBe(node(p, 'root', 'snk').y + h.dy)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,69 +0,0 @@
|
||||||
import { describe, expect, it } from 'vitest'
|
|
||||||
import { openInputs } from '../app/lib/logic/check'
|
|
||||||
import { compile } from '../app/lib/logic/compile'
|
|
||||||
import { rgbHex, screenLayout, shapeOf } from '../app/lib/logic/geometry'
|
|
||||||
import { createProject, lookup } from '../app/lib/logic/ops'
|
|
||||||
import { Simulator } from '../app/lib/logic/sim'
|
|
||||||
import type { ComponentDef } from '../app/lib/logic/types'
|
|
||||||
|
|
||||||
/** A component with one RGB pixel, its red and blue inputs from two input pins; placed in a circuit with two switches. */
|
|
||||||
function setup() {
|
|
||||||
const p = createProject({ examples: false })
|
|
||||||
const inner: ComponentDef = {
|
|
||||||
id: 'mon',
|
|
||||||
name: 'Monitor',
|
|
||||||
symbol: 'box',
|
|
||||||
nodes: [
|
|
||||||
{ id: 'R', kind: 'input', x: 0, y: 0, label: 'R' },
|
|
||||||
{ id: 'B', kind: 'input', x: 0, y: 2, label: 'B' },
|
|
||||||
{ id: 'px', kind: 'pixel', x: 10, y: 0, rgb: true },
|
|
||||||
],
|
|
||||||
wires: [
|
|
||||||
{ id: 'w1', from: { node: 'R', pin: 'q' }, to: { node: 'px', pin: 'r' } },
|
|
||||||
{ id: 'w2', from: { node: 'B', pin: 'q' }, to: { node: 'px', pin: 'b' } },
|
|
||||||
],
|
|
||||||
}
|
|
||||||
const root: ComponentDef = {
|
|
||||||
id: 'root',
|
|
||||||
name: 'Root',
|
|
||||||
symbol: 'box',
|
|
||||||
nodes: [
|
|
||||||
{ id: 's1', kind: 'input', x: 0, y: 0 },
|
|
||||||
{ id: 's2', kind: 'input', x: 0, y: 2 },
|
|
||||||
{ id: 'm', kind: 'chip', chip: 'mon', x: 10, y: 0 },
|
|
||||||
],
|
|
||||||
wires: [
|
|
||||||
{ id: 'a', from: { node: 's1', pin: 'q' }, to: { node: 'm', pin: 'R' } },
|
|
||||||
{ id: 'b', from: { node: 's2', pin: 'q' }, to: { node: 'm', pin: 'B' } },
|
|
||||||
],
|
|
||||||
}
|
|
||||||
p.components.push(inner, root)
|
|
||||||
return { p, inner, root }
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('RGB pixels', () => {
|
|
||||||
it('have red, green and blue inputs and mix eight colours', () => {
|
|
||||||
const { p, inner } = setup()
|
|
||||||
expect(shapeOf(inner.nodes[2]!, lookup(p)).inputs.map(i => i.key)).toEqual(['r', 'g', 'b'])
|
|
||||||
expect(rgbHex(0, 0, 0)).toBe('')
|
|
||||||
expect(rgbHex(1, 0, 1)).toBe('#ff5cf0')
|
|
||||||
expect(rgbHex(1, 1, 1)).toBe('#f2f6fa')
|
|
||||||
// Green left open on purpose: no warning.
|
|
||||||
expect(openInputs(inner, inner.nodes[2]!, lookup(p))).toEqual([])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('show their colour on the screen of the component they are in', () => {
|
|
||||||
const { p, inner, root } = setup()
|
|
||||||
expect(screenLayout(inner)!.pixels).toEqual([{ id: 'px', col: 0, row: 0, color: undefined, rgb: true }])
|
|
||||||
const s = new Simulator(compile(lookup(p), root.id))
|
|
||||||
s.setSource('s1', true)
|
|
||||||
s.setSource('s2', true)
|
|
||||||
s.run()
|
|
||||||
expect([s.face('m', 'px', 'r'), s.face('m', 'px', 'g'), s.face('m', 'px', 'b')]).toEqual([1, 0, 1])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a one-colour pixel keeps its single input', () => {
|
|
||||||
const { p } = setup()
|
|
||||||
expect(shapeOf({ id: 'x', kind: 'pixel', x: 0, y: 0 }, lookup(p)).inputs.map(i => i.key)).toEqual(['a'])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
import { shapeOf, type Pt } from '../app/lib/logic/geometry'
|
import { shapeOf, type Pt } from '../app/lib/logic/geometry'
|
||||||
import { createProject, lookup } from '../app/lib/logic/ops'
|
import { createProject, lookup } from '../app/lib/logic/ops'
|
||||||
import { circuitRoutes, findCrossings, planHops, routeAll, WIRE_H, type Box, type Routed } from '../app/lib/logic/routing'
|
import { circuitRoutes, findCrossings, routeAll, type Routed } from '../app/lib/logic/routing'
|
||||||
|
|
||||||
/** Every pair of segments from different nets that lie on the same line and overlap. */
|
/** Every pair of segments from different nets that lie on the same line and overlap. */
|
||||||
function overlaps(routes: Routed[]) {
|
function overlaps(routes: Routed[]) {
|
||||||
|
|
@ -133,138 +133,3 @@ describe('tidy routing on every example', () => {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
/** Segments of a route that run through the inside of a part (its edges, where pins sit, are fine). */
|
|
||||||
function throughParts(r: Routed, boxes: Box[]): number {
|
|
||||||
let n = 0
|
|
||||||
for (let i = 0; i < r.grid.length - 1; i++) {
|
|
||||||
const [ax, ay] = r.grid[i]!
|
|
||||||
const [bx, by] = r.grid[i + 1]!
|
|
||||||
const lx = Math.min(ax, bx)
|
|
||||||
const hx = Math.max(ax, bx)
|
|
||||||
const ly = Math.min(ay, by)
|
|
||||||
const hy = Math.max(ay, by)
|
|
||||||
for (const b of boxes) {
|
|
||||||
const hit = ly === hy ? ly > b.y && ly < b.y + b.h && hx > b.x && lx < b.x + b.w : lx > b.x && lx < b.x + b.w && hy > b.y && ly < b.y + b.h
|
|
||||||
if (hit) n++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return n
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('lines and parts', () => {
|
|
||||||
const p = createProject({ examples: true })
|
|
||||||
const get = lookup(p)
|
|
||||||
for (const tidy of [false, true]) {
|
|
||||||
it(`no wire runs over or under a part, on any example${tidy ? ' (tidy)' : ''}`, () => {
|
|
||||||
for (const def of p.components) {
|
|
||||||
const shapes = new Map(def.nodes.map(n => [n.id, shapeOf(n, get)]))
|
|
||||||
const boxes = def.nodes.filter(n => n.kind !== 'note').map(n => {
|
|
||||||
const b = shapes.get(n.id)!.body
|
|
||||||
return { x: n.x + b.x, y: n.y + b.y, w: b.w, h: b.h }
|
|
||||||
})
|
|
||||||
const routes = circuitRoutes({ ...def, wires: def.wires.map(w => ({ ...w, pts: undefined })) }, shapes, { tidy })
|
|
||||||
for (const r of routes) expect(throughParts(r, boxes), `${def.name}: ${r.id}`).toBe(0)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
it('goes around a part in the way, keeping off its edges', () => {
|
|
||||||
const part = { x: 4, y: -3, w: 4, h: 6 }
|
|
||||||
const [r] = routeAll([{ id: 'w', net: 'n', a: [0, 0], b: [14, 0] }], [part], [])
|
|
||||||
expect(throughParts(r!, [part])).toBe(0)
|
|
||||||
// Not along the part's top or bottom edge either.
|
|
||||||
expect(r!.grid.some(([, y]) => y === -3 || y === 3)).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('finds a way around a whole wall of parts', () => {
|
|
||||||
const wall = [-12, -6, 0, 6].map(y => ({ x: 5, y, w: 3, h: 6 }))
|
|
||||||
const [r] = routeAll([{ id: 'w', net: 'n', a: [0, 1], b: [14, 1] }], wall, [])
|
|
||||||
expect(throughParts(r!, wall)).toBe(0)
|
|
||||||
expect(r!.grid.at(-1)).toEqual([14, 1])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('cables', () => {
|
|
||||||
const CABLE = 0.47 // half the width of a 4-wire ribbon, in grid units
|
|
||||||
|
|
||||||
it('keeps two cables of different signals a column apart, where wires could sit side by side', () => {
|
|
||||||
// Both want column 5 for their vertical step.
|
|
||||||
const ends = (h?: number) =>
|
|
||||||
routeAll(
|
|
||||||
[
|
|
||||||
{ id: 'c1', net: 'n1', a: [0, 0], b: [10, 6], h },
|
|
||||||
{ id: 'c2', net: 'n2', a: [0, 2], b: [10, 8], h },
|
|
||||||
],
|
|
||||||
[],
|
|
||||||
[],
|
|
||||||
).map(r => r.grid[1]![0])
|
|
||||||
const [w1, w2] = ends()
|
|
||||||
expect(Math.abs(w2! - w1!)).toBe(1)
|
|
||||||
const [c1, c2] = ends(CABLE)
|
|
||||||
expect(Math.abs(c2! - c1!)).toBeGreaterThanOrEqual(2)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a second cable of one signal branches off the first, like a wire', () => {
|
|
||||||
const routes = routeAll(
|
|
||||||
[
|
|
||||||
{ id: 'c1', net: 'bus', a: [0, 0], b: [12, 8], h: CABLE },
|
|
||||||
{ id: 'c2', net: 'bus', a: [0, 0], b: [20, 10], h: CABLE },
|
|
||||||
],
|
|
||||||
[],
|
|
||||||
[],
|
|
||||||
)
|
|
||||||
const [first, second] = routes.map(r => r.grid)
|
|
||||||
// On its own it would turn at column 10; it follows the first down column 6 instead.
|
|
||||||
expect(first!.slice(0, 3)).toEqual([[0, 0], [6, 0], [6, 8]])
|
|
||||||
expect(second!.slice(0, 3)).toEqual(first!.slice(0, 3))
|
|
||||||
expect(second!.at(-1)).toEqual([20, 10])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('hops', () => {
|
|
||||||
const H = 0.47
|
|
||||||
|
|
||||||
it('a wire jumps over a cable, as wide as the cable', () => {
|
|
||||||
const routes = routeAll(
|
|
||||||
[
|
|
||||||
{ id: 'cable', net: 'c', a: [5, -6], b: [6, 6], pts: [[5, -6], [5, 6]], h: H },
|
|
||||||
{ id: 'wire', net: 'w', a: [0, 0], b: [10, 0] },
|
|
||||||
],
|
|
||||||
[],
|
|
||||||
[],
|
|
||||||
)
|
|
||||||
const hops = planHops(routes)
|
|
||||||
expect(hops.has(0)).toBe(false)
|
|
||||||
const [hop] = [...hops.get(1)!.values()][0]!
|
|
||||||
expect(hop!.hi - hop!.lo).toBeGreaterThanOrEqual(2 * (H + WIRE_H))
|
|
||||||
})
|
|
||||||
|
|
||||||
it('a vertical wire jumps sideways over a horizontal cable', () => {
|
|
||||||
const routes = routeAll(
|
|
||||||
[
|
|
||||||
{ id: 'cable', net: 'c', a: [0, 0], b: [10, 0], h: H },
|
|
||||||
{ id: 'wire', net: 'w', a: [5, -6], b: [6, 6], pts: [[5, -6], [5, 6]] },
|
|
||||||
],
|
|
||||||
[],
|
|
||||||
[],
|
|
||||||
)
|
|
||||||
const hops = planHops(routes)
|
|
||||||
expect(hops.has(0)).toBe(false)
|
|
||||||
expect(hops.get(1)?.size).toBe(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('two plain wires: the horizontal one hops; nothing hops over its own signal', () => {
|
|
||||||
const routes = routeAll(
|
|
||||||
[
|
|
||||||
{ id: 'h', net: 'n1', a: [0, 3], b: [10, 3] },
|
|
||||||
{ id: 'v', net: 'n2', a: [5, 0], b: [6, 8], pts: [[5, 0], [5, 8]] },
|
|
||||||
{ id: 'v2', net: 'n1', a: [0, 3], b: [8, 9], pts: [[7, 3], [7, 9]] },
|
|
||||||
],
|
|
||||||
[],
|
|
||||||
[],
|
|
||||||
)
|
|
||||||
const hops = planHops(routes)
|
|
||||||
expect([...hops.keys()].map(k => routes[k]!.id).sort()).toEqual(['h', 'v2'])
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
import { describe, expect, it } from 'vitest'
|
|
||||||
import { compile } from '../app/lib/logic/compile'
|
|
||||||
import { shapeOf } from '../app/lib/logic/geometry'
|
|
||||||
import { createProject, lookup } from '../app/lib/logic/ops'
|
|
||||||
import { toProject } from '../app/lib/logic/project'
|
|
||||||
import { scopeLayout } from '../app/lib/logic/scopeLayout'
|
|
||||||
import type { CircuitNode } from '../app/lib/logic/types'
|
|
||||||
|
|
||||||
/** A channel as it comes back from loading a project. */
|
|
||||||
function clean(col: unknown) {
|
|
||||||
const p = createProject({ examples: false })
|
|
||||||
p.components[0]!.nodes.push({ id: 's', kind: 'scope', x: 0, y: 0, scope: { cols: [col as never] } })
|
|
||||||
return toProject(JSON.parse(JSON.stringify(p))).components[0]!.nodes.find(n => n.id === 's')!.scope!.cols[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('logic analyzer part', () => {
|
|
||||||
it('a pin per bit down the left, a lane per channel beside its pins', () => {
|
|
||||||
const p = createProject({ examples: false })
|
|
||||||
const n: CircuitNode = { id: 's', kind: 'scope', x: 0, y: 0, scope: { cols: [{ id: 'a', name: 'CLK', bits: 1 }, { id: 'b', name: 'D', bits: 4 }] } }
|
|
||||||
const shape = shapeOf(n, lookup(p))
|
|
||||||
expect(shape.inputs.map(i => [i.label, i.dy])).toEqual([['CLK', 1], ['D0', 2], ['D1', 3], ['D2', 4], ['D3', 5]])
|
|
||||||
expect(scopeLayout(n).lanes.map(l => [l.row, l.bits])).toEqual([[1, 1], [2, 4]])
|
|
||||||
p.components[0]!.nodes.push(n)
|
|
||||||
expect(compile(lookup(p), p.components[0]!.id).errors).toEqual([])
|
|
||||||
})
|
|
||||||
|
|
||||||
it('its channels are saved and cleaned on loading', () => {
|
|
||||||
expect(clean({ id: 'a', name: 'X'.repeat(50), bits: 99 })).toEqual({ id: 'a', name: 'X'.repeat(40), bits: 1 })
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,344 +0,0 @@
|
||||||
// The editor itself keeping what circuits hold: going into a component and
|
|
||||||
// back, reloading, other projects, and the account on other computers. It
|
|
||||||
// runs the real composable in a stand-in browser (storage, events, a server).
|
|
||||||
|
|
||||||
import * as vue from 'vue'
|
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
||||||
import { compile } from '../app/lib/logic/compile'
|
|
||||||
import { chipPins } from '../app/lib/logic/geometry'
|
|
||||||
import { createProject, lookup } from '../app/lib/logic/ops'
|
|
||||||
import { toProject } from '../app/lib/logic/project'
|
|
||||||
import { Simulator } from '../app/lib/logic/sim'
|
|
||||||
import { packState, stateCarry } from '../app/lib/logic/state'
|
|
||||||
import { listProjects, loadProject, saveProject, setCachedAccount, setCurrentId, type ProjectMeta } from '../app/lib/logic/storage'
|
|
||||||
import type { Project } from '../app/lib/logic/types'
|
|
||||||
|
|
||||||
const USER = { id: 'u1', email: 'me@example.com' }
|
|
||||||
|
|
||||||
/** An SR latch with two buttons, so its bit changes without any edit, open as the circuit. */
|
|
||||||
function latchProject(): Project {
|
|
||||||
const p = createProject({ examples: true })
|
|
||||||
const pins = chipPins(lookup(p)('ex-sr')!)
|
|
||||||
const pin = (label: string) => pins.inputs.find(x => x.label === label)!.key
|
|
||||||
p.components.push({
|
|
||||||
id: 'mem',
|
|
||||||
name: 'Memory',
|
|
||||||
symbol: 'box',
|
|
||||||
nodes: [
|
|
||||||
{ id: 's', kind: 'button', x: 0, y: 0, label: 'S' },
|
|
||||||
{ id: 'r', kind: 'button', x: 0, y: 4, label: 'R' },
|
|
||||||
{ id: 'u', kind: 'chip', chip: 'ex-sr', x: 6, y: 0 },
|
|
||||||
{ id: 'q', kind: 'output', x: 20, y: 0, label: 'Q' },
|
|
||||||
],
|
|
||||||
wires: [
|
|
||||||
{ id: 'w1', from: { node: 's', pin: 'q' }, to: { node: 'u', pin: pin('S') } },
|
|
||||||
{ id: 'w2', from: { node: 'r', pin: 'q' }, to: { node: 'u', pin: pin('R') } },
|
|
||||||
{ id: 'w3', from: { node: 'u', pin: pins.outputs[0]!.key }, to: { node: 'q', pin: 'a' } },
|
|
||||||
],
|
|
||||||
})
|
|
||||||
p.openId = 'mem'
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
/** This browser's storage, kept across "reloads". */
|
|
||||||
let store: Map<string, string>
|
|
||||||
|
|
||||||
/** A tab with the editor open: the stand-in browser around it, then the real composable. */
|
|
||||||
async function openTab() {
|
|
||||||
const events = new Map<string, (() => void)[]>()
|
|
||||||
const on = (type: string, f: () => void) => events.set(type, [...(events.get(type) ?? []), f])
|
|
||||||
const doc = { addEventListener: on, visibilityState: 'visible' }
|
|
||||||
vi.stubGlobal('window', { addEventListener: on })
|
|
||||||
vi.stubGlobal('document', doc)
|
|
||||||
vi.stubGlobal('location', { pathname: '/', origin: 'http://localhost' })
|
|
||||||
vi.stubGlobal('history', { state: null, replaceState() {} })
|
|
||||||
for (const k of ['ref', 'computed', 'reactive', 'shallowRef', 'toRaw', 'watch'] as const) vi.stubGlobal(k, vue[k])
|
|
||||||
vi.resetModules()
|
|
||||||
const { useEditor } = await import('../app/composables/useEditor')
|
|
||||||
const ed = useEditor()
|
|
||||||
const fire = (type: string) => events.get(type)?.forEach(f => f())
|
|
||||||
return {
|
|
||||||
ed,
|
|
||||||
/** Q of the latch as the editor shows it. */
|
|
||||||
q: () => ed.val('q', 'a'),
|
|
||||||
/** A click on a button of the open circuit: down, settle, up, settle. */
|
|
||||||
push(label: string) {
|
|
||||||
const node = ed.def.value.nodes.find(n => n.label === label)!
|
|
||||||
ed.press(node, true)
|
|
||||||
ed.sim.value!.run()
|
|
||||||
ed.press(node, false)
|
|
||||||
ed.sim.value!.run()
|
|
||||||
},
|
|
||||||
hide() {
|
|
||||||
doc.visibilityState = 'hidden'
|
|
||||||
fire('visibilitychange')
|
|
||||||
},
|
|
||||||
close: () => fire('beforeunload'),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Puts a project in this browser's storage and makes it the one that opens. */
|
|
||||||
function stored(p: Project, meta: Partial<ProjectMeta> = {}): ProjectMeta {
|
|
||||||
const m: ProjectMeta = { id: 'p1', name: p.name, updated: Date.now(), ...meta }
|
|
||||||
saveProject(m, p)
|
|
||||||
setCurrentId(m.id)
|
|
||||||
return m
|
|
||||||
}
|
|
||||||
|
|
||||||
const copy = <T>(v: T): T => JSON.parse(JSON.stringify(v))
|
|
||||||
|
|
||||||
/** Q of the latch in a saved project, as it opens from what it held. */
|
|
||||||
function bitOf(p: Project): number {
|
|
||||||
const nl = compile(lookup(p), 'mem')
|
|
||||||
const held = p.state?.mem
|
|
||||||
const s = new Simulator(nl, held && stateCarry(held, nl))
|
|
||||||
s.run()
|
|
||||||
return s.pin('q', 'a')
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The project after the latch was set on another computer. */
|
|
||||||
function setElsewhere(p: Project): Project {
|
|
||||||
const s = new Simulator(compile(lookup(p), 'mem'))
|
|
||||||
for (const [id, on] of [['s', true], ['s', false]] as const) {
|
|
||||||
s.setSource(id, on)
|
|
||||||
s.run()
|
|
||||||
}
|
|
||||||
p.state = { mem: packState(s)! }
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The account on the server, as far as syncing uses it: one save per project with its revision, and savegames. */
|
|
||||||
function account() {
|
|
||||||
const saves = new Map<string, { meta: { id: string; name: string; updated: number; rev: number }; project: Project }>()
|
|
||||||
const versions = new Map<string, { v: number; project: Project }[]>()
|
|
||||||
const keep = (id: string, project: Project) => {
|
|
||||||
const list = versions.get(id) ?? []
|
|
||||||
list.push({ v: Date.now() + list.length, project })
|
|
||||||
versions.set(id, list)
|
|
||||||
}
|
|
||||||
const put = (id: string, project: Project) => {
|
|
||||||
const old = saves.get(id)
|
|
||||||
if (old) keep(id, old.project)
|
|
||||||
const meta = { id, name: project.name, updated: Date.now(), rev: (old?.meta.rev ?? 0) + 1 }
|
|
||||||
saves.set(id, { meta, project: toProject(copy(project)) })
|
|
||||||
return meta
|
|
||||||
}
|
|
||||||
const route = (method: string, url: string, body: Record<string, unknown>): [number, unknown] => {
|
|
||||||
if (url === '/api/auth/me') return [200, { user: USER }]
|
|
||||||
if (url === '/api/auth/logout') return [200, {}]
|
|
||||||
if (url === '/api/me/projects') return [200, { projects: [...saves.values()].map(s => s.meta), deleted: [] }]
|
|
||||||
const [, id, rest] = url.match(/^\/api\/me\/projects\/([^/]+)(.*)$/) ?? []
|
|
||||||
if (!id) return [404, {}]
|
|
||||||
const save = saves.get(id)
|
|
||||||
if (rest === '' && method === 'GET') return save ? [200, { project: copy(save.project) }] : [404, {}]
|
|
||||||
if (rest === '' && method === 'PUT') {
|
|
||||||
if (save && save.meta.rev !== body.baseRev && body.force !== true) return [409, { conflict: true, meta: save.meta }]
|
|
||||||
return [200, { meta: put(id, body.project as Project) }]
|
|
||||||
}
|
|
||||||
if (rest === '/versions' && method === 'POST') return [200, keep(id, toProject(copy(body.project)))]
|
|
||||||
if (rest === '/versions') return [200, { versions: (versions.get(id) ?? []).map(x => ({ v: x.v, at: x.v, rev: 0, name: x.project.name, size: 0 })) }]
|
|
||||||
const v = versions.get(id)?.find(x => `/versions/${x.v}` === rest)
|
|
||||||
return v ? [200, { version: { project: copy(v.project) } }] : [404, {}]
|
|
||||||
}
|
|
||||||
vi.stubGlobal('fetch', async (url: string, init: { method?: string; body?: string } = {}) => {
|
|
||||||
const [status, data] = route(init.method ?? 'GET', url, init.body ? JSON.parse(init.body) : {})
|
|
||||||
return { ok: status < 400, status, json: async () => data }
|
|
||||||
})
|
|
||||||
setCachedAccount(USER)
|
|
||||||
return { saves, versions, put }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Lets the timers due in `ms` run, and the requests they start finish. */
|
|
||||||
async function wait(ms: number) {
|
|
||||||
await vi.advanceTimersByTimeAsync(ms)
|
|
||||||
await new Promise(r => setImmediate(r))
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
store = new Map()
|
|
||||||
vi.stubGlobal('localStorage', {
|
|
||||||
getItem: (k: string) => store.get(k) ?? null,
|
|
||||||
setItem: (k: string, v: string) => void store.set(k, String(v)),
|
|
||||||
removeItem: (k: string) => void store.delete(k),
|
|
||||||
})
|
|
||||||
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'] })
|
|
||||||
})
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
vi.useRealTimers()
|
|
||||||
vi.unstubAllGlobals()
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('the editor keeping what circuits hold', () => {
|
|
||||||
it('keeps a bit set with buttons when you go into a component and come back, and after a reload', async () => {
|
|
||||||
stored(latchProject())
|
|
||||||
let tab = await openTab()
|
|
||||||
expect(tab.q()).toBe(0)
|
|
||||||
tab.push('S')
|
|
||||||
expect(tab.q()).toBe(1)
|
|
||||||
tab.ed.open('ex-sr')
|
|
||||||
tab.ed.back()
|
|
||||||
expect(tab.q()).toBe(1)
|
|
||||||
tab.ed.open('ex-sr')
|
|
||||||
tab.ed.goMain()
|
|
||||||
tab.ed.goTo(0)
|
|
||||||
tab.ed.open('mem')
|
|
||||||
expect(tab.q()).toBe(1)
|
|
||||||
tab.push('R')
|
|
||||||
tab.push('S')
|
|
||||||
tab.close()
|
|
||||||
tab = await openTab()
|
|
||||||
expect(tab.q()).toBe(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('does not mix the bits of two projects with the same circuits', async () => {
|
|
||||||
const a = stored(latchProject())
|
|
||||||
const b = { ...a, id: 'p2', name: 'Other' }
|
|
||||||
saveProject(b, latchProject())
|
|
||||||
setCurrentId(a.id)
|
|
||||||
const tab = await openTab()
|
|
||||||
tab.push('S')
|
|
||||||
tab.ed.switchProject(b.id)
|
|
||||||
expect(tab.q()).toBe(0)
|
|
||||||
tab.ed.switchProject(a.id)
|
|
||||||
expect(tab.q()).toBe(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('saves the bits of the circuit used last, and drops the oldest when there are too many', async () => {
|
|
||||||
const p = latchProject()
|
|
||||||
const filler = { names: [], on: 'x'.repeat(300_000) }
|
|
||||||
p.state = { main: filler, 'ex-sr': filler }
|
|
||||||
stored(p)
|
|
||||||
const tab = await openTab()
|
|
||||||
tab.push('S')
|
|
||||||
tab.ed.persist()
|
|
||||||
await wait(300)
|
|
||||||
const saved = loadProject('p1')!
|
|
||||||
expect(Object.keys(saved.state!)).toEqual(['ex-sr', 'mem'])
|
|
||||||
expect(bitOf(saved)).toBe(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('says so once when a circuit holds more bits than a project keeps, and starts it from 0', async () => {
|
|
||||||
stored(latchProject())
|
|
||||||
const tab = await openTab()
|
|
||||||
// The editor's own limits: a room so small that one latch is already too much.
|
|
||||||
const { LIMITS } = await import('../app/lib/logic/project')
|
|
||||||
LIMITS.state = 10
|
|
||||||
tab.push('S')
|
|
||||||
tab.ed.open('ex-sr')
|
|
||||||
expect(tab.ed.notice.value).toEqual({ text: expect.stringContaining('too many bits'), kind: 'error' })
|
|
||||||
tab.ed.back()
|
|
||||||
expect(tab.q()).toBe(0)
|
|
||||||
tab.ed.notice.value = null
|
|
||||||
tab.push('S')
|
|
||||||
tab.ed.open('ex-sr')
|
|
||||||
tab.ed.back()
|
|
||||||
expect(tab.ed.notice.value).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('takes the bits of a newer save from another computer, also for the circuit that is open', async () => {
|
|
||||||
const server = account()
|
|
||||||
// Here: revision 1, the latch at 0. The other computer saved revision 2 with the latch at 1.
|
|
||||||
stored(latchProject(), { cloud: { owner: USER.id, rev: 1 } })
|
|
||||||
server.put('p1', latchProject())
|
|
||||||
server.put('p1', setElsewhere(latchProject()))
|
|
||||||
const tab = await openTab()
|
|
||||||
expect(tab.q()).toBe(0)
|
|
||||||
await tab.ed.startAccount()
|
|
||||||
expect(tab.q()).toBe(1)
|
|
||||||
// The next save here keeps that 1 instead of writing this computer's old 0 over it.
|
|
||||||
await tab.ed.saveNow()
|
|
||||||
expect(server.saves.get('p1')!.meta.rev).toBe(3)
|
|
||||||
expect(bitOf(server.saves.get('p1')!.project)).toBe(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('brings back the bits of a savegame, so Power off and on can be undone', async () => {
|
|
||||||
const server = account()
|
|
||||||
stored(latchProject())
|
|
||||||
const tab = await openTab()
|
|
||||||
await tab.ed.startAccount()
|
|
||||||
tab.push('S')
|
|
||||||
await tab.ed.saveNow()
|
|
||||||
tab.ed.resetState()
|
|
||||||
expect(tab.q()).toBe(0)
|
|
||||||
await tab.ed.saveNow()
|
|
||||||
expect(bitOf(server.saves.get('p1')!.project)).toBe(0)
|
|
||||||
const before = server.versions.get('p1')!.at(-1)!
|
|
||||||
expect(bitOf(before.project)).toBe(1)
|
|
||||||
await tab.ed.restoreVersion('p1', before.v, false)
|
|
||||||
expect(tab.q()).toBe(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('sends bits set with buttons to the account when the page is left, not before', async () => {
|
|
||||||
const server = account()
|
|
||||||
stored(latchProject())
|
|
||||||
const tab = await openTab()
|
|
||||||
await tab.ed.startAccount()
|
|
||||||
tab.push('S')
|
|
||||||
// A running page writes the bits only to this browser.
|
|
||||||
await wait(61_000)
|
|
||||||
expect(bitOf(loadProject('p1')!)).toBe(1)
|
|
||||||
expect(server.saves.get('p1')!.meta.rev).toBe(1)
|
|
||||||
tab.hide()
|
|
||||||
await wait(2_000)
|
|
||||||
expect(server.saves.get('p1')!.meta.rev).toBe(2)
|
|
||||||
expect(bitOf(server.saves.get('p1')!.project)).toBe(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('lets an edit saved on another computer win over bits changed here', async () => {
|
|
||||||
const server = account()
|
|
||||||
stored(latchProject())
|
|
||||||
const tab = await openTab()
|
|
||||||
await tab.ed.startAccount()
|
|
||||||
tab.push('S')
|
|
||||||
await wait(5_000)
|
|
||||||
const edited = latchProject()
|
|
||||||
edited.name = 'Edited elsewhere'
|
|
||||||
server.put('p1', edited)
|
|
||||||
tab.hide()
|
|
||||||
await wait(2_000)
|
|
||||||
expect(tab.ed.project.value.name).toBe('Edited elsewhere')
|
|
||||||
expect(server.saves.get('p1')!.project.name).toBe('Edited elsewhere')
|
|
||||||
// The bits of this computer are in the project's savegames.
|
|
||||||
expect(bitOf(server.versions.get('p1')!.at(-1)!.project)).toBe(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('marks bits for the account when you leave the project, as no edit', async () => {
|
|
||||||
const a = stored(latchProject())
|
|
||||||
saveProject({ ...a, id: 'p2', name: 'Other' }, latchProject())
|
|
||||||
setCurrentId(a.id)
|
|
||||||
const tab = await openTab()
|
|
||||||
tab.push('S')
|
|
||||||
await wait(5_000)
|
|
||||||
tab.ed.switchProject('p2')
|
|
||||||
const left = listProjects().find(m => m.id === a.id)!
|
|
||||||
expect(left.dirty).toBe(true)
|
|
||||||
expect(left.updated).toBe(a.updated)
|
|
||||||
expect(bitOf(loadProject(a.id)!)).toBe(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keeps bits set with buttons when signing out and removing the projects from this browser', async () => {
|
|
||||||
const server = account()
|
|
||||||
stored(latchProject())
|
|
||||||
const tab = await openTab()
|
|
||||||
await tab.ed.startAccount()
|
|
||||||
tab.push('S')
|
|
||||||
await tab.ed.signOut(true)
|
|
||||||
expect(listProjects().some(m => m.id === 'p1')).toBe(false)
|
|
||||||
expect(bitOf(server.saves.get('p1')!.project)).toBe(1)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('keeps the bits of the project it leaves when a savegame opens as a copy', async () => {
|
|
||||||
const server = account()
|
|
||||||
stored(latchProject())
|
|
||||||
const tab = await openTab()
|
|
||||||
await tab.ed.startAccount()
|
|
||||||
tab.push('S')
|
|
||||||
server.put('p9', createProject({ examples: false }))
|
|
||||||
server.put('p9', createProject({ examples: false }))
|
|
||||||
await tab.ed.restoreVersion('p9', server.versions.get('p9')![0]!.v, true)
|
|
||||||
expect(tab.ed.meta.value.id).not.toBe('p1')
|
|
||||||
expect(bitOf(loadProject('p1')!)).toBe(1)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue