LogicSim: logic-gate simulator model, save/load, example circuits, tests

This commit is contained in:
4DBug committed 2026-10-17 06:15:35 -05:00
1 parent ad9af52825
commit 53d4cfba75
4 files changed
+342 -3

No files matched your search

+2 -1
View File
@@ -4,7 +4,8 @@
"$className": "DataModel",
"ReplicatedStorage": {
"ImGui": { "$path": "tools/core/build/ImGuiTyped.luau", "Impl": { "$path": "tools/core/build/ImGui.luau" } },
"ImNodes": { "$path": "ImNodes.lua" }
"ImNodes": { "$path": "ImNodes.lua" },
"LogicSim": { "$path": "examples/roblox/LogicSim.lua" }
},
"StarterPlayer": { "StarterPlayerScripts": { "ImNodesExample": { "$path": "examples/roblox/main.client.luau" } } }
}
+253
View File
@@ -0,0 +1,253 @@
-- Logic-gate simulator model (no UI). Usage: local LogicSim = require(RS.LogicSim)(G, ImNodes)
-- Pin ids: node.Id * 16 + slot; inputs use slots 0..7, outputs 8..15.
return function(G, ImNodes)
local LogicSim = {}
local MAX_PASSES = 16
local function b(x)
return x and 1 or 0
end
local function gate(f)
return { ins = { "A", "B" }, outs = { "Out" }, eval = function(i)
return { b(f(i[1] == 1, i[2] == 1)) }
end }
end
-- kind -> { ins = names, outs = names, eval = function(inputs, state) -> outputs }
LogicSim.Kinds = {
Switch = { ins = {}, outs = { "Out" }, eval = function(_, s) return { s.on and 1 or 0 } end },
Clock = { ins = {}, outs = { "Out" }, eval = function(_, s) return { s.on and 1 or 0 } end },
Const0 = { ins = {}, outs = { "Out" }, eval = function() return { 0 } end },
Const1 = { ins = {}, outs = { "Out" }, eval = function() return { 1 } end },
AND = gate(function(a, c) return a and c end),
OR = gate(function(a, c) return a or c end),
NAND = gate(function(a, c) return not (a and c) end),
NOR = gate(function(a, c) return not (a or c) end),
XOR = gate(function(a, c) return a ~= c end),
XNOR = gate(function(a, c) return a == c end),
NOT = { ins = { "In" }, outs = { "Out" }, eval = function(i) return { 1 - i[1] } end },
LED = { ins = { "In" }, outs = {}, eval = function(i, s) s.on = i[1] == 1; return {} end },
HexDisplay = { ins = { "1", "2", "4", "8" }, outs = {}, eval = function(i, s)
s.value = i[1] + 2 * i[2] + 4 * i[3] + 8 * i[4]
return {}
end },
DFlipFlop = { ins = { "D", "Clk" }, outs = { "Q", "notQ" }, eval = function(i, s)
if i[2] == 1 and s.prevClk ~= 1 then
s.q = i[1]
end
s.prevClk = i[2]
local q = s.q or 0
return { q, 1 - q }
end },
}
function LogicSim.InPin(nodeId, slot) return nodeId * 16 + slot - 1 end
function LogicSim.OutPin(nodeId, slot) return nodeId * 16 + 8 + slot - 1 end
function LogicSim.PinNode(pin) return pin // 16, pin % 16 >= 8, pin % 8 + 1 end -- nodeId, isOutput, slot
function LogicSim.New()
return { nodes = {}, order = {}, links = {}, values = {}, nextNode = 1, nextLink = 1 }
end
function LogicSim.AddNode(g, kind, x, y, state, id)
assert(LogicSim.Kinds[kind], kind)
id = id or g.nextNode
g.nextNode = math.max(g.nextNode, id + 1)
local n = { Id = id, Kind = kind, Pos = { x or 0, y or 0 }, state = state or {} }
if kind == "Clock" then n.state.rate = n.state.rate or 1 end
g.nodes[id] = n
table.insert(g.order, id)
return n
end
function LogicSim.RemoveNode(g, id)
g.nodes[id] = nil
table.remove(g.order, table.find(g.order, id))
for lid, l in g.links do
if l.Start // 16 == id or l.End // 16 == id then g.links[lid] = nil end
end
end
-- start = output pin, end = input pin (swapped if given reversed). An input takes one link; returns link id or nil.
function LogicSim.AddLink(g, a, c, id)
if select(2, LogicSim.PinNode(a)) == false then a, c = c, a end
if not select(2, LogicSim.PinNode(a)) or select(2, LogicSim.PinNode(c)) then return nil end
for lid, l in g.links do
if l.End == c then g.links[lid] = nil end
end
id = id or g.nextLink
g.nextLink = math.max(g.nextLink, id + 1)
g.links[id] = { Id = id, Start = a, End = c }
return id
end
function LogicSim.RemoveLink(g, id) g.links[id] = nil end
function LogicSim.Connect(g, from, fromSlot, to, toSlot)
return LogicSim.AddLink(g, LogicSim.OutPin(from.Id, fromSlot or 1), LogicSim.InPin(to.Id, toSlot or 1))
end
function LogicSim.Value(g, pin) return g.values[pin] or 0 end
-- Advance clocks by dt, then propagate (Gauss-Seidel in node order, capped passes for feedback loops).
function LogicSim.Step(g, dt)
for _, id in g.order do
local n = g.nodes[id]
if n.Kind == "Clock" then
local s = n.state
s.t = (s.t or 0) + (dt or 0)
local half = 0.5 / s.rate
while s.t >= half do s.t -= half; s.on = not s.on end
end
end
local src = {}
for _, l in g.links do src[l.End] = l.Start end
for _ = 1, MAX_PASSES do
local changed = false
for _, id in g.order do
local n = g.nodes[id]
local k = LogicSim.Kinds[n.Kind]
local ins = {}
for i = 1, #k.ins do
local s = src[LogicSim.InPin(id, i)]
ins[i] = s and g.values[s] or 0
end
for i, v in k.eval(ins, n.state) do
local p = LogicSim.OutPin(id, i)
if g.values[p] ~= v then g.values[p] = v; changed = true end
end
end
if not changed then break end
end
end
-- Text format: "N id kind x y key=val,...", "L id start end", "V pin value", then "INI" line followed by ImNodes ini (if a context exists).
function LogicSim.Save(g)
local out = {}
for _, id in g.order do
local n = g.nodes[id]
local kv = {}
for k, v in n.state do
if type(v) ~= "table" then table.insert(kv, `{k}={v}`) end
end
table.sort(kv)
table.insert(out, `N {id} {n.Kind} {n.Pos[1]} {n.Pos[2]} {table.concat(kv, ",")}`)
end
local lids = {}
for lid in g.links do table.insert(lids, lid) end
table.sort(lids)
for _, lid in lids do
local l = g.links[lid]
table.insert(out, `L {lid} {l.Start} {l.End}`)
end
local pins = {} -- output values carry feedback memory (latches)
for pin, v in g.values do
if v ~= 0 then table.insert(pins, pin) end
end
table.sort(pins)
for _, pin in pins do table.insert(out, `V {pin} {g.values[pin]}`) end
if ImNodes and ImNodes.GetCurrentContext() then
table.insert(out, "INI")
table.insert(out, ImNodes.SaveCurrentEditorStateToIniString())
end
return table.concat(out, "\n")
end
function LogicSim.Load(s)
local g = LogicSim.New()
local graphPart, ini = s, nil
local at = string.find(s, "\nINI\n", 1, true)
if at then graphPart, ini = string.sub(s, 1, at - 1), string.sub(s, at + 5) end
for line in string.gmatch(graphPart, "[^\n]+") do
local id, kind, x, y, kv = string.match(line, "^N (%d+) (%w+) (%S+) (%S+) ?(.*)$")
if id then
local st = {}
for k, v in string.gmatch(kv, "(%w+)=([^,]+)") do
st[k] = if v == "true" then true elseif v == "false" then false else tonumber(v) or v
end
LogicSim.AddNode(g, kind, tonumber(x), tonumber(y), st, tonumber(id))
else
local lid, a, c = string.match(line, "^L (%d+) (%d+) (%d+)$")
if lid then LogicSim.AddLink(g, tonumber(a), tonumber(c), tonumber(lid)) end
local pin, v = string.match(line, "^V (%d+) (%d+)$")
if pin then g.values[tonumber(pin)] = tonumber(v) end
end
end
if ini and ImNodes and ImNodes.GetCurrentContext() then
ImNodes.LoadCurrentEditorStateFromIniString(ini)
end
return g
end
-- Example builders: each returns a fresh graph plus named nodes.
LogicSim.Examples = {}
local add, con = LogicSim.AddNode, LogicSim.Connect
function LogicSim.Examples.HalfAdder()
local g = LogicSim.New()
local a, c = add(g, "Switch", 0, 0), add(g, "Switch", 0, 100)
local x, n = add(g, "XOR", 200, 0), add(g, "AND", 200, 100)
local sum, carry = add(g, "LED", 400, 0), add(g, "LED", 400, 100)
con(g, a, 1, x, 1); con(g, c, 1, x, 2); con(g, a, 1, n, 1); con(g, c, 1, n, 2)
con(g, x, 1, sum); con(g, n, 1, carry)
return g, { A = a, B = c, Sum = sum, Carry = carry }
end
-- Adds a full adder's gates to g; returns xor2 (sum) and or (carry) nodes. Inputs: wire to x1(A,B) and cin via setter.
local function fullAdder(g, a, bb, cin, ox, oy)
local x1, x2 = add(g, "XOR", ox, oy), add(g, "XOR", ox + 150, oy)
local a1, a2, o = add(g, "AND", ox, oy + 80), add(g, "AND", ox + 150, oy + 80), add(g, "OR", ox + 300, oy + 80)
con(g, a, 1, x1, 1); con(g, bb, 1, x1, 2); con(g, a, 1, a1, 1); con(g, bb, 1, a1, 2)
con(g, x1, 1, x2, 1); con(g, cin, 1, x2, 2); con(g, x1, 1, a2, 1); con(g, cin, 1, a2, 2)
con(g, a1, 1, o, 1); con(g, a2, 1, o, 2)
return x2, o
end
function LogicSim.Examples.FullAdder()
local g = LogicSim.New()
local a, c, cin = add(g, "Switch", 0, 0), add(g, "Switch", 0, 100), add(g, "Switch", 0, 200)
local s, co = fullAdder(g, a, c, cin, 200, 0)
local sum, carry = add(g, "LED", 650, 0), add(g, "LED", 650, 100)
con(g, s, 1, sum); con(g, co, 1, carry)
return g, { A = a, B = c, Cin = cin, Sum = sum, Carry = carry }
end
function LogicSim.Examples.RippleAdder4()
local g = LogicSim.New()
local A, B = {}, {}
for i = 1, 4 do
A[i] = add(g, "Switch", 0, (i - 1) * 200)
B[i] = add(g, "Switch", 0, (i - 1) * 200 + 100)
end
local hex = add(g, "HexDisplay", 900, 0)
local carry = add(g, "Const0", 0, -100)
for i = 1, 4 do
local s
s, carry = fullAdder(g, A[i], B[i], carry, 200, (i - 1) * 200)
con(g, s, 1, hex, i)
end
local cout = add(g, "LED", 900, 200)
con(g, carry, 1, cout)
return g, { A = A, B = B, Hex = hex, Carry = cout }
end
function LogicSim.Examples.SRLatch()
local g = LogicSim.New()
local s, r = add(g, "Switch", 0, 0), add(g, "Switch", 0, 150)
local n1, n2 = add(g, "NOR", 200, 0), add(g, "NOR", 200, 150)
local q, nq = add(g, "LED", 400, 0), add(g, "LED", 400, 150)
con(g, r, 1, n1, 1); con(g, n2, 1, n1, 2) -- n1 = Q
con(g, s, 1, n2, 1); con(g, n1, 1, n2, 2) -- n2 = notQ
con(g, n1, 1, q); con(g, n2, 1, nq)
return g, { S = s, R = r, Q = q, NotQ = nq }
end
function LogicSim.Examples.Blinker()
local g = LogicSim.New()
local clk, led = add(g, "Clock", 0, 0, { rate = 2 }), add(g, "LED", 200, 0)
con(g, clk, 1, led)
return g, { Clock = clk, LED = led }
end
return LogicSim
end
+85
View File
@@ -0,0 +1,85 @@
local RS = game:GetService("ReplicatedStorage")
local G = require(RS:WaitForChild("ImGui"))
local ImNodes = require(RS:WaitForChild("ImNodes"))(G)
local L = require(RS:WaitForChild("LogicSim"))(G, ImNodes)
local function out(g, n) return L.Value(g, L.OutPin(n.Id, 1)) end
local function inp(g, n) -- value driving input 1 of a sink (via its LED state)
return g.nodes[n.Id].state.on and 1 or 0
end
-- full adder truth table
local g, n = L.Examples.FullAdder()
for v = 0, 7 do
local a, b, c = v % 2, (v // 2) % 2, (v // 4) % 2
n.A.state.on, n.B.state.on, n.Cin.state.on = a == 1, b == 1, c == 1
L.Step(g, 0)
local s = a + b + c
assert(inp(g, n.Sum) == s % 2 and inp(g, n.Carry) == s // 2, `fa {a}{b}{c}`)
end
-- ripple adder 4-bit
g, n = L.Examples.RippleAdder4()
for _, ab in { { 5, 9 }, { 15, 1 }, { 7, 7 } } do
for i = 1, 4 do
n.A[i].state.on = (ab[1] // 2 ^ (i - 1)) % 2 == 1
n.B[i].state.on = (ab[2] // 2 ^ (i - 1)) % 2 == 1
end
L.Step(g, 0)
local s = ab[1] + ab[2]
assert(n.Hex.state.value == s % 16 and inp(g, n.Carry) == s // 16, `ripple {ab[1]}+{ab[2]}`)
end
-- SR latch holds
g, n = L.Examples.SRLatch()
n.S.state.on = true; L.Step(g, 0)
n.S.state.on = false; L.Step(g, 0)
assert(inp(g, n.Q) == 1 and inp(g, n.NotQ) == 0, "set holds")
n.R.state.on = true; L.Step(g, 0)
n.R.state.on = false; L.Step(g, 0)
assert(inp(g, n.Q) == 0 and inp(g, n.NotQ) == 1, "reset holds")
-- D flip-flop rising edge
g = L.New()
local d, clk, ff = L.AddNode(g, "Switch"), L.AddNode(g, "Switch"), L.AddNode(g, "DFlipFlop")
L.Connect(g, d, 1, ff, 1); L.Connect(g, clk, 1, ff, 2)
local function q() return L.Value(g, L.OutPin(ff.Id, 1)) end
d.state.on = true; L.Step(g, 0)
assert(q() == 0, "no edge yet")
clk.state.on = true; L.Step(g, 0)
assert(q() == 1 and L.Value(g, L.OutPin(ff.Id, 2)) == 0, "latched on rise")
d.state.on = false; L.Step(g, 0)
assert(q() == 1, "holds while clk high")
clk.state.on = false; L.Step(g, 0)
assert(q() == 1, "falling edge ignored")
clk.state.on = true; L.Step(g, 0)
assert(q() == 0, "second rise")
-- blinker toggles
g, n = L.Examples.Blinker()
L.Step(g, 0.3)
assert(inp(g, n.LED) == 1, "blink on")
L.Step(g, 0.25)
assert(inp(g, n.LED) == 0, "blink off")
-- save -> clear -> load round trip (no ImNodes context: graph only)
g, n = L.Examples.SRLatch()
n.S.state.on = true; L.Step(g, 0); n.S.state.on = false; L.Step(g, 0)
local saved = L.Save(g)
g = nil
local g2 = L.Load(saved)
L.Step(g2, 0)
assert(g2.nodes[n.Q.Id].state.on == true and L.Save(g2) == saved, "round trip")
g2.nodes[n.R.Id].state.on = true; L.Step(g2, 0) -- loaded graph still evaluates
g2.nodes[n.R.Id].state.on = false; L.Step(g2, 0)
assert(g2.nodes[n.Q.Id].state.on == false and g2.nodes[n.NotQ.Id].state.on == true, "loaded latch resets")
-- with ImNodes context: ini embedded and restored
ImNodes.CreateContext()
local s2 = L.Save(g2)
assert(string.find(s2, "\nINI\n", 1, true), "ini section")
local g3 = L.Load(s2)
L.Step(g3, 0)
assert(L.Save(g3) == s2, "round trip with ini\n" .. s2 .. "\n---\n" .. L.Save(g3))
ImNodes.DestroyContext()
print("OK")
+2 -2
View File
@@ -3,11 +3,11 @@
cd "$(dirname "$0")/.."
fail=0
for t in tests/t_*.luau; do
out=$(python3 tools/core/tools/test/run.py --module ImNodes=ImNodes.lua --main "$t" --quiet --roblox 2>&1)
out=$(python3 tools/core/tools/test/run.py --module ImNodes=ImNodes.lua --module LogicSim=examples/roblox/LogicSim.lua --main "$t" --quiet --roblox 2>&1)
if echo "$out" | grep -q "^OK"; then echo "PASS $t"; else echo "FAIL $t"; echo "$out" | tail -20; fail=1; fi
done
# example LocalScript: 400 frames of random input (mock drives Stepped, not RenderStepped)
ex=$(mktemp --suffix=.luau); sed 's/RenderStepped/Stepped/' examples/roblox/main.client.luau > "$ex"
out=$(python3 tools/core/tools/test/run.py --module ImNodes=ImNodes.lua --main "$ex" --roblox 2>&1); rm -f "$ex"
out=$(python3 tools/core/tools/test/run.py --module ImNodes=ImNodes.lua --module LogicSim=examples/roblox/LogicSim.lua --main "$ex" --roblox 2>&1); rm -f "$ex"
if echo "$out" | grep -q "^avg frame"; then echo "PASS examples/roblox/main.client.luau"; else echo "FAIL examples/roblox/main.client.luau"; echo "$out" | tail -20; fail=1; fi
exit $fail