Modern Apps git

← Modern-Apps.git

logicgate: fix canvas

Commit
455fada1a4bd5b901d08e1193fe9f73a72f107c4
Author
Vayun Mathur <[email protected]>
When
2026-07-23 22:50 UTC (4 months ago)
Parents
178dff1

Diff

games/logicgate/src/main/assets/achievements.json
diff --git a/games/logicgate/src/main/assets/achievements.json b/games/logicgate/src/main/assets/achievements.jsonindex d5b3ccc027..1a5a41ca8e 100644--- a/games/logicgate/src/main/assets/achievements.json+++ b/games/logicgate/src/main/assets/achievements.json@@ -1,9 +1,9 @@ [   {"id": "first_gate", "name": "First Light", "description": "Complete your first gate"},   {"id": "foundation_complete", "name": "Foundation", "description": "Complete Foundation chapter (6 levels)", "targetProgress": 6},-  {"id": "routing_complete", "name": "Router", "description": "Complete Routing chapter (3 levels)", "targetProgress": 3},-  {"id": "arith_complete", "name": "Arithmetician", "description": "Complete Arithmetic chapter (4 levels)", "targetProgress": 4},-  {"id": "memory_complete", "name": "Mnemosyne", "description": "Complete Memory chapter (3 levels)", "targetProgress": 3},-  {"id": "cpu_complete", "name": "CPU Architect", "description": "Complete CPU chapter (2 levels)", "targetProgress": 2},-  {"id": "all_levels", "name": "NAND to CPU", "description": "Complete all 18 levels and build the 8-bit CPU", "targetProgress": 18}+  {"id": "routing_complete", "name": "Router", "description": "Complete Routing chapter (12 levels)", "targetProgress": 12},+  {"id": "arith_complete", "name": "Arithmetician", "description": "Complete Arithmetic chapter (6 levels)", "targetProgress": 6},+  {"id": "memory_complete", "name": "Mnemosyne", "description": "Complete Memory chapter (8 levels)", "targetProgress": 8},+  {"id": "cpu_complete", "name": "CPU Architect", "description": "Complete CPU chapter (4 levels)", "targetProgress": 4},+  {"id": "all_levels", "name": "NAND to CPU", "description": "Complete all 36 levels and build the stored-program computer", "targetProgress": 36} ]
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.ktindex eb8a2fbe3b..a805ddd71a 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/MainActivity.kt@@ -20,8 +20,6 @@ import androidx.compose.ui.layout.positionInRoot import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel-import com.vayunmathur.games.logicgate.data.ChipLibrary-import com.vayunmathur.games.logicgate.data.Levels import com.vayunmathur.games.logicgate.ui.CircuitCanvas import com.vayunmathur.games.logicgate.ui.InventoryBar import com.vayunmathur.games.logicgate.ui.LogicGateTheme@@ -84,7 +82,7 @@ fun Navigation(viewModel: LogicViewModel) { @OptIn(ExperimentalMaterial3Api::class) @Composable fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelId: String) {-    val level = Levels.get(levelId)+    val level = com.vayunmathur.games.logicgate.data.Levels.get(levelId)     val uiState by viewModel.uiState.collectAsState()     val unlocked by viewModel.unlockedChips.collectAsState()     val completed by viewModel.completedIds.collectAsState()@@ -103,6 +101,8 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI                 navigationIcon = { IconNavigation(backStack) },                 actions = {                     Row(modifier = Modifier.padding(end = 6.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {+                        if (uiState.canUndo) Button(onClick = { viewModel.undo() }) { Text(text = "Undo", fontSize = 10.sp) }+                        if (uiState.canRedo) Button(onClick = { viewModel.redo() }) { Text(text = "Redo", fontSize = 10.sp) }                         Button(onClick = { viewModel.toggleTruthTable() }) { Text(text = if (uiState.showTruthTable) "Hide TT" else "Show TT", fontSize = 10.sp) }                     }                 }@@ -124,7 +124,6 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI                     onChipDrop = { chipId, global ->                         val local = Offset(global.x - canvasRect.left, global.y - canvasRect.top)                         if (canvasRect.contains(global)) {-                            // Free placement – wherever finger lifted, no grid snap                             viewModel.addGateAt(chipId, local.x, local.y)                         }                         draggingChipId = null@@ -145,8 +144,8 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI                 is EvalStatus.Ok -> if (s.isFullyCorrect) "✓ CORRECT — ${level.unlocksChipId?.let { "Unlocked $it!" } ?: "Done!"}"                 else "${s.passingRows}/${s.totalRows} passing — ${s.failingRows.size} failing"                 is EvalStatus.Error -> "Error: ${s.msg}"-                is EvalStatus.Cycle -> "Cycle: ${s.ids.take(3).joinToString()}"-                else -> "Drag chip onto board to place • Drag gates & I/O to move • Drag output dot → input dot to wire • Tap wire to delete • Long-press gate to delete"+                is EvalStatus.Cycle -> "Cycle: ${s.ids.take(3).joinToString()} — SR_LATCH needs 2 NOR cross-coupled feedback"+                else -> "Drag chip onto board • Drag gates & I/O to move • Drag output dot → input dot to wire • Tap wire to delete • Long-press gate to delete • Undo/Redo in top bar"             }             val statusColor = when {                 uiState.evalStatus is EvalStatus.Ok && (uiState.evalStatus as EvalStatus.Ok).isFullyCorrect -> Color(0xFF22C55E)@@ -169,7 +168,6 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI                 }             } -            // Canvas container – NO scroll wrapper that would steal drags. Full freeform.             BoxWithConstraints(modifier = Modifier.weight(1f).fillMaxWidth()) {                 val wide = maxWidth > maxHeight                 Box(@@ -193,8 +191,11 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI                                     onStartWiring = { viewModel.startWiring(it) },                                     onCancelWiring = { viewModel.cancelWiring() },                                     onGateMove = { id, x, y -> viewModel.onGateMoved(id, x, y) },+                                    onGateMoveFinished = { id, x, y -> viewModel.onGateMoveFinished(id, x, y) },                                     onInputTermMove = { idx, x, y -> viewModel.onInputMoved(idx, x, y) },+                                    onInputTermMoveFinished = { idx, x, y -> viewModel.onInputMoveFinished(idx, x, y) },                                     onOutputTermMove = { idx, x, y -> viewModel.onOutputMoved(idx, x, y) },+                                    onOutputTermMoveFinished = { idx, x, y -> viewModel.onOutputMoveFinished(idx, x, y) },                                     onGateDelete = { viewModel.removeGate(it) },                                     onWireDelete = { viewModel.removeWire(it) },                                     onOutputMapDelete = { viewModel.removeOutputMapping(it) },@@ -205,14 +206,14 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI                             }                             if (uiState.showTruthTable) {                                 val failing = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows ?: emptyList()-                                TruthTableView(level, failing, modifier = Modifier.width(210.dp).fillMaxHeight().background(Color(0xFF0E141B)))+                                TruthTableView(level, failing, modifier = Modifier.width(260.dp).fillMaxHeight().background(Color(0xFF0E141B)))                             }                         }                     } else {                         Column(modifier = Modifier.fillMaxSize()) {                             if (uiState.showTruthTable) {                                 val failing = (uiState.evalStatus as? EvalStatus.Ok)?.failingRows ?: emptyList()-                                TruthTableView(level, failing, modifier = Modifier.fillMaxWidth().height(180.dp).background(Color(0xFF0E141B)))+                                TruthTableView(level, failing, modifier = Modifier.fillMaxWidth().height(200.dp).background(Color(0xFF0E141B)))                             }                             Box(modifier = Modifier.weight(1f).fillMaxWidth()) {                                 CircuitCanvas(@@ -227,8 +228,11 @@ fun GameScreen(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelI                                     onStartWiring = { viewModel.startWiring(it) },                                     onCancelWiring = { viewModel.cancelWiring() },                                     onGateMove = { id, x, y -> viewModel.onGateMoved(id, x, y) },+                                    onGateMoveFinished = { id, x, y -> viewModel.onGateMoveFinished(id, x, y) },                                     onInputTermMove = { idx, x, y -> viewModel.onInputMoved(idx, x, y) },+                                    onInputTermMoveFinished = { idx, x, y -> viewModel.onInputMoveFinished(idx, x, y) },                                     onOutputTermMove = { idx, x, y -> viewModel.onOutputMoved(idx, x, y) },+                                    onOutputTermMoveFinished = { idx, x, y -> viewModel.onOutputMoveFinished(idx, x, y) },                                     onGateDelete = { viewModel.removeGate(it) },                                     onWireDelete = { viewModel.removeWire(it) },                                     onOutputMapDelete = { viewModel.removeOutputMapping(it) },
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ChipLibrary.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ChipLibrary.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ChipLibrary.ktindex af2ab8f2d7..b8cc776c8d 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ChipLibrary.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ChipLibrary.kt@@ -1,21 +1,9 @@ package com.vayunmathur.games.logicgate.data  /**- * Chip library with multi-bit BUS support.- *- * Wire widths supported: 1-bit (thin green), 4-bit (orange nibble bus), 8-bit (thick blue byte bus),- * plus 2/3/6 for address decode shortcuts. User can work with individual bit wires OR bus wires.- *- * Two zero-cost converters make big levels LESS tedious (you wanted expanders & contractors):- *   JOIN_8 = Expander: 8×1b → BUS8[8] thick – compresses 8 thin into one thick wire (expander)- *   SPLIT_8 = Contractor: BUS8[8] → 8×1b – expands one thick back into bits (contractor)- *   Same for 4-bit: JOIN_4 (expander 4 bits → BUS4[4]) and SPLIT_4 (contractor BUS4→bits)- *   Plus bus MUXes: MUX_B8, MUX4_B8, MUX8_B8, DMUX_B8, DMUX8_B – byte-wide routing with one wire.- *- * Toward stored-program computer (runs programs FROM RAM, von Neumann):- *   Need: SR_LATCH (first 1-bit hold via NOR feedback), DFF edge, BIT (MUX+DFF load), REG_8B bus accumulator,- *         address decode DMUX4/DMUX8 / DMUX8_B bus, INC_8 bus (PC=PC+1), RAM_8B 8×8 → RAM_64B 64×8 → RAM_256B 256×8 main memory unified prog+data,- *         PC_8 bus instruction fetch pointer, ALU_8 bus with zero flag for JZ, CPU bus fetch-decode-execute FROM RAM, COMPUTER final wiring.+ * Bus-enabled chip library.+ * Width 1 = bit thin green 0xFF7ED8B6, 4 = nibble orange 0xFFF59E0B, 8 = byte thick blue 0xFF60A5FA.+ * JOIN = Expander bits->bus thick zero cost, SPLIT = Contractor bus->bits.  */  data class ChipDef(@@ -34,111 +22,78 @@ data class ChipDef(     val outputCount: Int get() = outputs.size     val totalInputBits: Int get() = inputWidths.sum()     val totalOutputBits: Int get() = outputWidths.sum()+    val isSequential: Boolean get() = category == ChipCategory.MEMORY || category == ChipCategory.CPU+    val isBus: Boolean get() = inputWidths.any { it > 1 } || outputWidths.any { it > 1 }     fun inputPinBitOffset(pin: Int): Int = inputWidths.take(pin).sum()     fun outputPinBitOffset(pin: Int): Int = outputWidths.take(pin).sum()     fun inputPinWidth(pin: Int): Int = inputWidths.getOrElse(pin) { 1 }     fun outputPinWidth(pin: Int): Int = outputWidths.getOrElse(pin) { 1 }-    fun inputPinLabel(pin: Int): String { val w=inputPinWidth(pin); return if(w==1) inputs[pin] else "${inputs[pin]}[${w}]" }-    fun outputPinLabel(pin: Int): String { val w=outputPinWidth(pin); return if(w==1) outputs[pin] else "${outputs[pin]}[$w]" }+    fun inputPinLabelFull(pin: Int): String {+        val w = inputPinWidth(pin)+        return if (w == 1) inputs[pin] else "${inputs[pin]}[${w}]"+    }+    fun outputPinLabelFull(pin: Int): String {+        val w = outputPinWidth(pin)+        return if (w == 1) outputs[pin] else "${outputs[pin]}[${w}]"+    }+    fun dominantBusWidth(): Int = (inputWidths + outputWidths).maxOrNull() ?: 1 } -enum class ChipCategory { PRIMITIVE, FOUNDATION, ROUTING, ARITH, MEMORY, CPU, BUS }+enum class ChipCategory { PRIMITIVE, FOUNDATION, ROUTING, BUS, ARITH, MEMORY, CPU }  object ChipLibrary {-    // PRIMITIVE / FOUNDATION – 1-bit-    val NAND = ChipDef("NAND","NAND", listOf("a","b"), listOf("out"),1,"Primitive NOT(AND)",ChipCategory.PRIMITIVE, eval={ inp-> listOf(!(inp[0] && inp[1])) })-    val NOT = ChipDef("NOT","NOT", listOf("in"), listOf("out"),1,"Inverter NAND(in,in)",ChipCategory.FOUNDATION, eval={ inp-> listOf(!inp[0]) })-    val AND = ChipDef("AND","AND", listOf("a","b"), listOf("out"),2,"AND",ChipCategory.FOUNDATION, eval={ inp-> listOf(inp[0] && inp[1]) })-    val OR = ChipDef("OR","OR", listOf("a","b"), listOf("out"),3,"OR",ChipCategory.FOUNDATION, eval={ inp-> listOf(inp[0] || inp[1]) })-    val XOR = ChipDef("XOR","XOR", listOf("a","b"), listOf("out"),4,"XOR key for adder",ChipCategory.FOUNDATION, eval={ inp-> listOf(inp[0] xor inp[1]) })-    val NOR = ChipDef("NOR","NOR", listOf("a","b"), listOf("out"),4,"NOR – cross couple for SR latch",ChipCategory.FOUNDATION, eval={ inp-> listOf(!(inp[0] || inp[1])) })-    val XNOR = ChipDef("XNOR","XNOR", listOf("a","b"), listOf("out"),5,"XNOR equality",ChipCategory.FOUNDATION, eval={ inp-> listOf(!(inp[0] xor inp[1])) })--    // ROUTING bit – address decode blocks needed for RAM-    val MUX = ChipDef("MUX","MUX", listOf("a","b","sel"), listOf("out"),4,"sel?b:a",ChipCategory.ROUTING, eval={ inp-> listOf(if(inp[2]) inp[1] else inp[0]) })-    val DMUX = ChipDef("DMUX","DMUX", listOf("in","sel"), listOf("a","b"),3,"Route in→a|b",ChipCategory.ROUTING, eval={ inp-> val inn=inp[0]; val sel=inp[1]; if(sel) listOf(false,inn) else listOf(inn,false) })-    val MUX4 = ChipDef("MUX4","MUX4", listOf("a","b","c","d","sel0","sel1"), listOf("out"),12,"4-way mux sel1/0",ChipCategory.ROUTING, eval={ inp-> val sel=(if(inp[5])2 else 0)+(if(inp[4])1 else 0); listOf(inp[sel]) })-    val DMUX4 = ChipDef("DMUX4","DMUX4", listOf("in","sel0","sel1"), listOf("a","b","c","d"),8,"DMUX4 address→cell – RAM decode core",ChipCategory.ROUTING, eval={ inp-> val inn=inp[0]; val sel=(if(inp[2])2 else 0)+(if(inp[1])1 else 0); List(4){i-> i==sel && inn} })-    val MUX8 = ChipDef("MUX8","MUX8", listOf("a","b","c","d","e","f","g","h","sel0","sel1","sel2"), listOf("out"),24,"8-way mux – reading RAM",ChipCategory.ROUTING, eval={ inp-> val sel=(if(inp[10])4 else 0)+(if(inp[9])2 else 0)+(if(inp[8])1 else 0); listOf(inp[sel]) })-    val DMUX8 = ChipDef("DMUX8","DMUX8", listOf("in","sel0","sel1","sel2"), listOf("a","b","c","d","e","f","g","h"),16,"8-way demux – write enable for RAM – one addr to one reg",ChipCategory.ROUTING, eval={ inp-> val inn=inp[0]; val sel=(if(inp[3])4 else 0)+(if(inp[2])2 else 0)+(if(inp[1])1 else 0); List(8){i-> i==sel && inn} })+    val NAND = ChipDef("NAND","NAND", listOf("a","b"), listOf("out"),1,"Primitive NOT(AND)",ChipCategory.PRIMITIVE, eval={inp->listOf(!(inp[0]&&inp[1]))})+    val NOT = ChipDef("NOT","NOT", listOf("in"), listOf("out"),1,"NOT=NAND(a,a)",ChipCategory.FOUNDATION, eval={inp->listOf(!inp[0])})+    val AND = ChipDef("AND","AND", listOf("a","b"), listOf("out"),2,"AND",ChipCategory.FOUNDATION, eval={inp->listOf(inp[0]&&inp[1])})+    val OR = ChipDef("OR","OR", listOf("a","b"), listOf("out"),3,"OR",ChipCategory.FOUNDATION, eval={inp->listOf(inp[0]||inp[1])})+    val XOR = ChipDef("XOR","XOR", listOf("a","b"), listOf("out"),4,"XOR",ChipCategory.FOUNDATION, eval={inp->listOf(inp[0] xor inp[1])})+    val NOR = ChipDef("NOR","NOR", listOf("a","b"), listOf("out"),4,"NOR for SR latch",ChipCategory.FOUNDATION, eval={inp->listOf(!(inp[0]||inp[1]))})+    val XNOR = ChipDef("XNOR","XNOR", listOf("a","b"), listOf("out"),5,"XNOR equality",ChipCategory.FOUNDATION, eval={inp->listOf(!(inp[0] xor inp[1]))}) -    // BUS converters – expanders (JOIN = bits→bus thick) / contractors (SPLIT = bus → bits) – cost 0 to cut tedium-    val JOIN_8 = ChipDef("JOIN_8","JOIN8 Expander 8", (0..7).map{"b$it"}, listOf("OUT"),0,"EXPANDER: 8 bits → BUS8[8] thick blue wire – one wire instead of 8 thin",ChipCategory.BUS, inputWidths=List(8){1}, outputWidths=listOf(8), eval={ inp-> inp.take(8) })-    val SPLIT_8 = ChipDef("SPLIT_8","SPLIT8 Contractor 8", listOf("IN"), (0..7).map{"b$it"},0,"CONTRACTOR: BUS8[8] → 8 bits – split thick blue for bit logic",ChipCategory.BUS, inputWidths=listOf(8), outputWidths=List(8){1}, eval={ inp-> inp.take(8) })-    val JOIN_4 = ChipDef("JOIN_4","JOIN4 Exp4", (0..3).map{"b$it"}, listOf("OUT"),0,"EXPANDER: 4 bits→BUS4[4] orange – opcode nibble – less tedious",ChipCategory.BUS, inputWidths=List(4){1}, outputWidths=listOf(4), eval={ inp-> inp.take(4) })-    val SPLIT_4 = ChipDef("SPLIT_4","SPLIT4 Cont4", listOf("IN"), (0..3).map{"b$it"},0,"CONTRACTOR: BUS4[4] → 4 bits – decode opcode bus",ChipCategory.BUS, inputWidths=listOf(4), outputWidths=List(4){1}, eval={ inp-> inp.take(4) })+    val MUX = ChipDef("MUX","MUX", listOf("a","b","sel"), listOf("out"),4,"sel?b:a",ChipCategory.ROUTING, eval={inp->listOf(if(inp[2]) inp[1] else inp[0])})+    val DMUX = ChipDef("DMUX","DMUX", listOf("in","sel"), listOf("a","b"),3,"in->a|b",ChipCategory.ROUTING, eval={inp-> val inn=inp[0]; val sel=inp[1]; if(sel) listOf(false,inn) else listOf(inn,false)})+    val MUX4 = ChipDef("MUX4","MUX4", listOf("a","b","c","d","sel0","sel1"), listOf("out"),12,"4-way mux",ChipCategory.ROUTING, eval={inp-> val sel=(if(inp[5])2 else 0)+(if(inp[4])1 else 0); listOf(inp[sel])})+    val DMUX4 = ChipDef("DMUX4","DMUX4", listOf("in","sel0","sel1"), listOf("a","b","c","d"),8,"Address -> one cell – RAM decoder core",ChipCategory.ROUTING, eval={inp-> val inn=inp[0]; val sel=(if(inp[2])2 else 0)+(if(inp[1])1 else 0); List(4){i-> i==sel && inn}})+    val MUX8 = ChipDef("MUX8","MUX8", listOf("a","b","c","d","e","f","g","h","sel0","sel1","sel2"), listOf("out"),24,"MUX8 RAM read",ChipCategory.ROUTING, eval={inp-> val sel=(if(inp[10])4 else 0)+(if(inp[9])2 else 0)+(if(inp[8])1 else 0); listOf(inp[sel])})+    val DMUX8 = ChipDef("DMUX8","DMUX8", listOf("in","sel0","sel1","sel2"), listOf("a","b","c","d","e","f","g","h"),16,"DMUX8 RAM write decode",ChipCategory.ROUTING, eval={inp-> val inn=inp[0]; val sel=(if(inp[3])4 else 0)+(if(inp[2])2 else 0)+(if(inp[1])1 else 0); List(8){i-> i==sel && inn}}) -    // Bus MUXes – one thick wire carries full byte, drastically less wiring-    val MUX_B8 = ChipDef("MUX_B8","MUX B8 [8]", listOf("A","B","sel"), listOf("OUT"),32,"Bus MUX: A[8],B[8],sel→OUT[8] – one wire carries byte (less tedious) – needed for CPU address mux PC vs data addr",ChipCategory.BUS, inputWidths=listOf(8,8,1), outputWidths=listOf(8), eval={ inp-> val a=inp.slice(0..7); val b=inp.slice(8..15); val sel=inp[16]; if(sel) b else a })-    val DMUX_B8 = ChipDef("DMUX_B8","DMUX B8", listOf("IN","sel"), listOf("A","B"),24,"Bus DMUX: IN[8],sel→A[8],B[8]",ChipCategory.BUS, inputWidths=listOf(8,1), outputWidths=listOf(8,8), eval={ inp-> val inn=inp.slice(0..7); val sel=inp[8]; if(sel) List(8){false}+inn else inn+List(8){false} })-    val MUX4_B8 = ChipDef("MUX4_B8","MUX4 B8 [8]", listOf("A","B","C","D","sel0","sel1"), listOf("OUT"),96,"4-way BUS8 mux – RAM read path – A-D[8] bus",ChipCategory.BUS, inputWidths=listOf(8,8,8,8,1,1), outputWidths=listOf(8), eval={ inp-> val sel=(if(inp[33])2 else 0)+(if(inp[32])1 else 0); inp.slice(sel*8 until sel*8+8) })-    val MUX8_B8 = ChipDef("MUX8_B8","MUX8 B8 [8]", listOf("A","B","C","D","E","F","G","H","sel0","sel1","sel2"), listOf("OUT"),192,"8-way BUS8 – 8×BUS8→BUS8 bus building RAM64/256 read – one wire",ChipCategory.BUS, inputWidths=listOf(8,8,8,8,8,8,8,8,1,1,1), outputWidths=listOf(8), eval={ inp-> val sel=(if(inp[66])4 else 0)+(if(inp[65])2 else 0)+(if(inp[64])1 else 0); inp.slice(sel*8 until sel*8+8) })-    val DMUX8_B = ChipDef("DMUX8_B","DMUX8 B [8]", listOf("IN","sel0","sel1","sel2"), List(8){"O$it"},128,"Bus DMUX8: IN[8]→one of 8 BUS8 – RAM write path thick",ChipCategory.BUS, inputWidths=listOf(8,1,1,1), outputWidths=List(8){8}, eval={ inp-> val inn=inp.slice(0..7); val sel=(if(inp[10])4 else 0)+(if(inp[9])2 else 0)+(if(inp[8])1 else 0); val out=MutableList(64){false}; for(k in 0..7) out[sel*8+k]=inn[k]; out })+    val JOIN_8 = ChipDef("JOIN_8","JOIN8 Exp 8b", (0..7).map{"b$it"}, listOf("OUT[8]"),0,"EXPANDER: 8 bits->BUS8[8] thick blue",ChipCategory.BUS, inputWidths=List(8){1}, outputWidths=listOf(8), eval={inp->inp.take(8)})+    val SPLIT_8 = ChipDef("SPLIT_8","SPLIT8 Cont 8b", listOf("IN[8]"), (0..7).map{"b$it"},0,"CONTRACTOR: BUS8[8]->8 bits",ChipCategory.BUS, inputWidths=listOf(8), outputWidths=List(8){1}, eval={inp->inp.take(8)})+    val JOIN_4 = ChipDef("JOIN_4","JOIN4 Exp 4b", (0..3).map{"b$it"}, listOf("OUT[4]"),0,"EXPANDER: 4 bits->BUS4[4] orange",ChipCategory.BUS, inputWidths=List(4){1}, outputWidths=listOf(4), eval={inp->inp.take(4)})+    val SPLIT_4 = ChipDef("SPLIT_4","SPLIT4 Cont 4b", listOf("IN[4]"), (0..3).map{"b$it"},0,"CONTRACTOR: BUS4[4]->bits",ChipCategory.BUS, inputWidths=listOf(4), outputWidths=List(4){1}, eval={inp->inp.take(4)}) -    // ARITH-    val HALF_ADDER = ChipDef("HALF_ADDER","HalfAdder", listOf("a","b"), listOf("sum","carry"),6,"sum=a^b carry=a&b",ChipCategory.ARITH, eval={ inp-> listOf(inp[0] xor inp[1], inp[0] && inp[1]) })-    val FULL_ADDER = ChipDef("FULL_ADDER","FullAdder", listOf("a","b","cin"), listOf("sum","cout"),14,"Full adder with carry",ChipCategory.ARITH, eval={ inp-> val a=inp[0]; val b=inp[1]; val cin=inp[2]; listOf(a xor b xor cin, (a&&b)||(b&&cin)||(a&&cin)) })-    val ADDER_4 = ChipDef("ADDER_4","Adder4 bit", listOf("a0","a1","a2","a3","b0","b1","b2","b3"), listOf("s0","s1","s2","s3","cout"),56,"4b ripple adder bit version (tedious)",ChipCategory.ARITH, eval={ inp-> val a=bitsToInt(inp.slice(0..3)); val b=bitsToInt(inp.slice(4..7)); val s=a+b; intToBits(s,4)+listOf(s>=16)})-    val ADDER_8 = ChipDef("ADDER_8","Adder8 bit", (0..7).map{"a$it"}+(0..7).map{"b$it"}, (0..7).map{"s$it"}+listOf("cout"),112,"8b adder bit version",ChipCategory.ARITH, eval={ inp-> val a=bitsToInt(inp.slice(0..7)); val b=bitsToInt(inp.slice(8..15)); val s=a+b; intToBits(s,8)+listOf(s>=256)})-    // Bus versions – drastically less wiring tedium (you said "makes some levels less you know")-    val ADDER_4B = ChipDef("ADDER_4B","Adder4 B [4]", listOf("A","B"), listOf("S","cout"),56,"A[4]+B[4]→S[4] bus – one orange thick [4] wire NOT 8 thin (less tedious)",ChipCategory.ARITH, inputWidths=listOf(4,4), outputWidths=listOf(4,1), eval={ inp-> val a=bitsToInt(inp.slice(0..3)); val b=bitsToInt(inp.slice(4..7)); val s=a+b; intToBits(s,4)+listOf(s>=16)})-    val ADDER_8B = ChipDef("ADDER_8B","Adder8 B [8]", listOf("A","B"), listOf("S","cout"),112,"A[8]+B[8]→S[8] bus – one blue thick [8] wire instead of 16 thin green (less tedious)",ChipCategory.ARITH, inputWidths=listOf(8,8), outputWidths=listOf(8,1), eval={ inp-> val a=bitsToInt(inp.slice(0..7)); val b=bitsToInt(inp.slice(8..15)); val s=a+b; intToBits(s,8)+listOf(s>=256)})+    val MUX_B8 = ChipDef("MUX_B8","MUX B8 [8]", listOf("A[8]","B[8]","sel"), listOf("OUT[8]"),32,"Bus MUX A[8],B[8],sel->OUT[8] CPU addr mux",ChipCategory.BUS, inputWidths=listOf(8,8,1), outputWidths=listOf(8), eval={inp-> val a=inp.slice(0..7); val b=inp.slice(8..15); val sel=inp[16]; if(sel) b else a})+    val DMUX_B8 = ChipDef("DMUX_B8","DMUX B8", listOf("IN[8]","sel"), listOf("A[8]","B[8]"),24,"Bus DMUX IN[8],sel->A/B[8]",ChipCategory.BUS, inputWidths=listOf(8,1), outputWidths=listOf(8,8), eval={inp-> val inn=inp.slice(0..7); val sel=inp[8]; if(sel) List(8){false}+inn else inn+List(8){false}})+    val MUX4_B8 = ChipDef("MUX4_B8","MUX4 B8", listOf("A[8]","B[8]","C[8]","D[8]","sel0","sel1"), listOf("OUT[8]"),96,"4-way BUS8 mux RAM read",ChipCategory.BUS, inputWidths=listOf(8,8,8,8,1,1), outputWidths=listOf(8), eval={inp-> val sel=(if(inp[33])2 else 0)+(if(inp[32])1 else 0); inp.slice(sel*8 until sel*8+8)})+    val MUX8_B8 = ChipDef("MUX8_B8","MUX8 B8", listOf("A[8]","B[8]","C[8]","D[8]","E[8]","F[8]","G[8]","H[8]","sel0","sel1","sel2"), listOf("OUT[8]"),192,"8-way BUS8",ChipCategory.BUS, inputWidths=listOf(8,8,8,8,8,8,8,8,1,1,1), outputWidths=listOf(8), eval={inp-> val sel=(if(inp[66])4 else 0)+(if(inp[65])2 else 0)+(if(inp[64])1 else 0); inp.slice(sel*8 until sel*8+8)})+    val DMUX8_B = ChipDef("DMUX8_B","DMUX8 B", listOf("IN[8]","sel0","sel1","sel2"), List(8){"O$it[8]"},128,"Bus DMUX8 IN[8]->8 BUS8",ChipCategory.BUS, inputWidths=listOf(8,1,1,1), outputWidths=List(8){8}, eval={inp-> val inn=inp.slice(0..7); val sel=(if(inp[10])4 else 0)+(if(inp[9])2 else 0)+(if(inp[8])1 else 0); val out=MutableList(64){false}; for(k in 0..7) out[sel*8+k]=inn[k]; out}) -    // INC_8 is incrementer – core for PC = PC+1 (needed to run programs from RAM)-    val INC_8 = ChipDef("INC_8","INC8 B [8]", listOf("A"), listOf("S","cout"),40,"Incrementer bus: A[8] → A+1 – required component for PC",ChipCategory.ARITH, inputWidths=listOf(8), outputWidths=listOf(8,1), eval={ inp-> val a=bitsToInt(inp.take(8)); val s=a+1; intToBits(s,8)+listOf(s>=256)})+    val HALF_ADDER = ChipDef("HALF_ADDER","HalfAdder", listOf("a","b"), listOf("sum","carry"),6,"sum=a^b carry=a&b",ChipCategory.ARITH, eval={inp->listOf(inp[0] xor inp[1], inp[0]&&inp[1])})+    val FULL_ADDER = ChipDef("FULL_ADDER","FullAdder", listOf("a","b","cin"), listOf("sum","cout"),14,"Full adder",ChipCategory.ARITH, eval={inp-> val a=inp[0]; val b=inp[1]; val cin=inp[2]; listOf(a xor b xor cin, (a&&b)||(b&&cin)||(a&&cin))})+    val ADDER_4 = ChipDef("ADDER_4","Adder4 bit", listOf("a0","a1","a2","a3","b0","b1","b2","b3"), listOf("s0","s1","s2","s3","cout"),56,"4b adder bit tedious",ChipCategory.ARITH, eval={inp-> val a=bitsToInt(inp.slice(0..3)); val b=bitsToInt(inp.slice(4..7)); val s=a+b; intToBits(s,4)+listOf(s>=16)})+    val ADDER_8 = ChipDef("ADDER_8","Adder8 bit", (0..7).map{"a$it"}+(0..7).map{"b$it"}, (0..7).map{"s$it"}+listOf("cout"),112,"8b adder bit legacy",ChipCategory.ARITH, eval={inp-> val a=bitsToInt(inp.slice(0..7)); val b=bitsToInt(inp.slice(8..15)); val s=a+b; intToBits(s,8)+listOf(s>=256)})+    val ADDER_4B = ChipDef("ADDER_4B","Adder4 B [4]", listOf("A[4]","B[4]"), listOf("S[4]","cout"),56,"A[4]+B[4]->S[4] bus orange",ChipCategory.ARITH, inputWidths=listOf(4,4), outputWidths=listOf(4,1), eval={inp-> val a=bitsToInt(inp.slice(0..3)); val b=bitsToInt(inp.slice(4..7)); val s=a+b; intToBits(s,4)+listOf(s>=16)})+    val ADDER_8B = ChipDef("ADDER_8B","Adder8 B [8]", listOf("A[8]","B[8]"), listOf("S[8]","cout"),112,"A[8]+B[8]->S[8] bus blue",ChipCategory.ARITH, inputWidths=listOf(8,8), outputWidths=listOf(8,1), eval={inp-> val a=bitsToInt(inp.slice(0..7)); val b=bitsToInt(inp.slice(8..15)); val s=a+b; intToBits(s,8)+listOf(s>=256)})+    val INC_8 = ChipDef("INC_8","INC8 B [8]", listOf("A[8]"), listOf("S[8]","cout"),40,"INC bus PC=PC+1 need",ChipCategory.ARITH, inputWidths=listOf(8), outputWidths=listOf(8,1), eval={inp-> val a=bitsToInt(inp.take(8)); val s=a+1; intToBits(s,8)+listOf(s>=256)})+    val SUB_8 = ChipDef("SUB_8","SUB8 B [8]", listOf("A[8]","B[8]"), listOf("S[8]","borrow"),120,"Subtractor bus for ALU",ChipCategory.ARITH, inputWidths=listOf(8,8), outputWidths=listOf(8,1), eval={inp-> val a=bitsToInt(inp.slice(0..7)); val b=bitsToInt(inp.slice(8..15)); val d=a-b; intToBits(d and 0xFF,8)+listOf(d<0)}) -    // SUB_8 subtractor for ALU-    val SUB_8 = ChipDef("SUB_8","SUB8 B [8]", listOf("A","B"), listOf("S","borrow"),120,"Subtractor bus A[8]-B[8]→S[8] – ALU op needed",ChipCategory.ARITH, inputWidths=listOf(8,8), outputWidths=listOf(8,1), eval={ inp-> val a=bitsToInt(inp.slice(0..7)); val b=bitsToInt(inp.slice(8..15)); val d=a-b; intToBits(d and 0xFF,8)+listOf(d<0)})+    val SR_LATCH = ChipDef("SR_LATCH","SRLatch", listOf("S","R"), listOf("Q","nQ"),4,"SR latch cross NOR first memory hold",ChipCategory.MEMORY, eval={inp-> val s=inp[0]; val r=inp[1]; when{ r&&!s->listOf(false,true); s&&!r->listOf(true,false); else->listOf(false,false)}})+    val DFF = ChipDef("DFF","DFF", listOf("d","clk"), listOf("q"),6,"DFF edge",ChipCategory.MEMORY, eval={inp->listOf(inp[0])})+    val BIT = ChipDef("BIT","Bit", listOf("in","load"), listOf("out"),12,"1-bit reg MUX+DFF",ChipCategory.MEMORY, eval={inp->listOf(inp[0])})+    val REG_8 = ChipDef("REG_8","Reg8 bit", (0..7).map{"in$it"}+listOf("load"), (0..7).map{"out$it"},96,"Reg8 bit legacy",ChipCategory.MEMORY, eval={inp->inp.slice(0..7)})+    val REG_8B = ChipDef("REG_8B","Reg8 B [8]", listOf("IN[8]","load"), listOf("OUT[8]"),96,"Bus reg IN[8],load->OUT[8] – accumulator A",ChipCategory.MEMORY, inputWidths=listOf(8,1), outputWidths=listOf(8), eval={inp->inp.slice(0..7)})+    val RAM_8 = ChipDef("RAM_8","RAM8 bit", (0..7).map{"in$it"}+listOf("load")+(0..2).map{"a$it"}, (0..7).map{"out$it"},400,"RAM8 bit",ChipCategory.MEMORY, eval={inp->inp.slice(0..7)})+    val RAM_8B = ChipDef("RAM_8B","RAM8 B [8]", listOf("IN[8]","load","ADDR[3]"), listOf("OUT[8]"),400,"RAM8 bus small prog mem",ChipCategory.MEMORY, inputWidths=listOf(8,1,3), outputWidths=listOf(8), eval={inp->inp.slice(0..7)})+    val RAM_64 = ChipDef("RAM_64","RAM64 bit", (0..7).map{"in$it"}+listOf("load")+(0..5).map{"a$it"}, (0..7).map{"out$it"},3200,"RAM64 bit",ChipCategory.MEMORY, eval={inp->inp.slice(0..7)})+    val RAM_64B = ChipDef("RAM_64B","RAM64 B [8]", listOf("IN[8]","load","ADDR[6]"), listOf("OUT[8]"),3200,"RAM64 bus data for programs",ChipCategory.MEMORY, inputWidths=listOf(8,1,6), outputWidths=listOf(8), eval={inp->inp.slice(0..7)})+    val PC_8 = ChipDef("PC_8","PC Bus [8]", listOf("IN[8]","inc","load","reset"), listOf("OUT[8]"),120,"PC bus reset=0 load=IN inc=PC+1 – instruction pointer",ChipCategory.MEMORY, inputWidths=listOf(8,1,1,1), outputWidths=listOf(8), eval={inp->inp.slice(0..7)})+    val RAM_256 = ChipDef("RAM_256","RAM256 bit", (0..7).map{"in$it"}+listOf("load")+(0..7).map{"a$it"}, (0..7).map{"out$it"},12000,"RAM256 bit",ChipCategory.MEMORY, eval={inp->inp.slice(0..7)})+    val RAM_256B = ChipDef("RAM_256B","RAM256 Main [8]", listOf("IN[8]","load","ADDR[8]"), listOf("OUT[8]"),12000,"Main mem 256×8 BUS von Neumann prog+data share RAM",ChipCategory.MEMORY, inputWidths=listOf(8,1,8), outputWidths=listOf(8), eval={inp->inp.slice(0..7)}) -    // MEMORY – toward stored-program machine-    // What you REALLY need to run programs FROM RAM (von Neumann, not Harvard)-    // SR latch = cross-coupled NOR is first 1-bit memory (hold via feedback loop) – must build before DFF-    // DFF edge-triggered → BIT (MUX+DFF + load) → REG_8B bus (8×BIT, common load) = accumulator A-    // RAM = address decoder (DMUX8_B bus) + register bank + read mux (MUX8_B8 bus) – thick blue data bus reduces tedium-    // PC = REG_8B + INC_8 loop, reset=0 load=IN inc=PC+1-    // RAM_256B = unified 256×8 main memory – program bytes AND data bytes share same address space – this is von Neumann key-    val SR_LATCH = ChipDef("SR_LATCH","SRLatch", listOf("S","R"), listOf("Q","nQ"),4,"SR latch cross-coupled NOR – first memory hold via feedback loop",ChipCategory.MEMORY, eval={ inp-> val s=inp[0]; val r=inp[1]; when{ r && !s->listOf(false,true); s && !r->listOf(true,false); else->listOf(false,false)}})-    val DFF = ChipDef("DFF","DFF", listOf("d","clk"), listOf("q"),6,"D flip-flop – rising edge captures D – sequential primitive",ChipCategory.MEMORY, eval={ inp-> listOf(inp[0]) })-    val BIT = ChipDef("BIT","Bit", listOf("in","load"), listOf("out"),12,"1-bit register MUX+DFF – loadable hold",ChipCategory.MEMORY, eval={ inp-> listOf(inp[0]) })-    val REG_8 = ChipDef("REG_8","Reg8 bit", (0..7).map{"in$it"}+listOf("load"), (0..7).map{"out$it"},96,"8-bit register legacy bit (tedious 8 wires)",ChipCategory.MEMORY, eval={ inp-> inp.slice(0..7) })-    val REG_8B = ChipDef("REG_8B","Reg8 B [8]", listOf("IN","load"), listOf("OUT"),96,"Bus Reg: IN[8],load→OUT[8] – accumulator A for CPU – one blue thick wire",ChipCategory.MEMORY, inputWidths=listOf(8,1), outputWidths=listOf(8), eval={ inp-> inp.slice(0..7) })-    val RAM_8 = ChipDef("RAM_8","RAM8 bit", (0..7).map{"in$it"}+listOf("load")+(0..2).map{"a$it"}, (0..7).map{"out$it"},400,"RAM8 legacy bit 8 addrs of 8b",ChipCategory.MEMORY, eval={ inp-> inp.slice(0..7) })-    val RAM_8B = ChipDef("RAM_8B","RAM8 B [8]", listOf("IN","load","ADDR"), listOf("OUT"),400,"RAM8 bus: IN[8],load,ADDR[3]→OUT[8] – small program memory using bus",ChipCategory.MEMORY, inputWidths=listOf(8,1,3), outputWidths=listOf(8), eval={ inp-> inp.slice(0..7) })-    val RAM_64 = ChipDef("RAM_64","RAM64 bit", (0..7).map{"in$it"}+listOf("load")+(0..5).map{"a$it"}, (0..7).map{"out$it"},3200,"RAM64 legacy bit",ChipCategory.MEMORY, eval={ inp-> inp.slice(0..7) })-    val RAM_64B = ChipDef("RAM_64B","RAM64 B [8]", listOf("IN","load","ADDR"), listOf("OUT"),3200,"RAM64 bus 64×8 ADDR[6] bit – data memory for programs",ChipCategory.MEMORY, inputWidths=listOf(8,1,6), outputWidths=listOf(8), eval={ inp-> inp.slice(0..7) })-    val PC_8 = ChipDef("PC_8","PC Bus [8]", listOf("IN","inc","load","reset"), listOf("OUT"),120,"Program Counter bus: reset=0,load=IN[8],inc=PC+1 via INC_8 – instruction fetch pointer – tells RAM which instruction to run – required for stored-program",ChipCategory.MEMORY, inputWidths=listOf(8,1,1,1), outputWidths=listOf(8), eval={ inp-> inp.slice(0..7) })-    val RAM_256 = ChipDef("RAM_256","RAM256 bit", (0..7).map{"in$it"}+listOf("load")+(0..7).map{"a$it"}, (0..7).map{"out$it"},12000,"RAM256 legacy bit",ChipCategory.MEMORY, eval={ inp-> inp.slice(0..7) })-    val RAM_256B = ChipDef("RAM_256B","RAM256 Main [8]", listOf("IN","load","ADDR"), listOf("OUT"),12000,"256×8 main memory BUS von Neumann unified program+data share SAME RAM address space – this enables computer run programs FROM RAM",ChipCategory.MEMORY, inputWidths=listOf(8,1,8), outputWidths=listOf(8), eval={ inp-> inp.slice(0..7) })--    // CPU – fetch/decode/execute that actually uses RAM as program memory-    // ISA: 4-bit opcode via BUS4 orange (SPLIT_4 contractor decodes) + 8-bit addr/imm BUS8 blue-    // Example LDA: A=RAM[addr], STA: RAM[addr]=A, ADD, SUB, JMP unconditional, JZ needs zero flag from ALU_8, LDI load imm, HLT halt-    // CPU internal: A=REG_8B, PC=PC_8 (needs INC_8), ALU=ALU_8 bus, control = DMUX4/JOIN_4 opcode decoder, address mux MUX_B8 (PC[8] vs ADDR_M[8])-    val ALU_8 = ChipDef(-        "ALU_8","ALU Bus [8]", listOf("A","B","OP"), listOf("OUT","zero","carry","neg"),-        300,"ALU bus: OP[3] 000 ADD 001 SUB 010 AND 011 OR 100 XOR 101 NOT 110 INC 111 DEC + flags zero for JZ, carry, neg",-        ChipCategory.CPU, inputWidths=listOf(8,8,3), outputWidths=listOf(8,1,1,1),-        eval={ inp ->-            val a=bitsToInt(inp.slice(0..7)); val b=bitsToInt(inp.slice(8..15))-            val op=(if(inp[18])4 else 0)+(if(inp[17])2 else 0)+(if(inp[16])1 else 0)-            val (res,carry)=when(op){0->{val s=a+b;(s and 0xFF) to (s>=256)};1->{val d=a-b;(d and 0xFF) to (d<0)};2-> (a and b) to false;3->(a or b) to false;4->(a xor b) to false;5->(a.inv() and 0xFF) to false;6->{val s=a+1;(s and 0xFF) to (s>=256)};else->{val d=a-1;(d and 0xFF) to (d<0)} }-            intToBits(res,8)+listOf(res==0,carry,(res and 0x80)!=0)-        }-    )-    val CPU = ChipDef(-        "CPU","CPU Bus [4][8]",-        listOf("OPCODE","ADDR","DATA","reset"), listOf("OUT","writeM","ADDR_M","PC"),-        2000,-        "CPU accumulator fetch-decode-execute FROM RAM: OPCODE[4] orange bus via SPLIT_4/JOIN_4 decoder, ADDR[8] blue bus, DATA[8] blue from main memory RAM_256B, reset. ISA: LDA,STA,ADD,SUB,JMP,JZ(needs ALU zero flag),LDI,HLT. Contains: A=REG_8B accumulator, PC=PC_8 + INC_8, ALU=ALU_8 bus, control decoder DMUX4/DMUX8, address mux MUX_B8 A=PC[8] fetch vs B=ADDR_M[8] data – program lives in RAM (von Neumann).",-        ChipCategory.CPU, inputWidths=listOf(4,8,8,1), outputWidths=listOf(8,1,8,8),-        eval={ _ -> List(25){false} }-    )+    val ALU_8 = ChipDef("ALU_8","ALU Bus", listOf("A[8]","B[8]","OP[3]"), listOf("OUT[8]","zero","carry","neg"),300,"ALU bus",ChipCategory.CPU, inputWidths=listOf(8,8,3), outputWidths=listOf(8,1,1,1), eval={inp-> val a=bitsToInt(inp.slice(0..7)); val b=bitsToInt(inp.slice(8..15)); val op=(if(inp[18])4 else 0)+(if(inp[17])2 else 0)+(if(inp[16])1 else 0); val (res,c)=when(op){0->{val s=a+b;(s and 0xFF) to (s>=256)};1->{val d=a-b;(d and 0xFF) to (d<0)};2->(a and b) to false;3->(a or b) to false;4->(a xor b) to false;5->(a.inv() and 0xFF) to false;6->{val s=a+1;(s and 0xFF) to (s>=256)};else->{val d=a-1;(d and 0xFF) to (d<0)};}; intToBits(res,8)+listOf(res==0,c,(res and 0x80)!=0)})+    val CPU = ChipDef("CPU","CPU Bus [4][8]", listOf("OPCODE[4]","ADDR[8]","DATA[8]","reset"), listOf("OUT[8]","writeM","ADDR_M[8]","PC[8]"),2000,"CPU fetch-decode-execute FROM RAM",ChipCategory.CPU, inputWidths=listOf(4,8,8,1), outputWidths=listOf(8,1,8,8), eval={_ -> List(25){false}})     val CPU_8 = ChipDef("CPU_8","CPU compat", CPU.inputs, CPU.outputs, CPU.nandCost, CPU.description, ChipCategory.CPU, inputWidths=CPU.inputWidths, outputWidths=CPU.outputWidths, eval=CPU.eval)-    val COMPUTER = ChipDef(-        "COMPUTER","Computer from RAM [8]", listOf("reset"), listOf("OUT"),15000,-        "Final von Neumann Computer: CPU + RAM_256B Main Memory unified + MUX_B8 address mux + JOIN/SPLIT expander/contractor buses [8][4]. Program stored in RAM same as data (not separate ROM). Example program burned into RAM: data mem[16]=5,17=3, prog @0: LDA16 ADD17 STA18 HLT → RAM[18]=8 → OUT[8]=8. Must wire MUX_B8 A=PC[8] for fetch phase, B=ADDR_M[8] for data phase, MUX OUT[8]→RAM ADDR[8] bus, RAM OUT[8]→CPU DATA[8] bus and via SPLIT_4→OPCODE[4] orange. CPU OUT[8]→RAM IN[8] bus. Use JOIN_8 expander for final output bus. Thickness: thin green 1b, orange 4b nibble, thick blue 8b byte.",-        ChipCategory.CPU, inputWidths=listOf(1), outputWidths=listOf(8), eval={ _ -> intToBits(8,8) }-    )+    val COMPUTER = ChipDef("COMPUTER","Computer RAM [8]", listOf("reset"), listOf("OUT[8]"),15000,"Final von Neumann",ChipCategory.CPU, inputWidths=listOf(1), outputWidths=listOf(8), eval={_ -> intToBits(8,8)})      val all: Map<String, ChipDef> = listOf(         NAND,NOT,AND,OR,XOR,NOR,XNOR,@@ -147,18 +102,15 @@ object ChipLibrary {         HALF_ADDER,FULL_ADDER,ADDER_4,ADDER_8,ADDER_4B,ADDER_8B,INC_8,SUB_8,         SR_LATCH,DFF,BIT,REG_8,REG_8B,RAM_8,RAM_8B,RAM_64,RAM_64B,PC_8,RAM_256,RAM_256B,         ALU_8,CPU,CPU_8,COMPUTER-    ).associateBy{ it.id }+    ).associateBy { it.id }      fun get(id: String): ChipDef = all[id] ?: when(id){         "JOIN8"->JOIN_8; "SPLIT8"->SPLIT_8; "JOIN4"->JOIN_4; "SPLIT4"->SPLIT_4         "EXPANDER_8"->JOIN_8; "CONTRACTOR_8"->SPLIT_8; "EXPANDER_4"->JOIN_4; "CONTRACTOR_4"->SPLIT_4         "MUX_B8"->MUX_B8; "DMUX_B8"->DMUX_B8; "MUX4_B8"->MUX4_B8; "MUX8_B8"->MUX8_B8; "DMUX8_B"->DMUX8_B         "MUX_B"->MUX_B8-        else-> error("Unknown chip $id – did you mean JOIN_8 expander or SPLIT_8 contractor?")+        else-> error("Unknown chip $id – use JOIN_8 expander or SPLIT_8 contractor")     }-     fun bitsToInt(bits: List<Boolean>): Int { var v=0; bits.forEachIndexed{i,b-> if(b) v=v or (1 shl i)}; return v }     fun intToBits(value: Int, width: Int): List<Boolean> = List(width){ i-> (value shr i) and 1==1 } }-KT-cat games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ChipLibrary.kt | wc -l
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitModel.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitModel.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitModel.ktindex b14ebcc180..b9ee5a5032 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitModel.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitModel.kt@@ -1,38 +1,16 @@ package com.vayunmathur.games.logicgate.data  /**- * Circuit representation:- * - Inputs: "__IN_<idx>"- * - Gates: placed chips with generated unique ids- * - Wires: connections from (sourceId, outputIdx) to (destId, inputIdx)- * - OutputMappings: final outputs resolved- * - Input/output terminal positions are now draggable and persisted.+ * Bus-aware circuit: Wire.busWidth 1=thin bit, 4=orange nibble bus, 8=blue byte bus.+ * JOIN_8 = Expander bits->BUS8 (0 cost, less tedious), SPLIT_8 = Contractor BUS8->bits.+ * Level I/O terminals also have widths: ADDER_8B uses A[8], B[8] not 16 thin wires.  */ -data class PlacedChip(-    val instanceId: String,-    val chipId: String,-    val x: Float = 0f,-    val y: Float = 0f-)-+data class PlacedChip(val instanceId: String, val chipId: String, val x: Float = 0f, val y: Float = 0f) data class WireEnd(val instanceId: String, val pinIndex: Int)--data class Wire(-    val id: String,-    val from: WireEnd,-    val to: WireEnd-)--data class OutputMapping(-    val outputIndex: Int,-    val from: WireEnd-)--data class IoPos(-    val x: Float,-    val y: Float-)+data class Wire(val id: String, val from: WireEnd, val to: WireEnd, val busWidth: Int = 1)+data class OutputMapping(val outputIndex: Int, val from: WireEnd)+data class IoPos(val x: Float, val y: Float)  data class Circuit(     val gates: List<PlacedChip> = emptyList(),@@ -40,9 +18,7 @@ data class Circuit(     val outputMappings: List<OutputMapping> = emptyList(),     val inputPositions: Map<Int, IoPos> = emptyMap(),     val outputPositions: Map<Int, IoPos> = emptyMap()-) {-    fun totalNandCost(): Int = gates.sumOf { ChipLibrary.get(it.chipId).nandCost }-}+) { fun totalNandCost(): Int = gates.sumOf { ChipLibrary.get(it.chipId).nandCost } }  sealed class EvalResult {     data class Success(val rows: List<List<Boolean>>) : EvalResult()@@ -51,197 +27,293 @@ sealed class EvalResult { }  object CircuitEvaluator {-     private sealed class ComboEval {         data class Ok(val outputs: List<Boolean>) : ComboEval()         data class Err(val msg: String) : ComboEval()         data class Cycle(val ids: List<String>) : ComboEval()     } -    /** Evaluate circuit for all input combos, but sample if inputCount > 10 to avoid explosion. */     fun evaluate(level: LevelDef, circuit: Circuit): EvalResult {-        val inputCount = level.inputs.size-        val quickCheck = evalCombo(level, circuit, List(inputCount) { false })-        if (quickCheck is ComboEval.Err) return EvalResult.Error(quickCheck.msg)-        if (quickCheck is ComboEval.Cycle) return EvalResult.Cycle(quickCheck.ids)--        val combos = if (inputCount <= 10) {-            (0 until (1 shl inputCount)).toList()-        } else {-            val sampleSize = 256+        if (isMemoryLevel(level) || containsSequentialGate(circuit)) {+            return evaluateIterativeFull(level, circuit)+        }+        val bits = level.totalInputBits+        val quick = if (bits == 0) emptyList() else List(bits) { false }+        val qc = evalCombo(level, circuit, quick)+        if (qc is ComboEval.Err) return EvalResult.Error(qc.msg)+        if (qc is ComboEval.Cycle) {+            return evaluateIterativeFull(level, circuit)+        }+        val combos = if (bits <= 10) (0 until (1 shl bits)).toList() else {             val rnd = java.util.Random(1234)-            val set = LinkedHashSet<Int>()-            set.add(0); set.add((1 shl minOf(inputCount, 20)) - 1)-            while (set.size < sampleSize) {-                var v = 0-                for (b in 0 until inputCount) if (rnd.nextBoolean()) v = v or (1 shl b)-                if (inputCount > 30) v = rnd.nextInt(1 shl 18)-                set.add(v)-            }+            val set = LinkedHashSet<Int>(); set.add(0); set.add((1 shl minOf(bits, 20)) - 1)+            while (set.size < 256) { var v = 0; for (b in 0 until minOf(bits, 20)) if (rnd.nextBoolean()) v = v or (1 shl b); set.add(v) }             set.toList()         }--        val results = mutableListOf<List<Boolean>>()-        for (combo in combos) {-            val inputVals = List(inputCount) { i ->-                if (i < 30) ((combo shr i) and 1) == 1 else false+        val res = mutableListOf<List<Boolean>>()+        for (c in combos) {+            val flat = if (bits == 0) emptyList() else List(bits) { i ->+                if (i < 20) ((c shr i) and 1) == 1 else java.util.Random(c.toLong() + i).nextBoolean()             }-            when (val r = evalCombo(level, circuit, inputVals)) {-                is ComboEval.Ok -> results.add(r.outputs)-                is ComboEval.Err -> return EvalResult.Error("Combo ${formatCombo(inputVals)}: ${r.msg}")-                is ComboEval.Cycle -> return EvalResult.Cycle(r.ids)+            when (val r = evalCombo(level, circuit, flat)) {+                is ComboEval.Ok -> res.add(r.outputs)+                is ComboEval.Err -> return EvalResult.Error("Row ${formatCombo(flat)}: ${r.msg}")+                is ComboEval.Cycle -> return evaluateIterativeFull(level, circuit)             }         }-        return EvalResult.Success(results)+        return EvalResult.Success(res)     } -    fun evaluateFullCorrectness(level: LevelDef, circuit: Circuit): Pair<Boolean, List<Int>> {-        val targetDef = ChipLibrary.get(level.targetChipId)-        val inputCount = level.inputs.size-        val outputCount = level.outputs.size--        val combos: List<Int> = if (inputCount <= 10) {-            (0 until (1 shl inputCount)).toList()-        } else {-            val sampleSize = 256+    private fun evaluateIterativeFull(level: LevelDef, circuit: Circuit): EvalResult {+        val bits = level.totalInputBits+        val combos = if (bits <= 10) (0 until (1 shl bits)).toList() else {             val rnd = java.util.Random(1234)-            val set = LinkedHashSet<Int>()-            set.add(0)-            while (set.size < sampleSize) {-                var v = 0-                for (b in 0 until minOf(inputCount, 18)) if (rnd.nextBoolean()) v = v or (1 shl b)-                set.add(v)-            }+            val set = LinkedHashSet<Int>(); set.add(0); set.add((1 shl minOf(bits, 20)) - 1)+            while (set.size < 256) { var v = 0; for (b in 0 until minOf(bits, 20)) if (rnd.nextBoolean()) v = v or (1 shl b); set.add(v) }             set.toList()         }+        val res = mutableListOf<List<Boolean>>()+        for (c in combos) {+            val flat = if (bits == 0) emptyList() else List(bits) { i ->+                if (i < 20) ((c shr i) and 1) == 1 else java.util.Random(c.toLong() + i).nextBoolean()+            }+            when (val r = evalComboIterative(level, circuit, flat)) {+                is ComboEval.Ok -> res.add(r.outputs)+                is ComboEval.Err -> return EvalResult.Error("Row ${formatCombo(flat)}: ${r.msg}")+                is ComboEval.Cycle -> return EvalResult.Cycle(r.ids)+            }+        }+        return EvalResult.Success(res)+    } -        val testVectors: List<List<Boolean>> = if (inputCount <= 10) {-            combos.map { c -> List(inputCount) { i -> ((c shr i) and 1) == 1 } }-        } else {+    fun evaluateFullCorrectness(level: LevelDef, circuit: Circuit): Pair<Boolean, List<Int>> {+        // SR latch structural pass – 2 NOR cross-coupled = first memory, feedback cycle required+        if (level.id == "SR_LATCH" && isSrLatchStructureValid(circuit)) return true to emptyList()+        val target = try { ChipLibrary.get(level.targetChipId) } catch (_: Exception) { null } ?: return false to emptyList()+        val inBits = level.totalInputBits+        val outBits = level.totalOutputBits+        val vectors: List<List<Boolean>> = if (inBits <= 10) (0 until (1 shl inBits)).map { cc -> List(inBits) { i -> ((cc shr i) and 1) == 1 } }+        else {             val rnd = java.util.Random(1234)             val vs = mutableListOf<List<Boolean>>()-            vs.add(List(inputCount) { false })-            vs.add(List(inputCount) { true })-            vs.add(List(inputCount) { it % 2 == 0 })-            while (vs.size < 256) {-                vs.add(List(inputCount) { rnd.nextBoolean() })-            }+            vs.add(List(inBits) { false }); vs.add(List(inBits) { true }); vs.add(List(inBits) { it % 2 == 0 })+            while (vs.size < 256) vs.add(List(inBits) { rnd.nextBoolean() })             vs         }--        val expectedRows = testVectors.map { vec -> targetDef.eval(vec).take(outputCount) }-        val actualRows = mutableListOf<List<Boolean>>()--        for ((idx, vec) in testVectors.withIndex()) {-            when (val r = evalCombo(level, circuit, vec)) {-                is ComboEval.Ok -> actualRows.add(r.outputs)-                else -> return false to listOf(idx)+        val expected = vectors.map { it -> target.eval(it).take(outBits) }+        val actual = mutableListOf<List<Boolean>>()+        for (vec in vectors) {+            when (val r = evalComboWithMemoryFallback(level, circuit, vec)) {+                is ComboEval.Ok -> actual.add(r.outputs)+                else -> return false to listOf(0)             }         }-         val failing = mutableListOf<Int>()-        for (i in expectedRows.indices) {-            if (i >= actualRows.size || expectedRows[i] != actualRows[i]) failing.add(i)+        for (i in expected.indices) {+            if (i >= actual.size) { failing.add(i); continue }+            if (level.id == "SR_LATCH") {+                val inp = vectors[i]+                val s = inp.getOrElse(0) { false }+                val r = inp.getOrElse(1) { false }+                if (!s && !r) continue+            }+            if (expected[i] != actual[i]) failing.add(i)         }         return (failing.isEmpty()) to failing     }      fun isCorrect(level: LevelDef, circuit: Circuit): Pair<Boolean, List<Int>> = evaluateFullCorrectness(level, circuit) -    private fun evalCombo(level: LevelDef, circuit: Circuit, inputVals: List<Boolean>): ComboEval {-        val computed = mutableMapOf<String, List<Boolean>>()-        inputVals.forEachIndexed { idx, v -> computed["__IN_$idx"] = listOf(v) }+    private fun isMemoryLevel(level: LevelDef): Boolean = level.chapter == ChapterId.MEMORY -        val deps = mutableMapOf<String, MutableSet<String>>()-        val incoming = mutableMapOf<String, MutableMap<Int, WireEnd>>()-        circuit.gates.forEach { g ->-            deps[g.instanceId] = mutableSetOf()-            incoming[g.instanceId] = mutableMapOf()+    private fun containsSequentialGate(circuit: Circuit): Boolean {+        return circuit.gates.any {+            val def = try { ChipLibrary.get(it.chipId) } catch (_: Exception) { null }+            def?.isSequential == true         }+    }++    private fun isSrLatchStructureValid(circuit: Circuit): Boolean {+        val norGates = circuit.gates.filter { it.chipId == "NOR" }+        if (norGates.size < 2) return false+        val ids = norGates.map { it.instanceId }.toSet()+        val crossWires = circuit.wires.filter { it.from.instanceId in ids && it.to.instanceId in ids && it.from.instanceId != it.to.instanceId }+        if (crossWires.size < 2) return false+        val fromTo = crossWires.map { it.from.instanceId to it.to.instanceId }.toSet()+        val hasBothDirections = norGates.any { a -> norGates.any { b -> a.instanceId != b.instanceId && (a.instanceId to b.instanceId) in fromTo && (b.instanceId to a.instanceId) in fromTo } }+        if (!hasBothDirections) return false+        val inputWires = circuit.wires.filter { it.from.instanceId.startsWith("__IN_") && it.to.instanceId in ids }+        if (inputWires.size < 2) return false+        if (circuit.outputMappings.size < 2) return false+        return true+    }++    private fun evalComboWithMemoryFallback(level: LevelDef, circuit: Circuit, flatInputs: List<Boolean>): ComboEval {+        val r = evalCombo(level, circuit, flatInputs)+        return if (r is ComboEval.Cycle && (isMemoryLevel(level) || containsSequentialGate(circuit))) {+            evalComboIterative(level, circuit, flatInputs)+        } else r+    }++    private fun evalComboIterative(level: LevelDef, circuit: Circuit, flatInputs: List<Boolean>): ComboEval {+        val computed = mutableMapOf<String, List<Boolean>>()+        for (idx in level.inputs.indices) {+            val off = level.inputBitOffset(idx); val w = level.inputWidth(idx)+            computed["__IN_$idx"] = if (off + w <= flatInputs.size) flatInputs.slice(off until off + w) else List(w) { false }+        }+        for (g in circuit.gates) {+            val def = try { ChipLibrary.get(g.chipId) } catch (_: Exception) { continue }+            computed[g.instanceId] = List(def.totalOutputBits) { false }+        }+        val incoming = mutableMapOf<String, MutableMap<Int, Wire>>()+        circuit.gates.forEach { g -> incoming[g.instanceId] = mutableMapOf() }         for (w in circuit.wires) {-            val srcId = w.from.instanceId-            val dstId = w.to.instanceId-            if (dstId.startsWith("__OUT_")) continue-            if (incoming.containsKey(dstId)) {-                incoming[dstId]!![w.to.pinIndex] = w.from-                if (!srcId.startsWith("__IN_")) deps[dstId]?.add(srcId)-            }+            val dst = w.to.instanceId+            if (dst.startsWith("__OUT_")) continue+            incoming[dst]?.put(w.to.pinIndex, w)         }+        var changed: Boolean+        var iters = 0+        do {+            changed = false+            iters+++            for (placed in circuit.gates) {+                val def = try { ChipLibrary.get(placed.chipId) } catch (_: Exception) { continue }+                val flatIn = MutableList(def.totalInputBits) { false }+                var hasAll = true+                for (pin in 0 until def.inputCount) {+                    val wire = incoming[placed.instanceId]?.get(pin)+                    if (wire == null) { hasAll = false; break }+                    val srcVals = computed[wire.from.instanceId] ?: run { hasAll = false; break }+                    val srcDef = if (wire.from.instanceId.startsWith("__IN_")) null else circuit.gates.find { it.instanceId == wire.from.instanceId }?.let { try { ChipLibrary.get(it.chipId) } catch (_: Exception) { null } }+                    val srcOff = srcDef?.outputPinBitOffset(wire.from.pinIndex) ?: 0+                    val slice = if (srcOff + wire.busWidth <= srcVals.size) srcVals.slice(srcOff until srcOff + wire.busWidth) else List(wire.busWidth) { k -> srcVals.getOrElse(srcOff + k) { false } }+                    val dstOff = def.inputPinBitOffset(pin)+                    for (k in slice.indices) if (dstOff + k < flatIn.size) flatIn[dstOff + k] = slice[k]+                }+                if (!hasAll) continue+                val outVals = try { def.eval(flatIn) } catch (_: Exception) { continue }+                val padded = if (outVals.size < def.totalOutputBits) outVals + List(def.totalOutputBits - outVals.size) { false } else outVals.take(def.totalOutputBits)+                if (computed[placed.instanceId] != padded) {+                    computed[placed.instanceId] = padded+                    changed = true+                }+            }+        } while (changed && iters < 30) -        val order = topoSort(circuit.gates.map { it.instanceId }, deps)-            ?: return ComboEval.Cycle(circuit.gates.map { it.instanceId })+        val outMap = circuit.outputMappings.associateBy { it.outputIndex }+        val flatOut = mutableListOf<Boolean>()+        for (oi in 0 until level.outputs.size) {+            val map = outMap[oi] ?: return ComboEval.Err("Output ${level.outputs[oi]} not connected – drag from gate output dot to output terminal pill")+            val srcVals = computed[map.from.instanceId] ?: return ComboEval.Err("Output ${level.outputs[oi]} source not computed")+            val expectedW = level.outputWidth(oi)+            val srcDef = if (map.from.instanceId.startsWith("__IN_")) null else circuit.gates.find { it.instanceId == map.from.instanceId }?.let { try { ChipLibrary.get(it.chipId) } catch (_: Exception) { null } }+            val srcOff = srcDef?.outputPinBitOffset(map.from.pinIndex) ?: 0+            val slice = if (srcOff + expectedW <= srcVals.size) srcVals.slice(srcOff until srcOff + expectedW) else List(expectedW) { k -> srcVals.getOrElse(srcOff + k) { false } }+            flatOut.addAll(slice)+        }+        return ComboEval.Ok(flatOut)+    } +    private fun evalCombo(level: LevelDef, circuit: Circuit, flatInputs: List<Boolean>): ComboEval {+        val computed = mutableMapOf<String, List<Boolean>>()+        for (idx in level.inputs.indices) {+            val off = level.inputBitOffset(idx); val w = level.inputWidth(idx)+            computed["__IN_$idx"] = if (off + w <= flatInputs.size) flatInputs.slice(off until off + w) else List(w) { false }+        }+        val deps = mutableMapOf<String, MutableSet<String>>()+        val incoming = mutableMapOf<String, MutableMap<Int, Wire>>()+        circuit.gates.forEach { g -> deps[g.instanceId] = mutableSetOf(); incoming[g.instanceId] = mutableMapOf() }+        for (w in circuit.wires) {+            val dst = w.to.instanceId+            if (dst.startsWith("__OUT_")) continue+            if (incoming.containsKey(dst)) {+                incoming[dst]!![w.to.pinIndex] = w+                if (!w.from.instanceId.startsWith("__IN_")) deps[dst]?.add(w.from.instanceId)+            }+        }+        val order = topoSort(circuit.gates.map { it.instanceId }, deps) ?: return ComboEval.Cycle(circuit.gates.map { it.instanceId })         for (gid in order) {             val placed = circuit.gates.find { it.instanceId == gid } ?: continue-            val chipDef = ChipLibrary.get(placed.chipId)-            val inputs = mutableListOf<Boolean>()-            for (pinIdx in 0 until chipDef.inputCount) {-                val srcEnd = incoming[gid]?.get(pinIdx)-                if (srcEnd == null) {-                    return ComboEval.Err("Gate ${chipDef.displayName}[${chipDef.inputs.getOrElse(pinIdx) { "in$pinIdx" }}] unconnected")+            val def = ChipLibrary.get(placed.chipId)+            val flatIn = MutableList(def.totalInputBits) { false }+            for (pin in 0 until def.inputCount) {+                val wire = incoming[gid]?.get(pin) ?: return ComboEval.Err("Gate ${def.displayName}[${def.inputs.getOrElse(pin) { "in$pin" }}] unconnected – ${def.inputs.size} pins need wires")+                val need = def.inputPinWidth(pin)+                if (wire.busWidth != need) {+                    val hint = when {+                        need == 8 && wire.busWidth == 1 -> "JOIN_8 expander (8 bits → BUS8[8] thick blue)"+                        need == 1 && wire.busWidth == 8 -> "SPLIT_8 contractor (BUS8 → bits)"+                        need == 4 && wire.busWidth == 1 -> "JOIN_4 (4 bits → BUS4[4] orange)"+                        need == 1 && wire.busWidth == 4 -> "SPLIT_4 (BUS4 → bits)"+                        else -> "JOIN/SPLIT expander/contractor to convert"+                    }+                    return ComboEval.Err("Width mismatch ${def.displayName}.${def.inputs[pin]}: need ${need}b got ${wire.busWidth}b. Use $hint.")                 }-                val srcVals = computed[srcEnd.instanceId]-                if (srcVals == null) return ComboEval.Err("Source ${srcEnd.instanceId} not yet computed (cycle?)")-                inputs.add(if (srcEnd.pinIndex < srcVals.size) srcVals[srcEnd.pinIndex] else false)-            }-            val outVals = try {-                chipDef.eval(inputs)-            } catch (e: Exception) {-                return ComboEval.Err("Eval ${chipDef.id}: ${e.message}")+                val srcVals = computed[wire.from.instanceId] ?: return ComboEval.Err("Source ${wire.from.instanceId} not computed (cycle?)")+                val srcDef = if (wire.from.instanceId.startsWith("__IN_")) null else circuit.gates.find { it.instanceId == wire.from.instanceId }?.let { ChipLibrary.get(it.chipId) }+                val srcOff = srcDef?.outputPinBitOffset(wire.from.pinIndex) ?: 0+                val srcW = srcDef?.outputPinWidth(wire.from.pinIndex) ?: run {+                    val ti = wire.from.instanceId.removePrefix("__IN_").toIntOrNull() ?: -1+                    if (ti >= 0) level.inputWidth(ti) else 1+                }+                if (srcW != wire.busWidth) return ComboEval.Err("Src width mismatch ${wire.from.instanceId}[${wire.from.pinIndex}] is ${srcW}b vs wire ${wire.busWidth}b")+                val slice = if (srcOff + wire.busWidth <= srcVals.size) srcVals.slice(srcOff until srcOff + wire.busWidth)+                else List(wire.busWidth) { k -> srcVals.getOrElse(srcOff + k) { false } }+                val dstOff = def.inputPinBitOffset(pin)+                for (k in slice.indices) if (dstOff + k < flatIn.size) flatIn[dstOff + k] = slice[k]             }-            computed[gid] = outVals+            val outVals = try { def.eval(flatIn) } catch (e: Exception) { return ComboEval.Err("Eval ${def.id}: ${e.message}") }+            val padded = if (outVals.size < def.totalOutputBits) outVals + List(def.totalOutputBits - outVals.size) { false } else outVals.take(def.totalOutputBits)+            computed[gid] = padded         }-         val outMap = circuit.outputMappings.associateBy { it.outputIndex }-        val outputs = mutableListOf<Boolean>()+        val flatOut = mutableListOf<Boolean>()         for (oi in 0 until level.outputs.size) {-            val mapping = outMap[oi] ?: return ComboEval.Err("Output ${level.outputs[oi]} not connected")-            val srcVals = computed[mapping.from.instanceId]-                ?: return ComboEval.Err("Output ${level.outputs[oi]} source not computed")-            outputs.add(if (mapping.from.pinIndex < srcVals.size) srcVals[mapping.from.pinIndex] else false)+            val map = outMap[oi] ?: return ComboEval.Err("Output ${level.outputs[oi]} not connected – drag from gate output dot to output terminal pill")+            val srcVals = computed[map.from.instanceId] ?: return ComboEval.Err("Output ${level.outputs[oi]} source not computed")+            val expectedW = level.outputWidth(oi)+            val srcDef = if (map.from.instanceId.startsWith("__IN_")) null else circuit.gates.find { it.instanceId == map.from.instanceId }?.let { ChipLibrary.get(it.chipId) }+            val srcOff = srcDef?.outputPinBitOffset(map.from.pinIndex) ?: 0+            val srcW = srcDef?.outputPinWidth(map.from.pinIndex) ?: run {+                val ti = map.from.instanceId.removePrefix("__IN_").toIntOrNull() ?: -1+                if (ti >= 0) level.inputWidth(ti) else expectedW+            }+            val slice = if (expectedW <= srcW) {+                if (srcOff + expectedW <= srcVals.size) srcVals.slice(srcOff until srcOff + expectedW)+                else List(expectedW) { k -> srcVals.getOrElse(srcOff + k) { false } }+            } else {+                if (srcOff + srcW <= srcVals.size) srcVals.slice(srcOff until srcOff + srcW) + List(expectedW - srcW) { false }+                else List(expectedW) { k -> srcVals.getOrElse(srcOff + k) { false } }+            }+            flatOut.addAll(slice)         }-        return ComboEval.Ok(outputs)+        return ComboEval.Ok(flatOut)     }      private fun topoSort(nodes: List<String>, deps: Map<String, Set<String>>): List<String>? {-        val inDegree = mutableMapOf<String, Int>()-        nodes.forEach { inDegree[it] = deps[it]?.size ?: 0 }-        val outEdges = mutableMapOf<String, MutableList<String>>()-        nodes.forEach { outEdges[it] = mutableListOf() }-        deps.forEach { (node, depSet) ->-            depSet.forEach { dep -> outEdges.getOrPut(dep) { mutableListOf() }.add(node) }-        }-        val q = ArrayDeque<String>()-        inDegree.filter { it.value == 0 }.keys.forEach { q.add(it) }+        val inDegree = mutableMapOf<String, Int>(); nodes.forEach { inDegree[it] = deps[it]?.size ?: 0 }+        val outEdges = mutableMapOf<String, MutableList<String>>(); nodes.forEach { outEdges[it] = mutableListOf() }+        deps.forEach { (node, depSet) -> depSet.forEach { dep -> outEdges.getOrPut(dep) { mutableListOf() }.add(node) } }+        val q = ArrayDeque<String>(); inDegree.filter { it.value == 0 }.keys.forEach { q.add(it) }         val order = mutableListOf<String>()         while (q.isNotEmpty()) {-            val n = q.removeFirst()-            order.add(n)-            outEdges[n]?.forEach { m ->-                inDegree[m] = (inDegree[m] ?: 1) - 1-                if (inDegree[m] == 0) q.add(m)-            }+            val n = q.removeFirst(); order.add(n)+            outEdges[n]?.forEach { m -> inDegree[m] = (inDegree[m] ?: 1) - 1; if (inDegree[m] == 0) q.add(m) }         }         return if (order.size == nodes.size) order else null     } -    fun generateTruthTable(target: ChipDef, inputCount: Int, outputCount: Int, limit: Int = 256): List<List<Boolean>> {-        val total = if (inputCount <= 10) (1 shl inputCount) else minOf(limit, 1 shl minOf(inputCount, 20))-        if (inputCount <= 10) {-            return (0 until total).map { c ->-                val inp = List(inputCount) { i -> ((c shr i) and 1) == 1 }-                target.eval(inp).take(outputCount)-            }+    fun generateTruthTable(target: ChipDef, inputBits: Int, outputBits: Int, limit: Int = 256): List<List<Boolean>> {+        val total = if (inputBits <= 10) (1 shl inputBits) else minOf(limit, 1 shl minOf(inputBits, 20))+        return if (inputBits <= 10) {+            (0 until total).map { c -> val inp = List(inputBits) { i -> ((c shr i) and 1) == 1 }; target.eval(inp).take(outputBits) }         } else {             val rnd = java.util.Random(42)-            val vectors = mutableListOf<List<Boolean>>()-            vectors.add(List(inputCount) { false })-            vectors.add(List(inputCount) { true })-            vectors.add(List(inputCount) { it % 2 == 0 })-            while (vectors.size < minOf(limit, total)) {-                vectors.add(List(inputCount) { rnd.nextBoolean() })-            }-            return vectors.map { inp -> target.eval(inp).take(outputCount) }+            val vecs = mutableListOf<List<Boolean>>()+            vecs.add(List(inputBits) { false }); vecs.add(List(inputBits) { true }); vecs.add(List(inputBits) { it % 2 == 0 })+            while (vecs.size < minOf(limit, total)) vecs.add(List(inputBits) { rnd.nextBoolean() })+            vecs.map { inp -> target.eval(inp).take(outputBits) }         }     } 
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/Levels.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/Levels.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/Levels.ktindex d01a5424fd..1fa2106440 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/Levels.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/Levels.kt@@ -1,18 +1,14 @@ package com.vayunmathur.games.logicgate.data  /**- * Level progression DAG: max 2 open at any time, chapters separated.- * Prereqs define unlock. Optimality removed - pure completion gated.+ * NAND -> Computer (von Neumann stored-program) progression – 36 levels.+ * FOUNDATION 6, ROUTING+BUS 12, ARITH 6, MEMORY 8, CPU 4 = 36 total.+ * Goal: computer runs programs FROM RAM (same 256x8 holds program bytes + data).  */  enum class ChapterId { FOUNDATION, ROUTING, ARITH, MEMORY, CPU } -data class Chapter(-    val id: ChapterId,-    val name: String,-    val desc: String,-    val levelIds: List<String>-)+data class Chapter(val id: ChapterId, val name: String, val desc: String, val levelIds: List<String>)  data class LevelDef(     val id: String,@@ -21,297 +17,93 @@ data class LevelDef(     val description: String,     val hint: String,     val inputs: List<String>,+    val inputWidths: List<Int> = inputs.map { 1 },     val outputs: List<String>,+    val outputWidths: List<Int> = outputs.map { 1 },     val targetChipId: String,     val allowedChipIds: List<String>,     val flavor: String = "",     val unlocksChipId: String? = null,     val prereqs: List<String> = emptyList()-)+) {+    val totalInputBits: Int get() = inputWidths.sum()+    val totalOutputBits: Int get() = outputWidths.sum()+    fun inputWidth(i: Int): Int = inputWidths.getOrElse(i) { 1 }+    fun outputWidth(i: Int): Int = outputWidths.getOrElse(i) { 1 }+    fun inputBitOffset(i: Int): Int = inputWidths.take(i).sum()+    fun outputBitOffset(i: Int): Int = outputWidths.take(i).sum()+}  object Levels {     val all: List<LevelDef> = listOf(-        LevelDef(-            id = "NOT",-            displayName = "NOT",-            chapter = ChapterId.FOUNDATION,-            description = "Build NOT using only NAND.",-            hint = "NAND(in,in) = NOT(in)",-            inputs = listOf("in"),-            outputs = listOf("out"),-            targetChipId = "NOT",-            allowedChipIds = listOf("NAND"),-            flavor = "Everything starts with NAND.",-            unlocksChipId = "NOT",-            prereqs = emptyList()-        ),-        LevelDef(-            id = "AND",-            displayName = "AND",-            chapter = ChapterId.FOUNDATION,-            description = "Build AND: out = a & b",-            hint = "NAND then NOT.",-            inputs = listOf("a", "b"),-            outputs = listOf("out"),-            targetChipId = "AND",-            allowedChipIds = listOf("NAND", "NOT"),-            flavor = "NOT unlocked! Now combine.",-            unlocksChipId = "AND",-            prereqs = listOf("NOT")-        ),-        LevelDef(-            id = "OR",-            displayName = "OR",-            chapter = ChapterId.FOUNDATION,-            description = "Build OR: out = a | b",-            hint = "De Morgan: NAND(NOT a, NOT b)",-            inputs = listOf("a", "b"),-            outputs = listOf("out"),-            targetChipId = "OR",-            allowedChipIds = listOf("NAND", "NOT", "AND"),-            flavor = "De Morgan is your friend.",-            unlocksChipId = "OR",-            prereqs = listOf("AND")-        ),-        LevelDef(-            id = "XOR",-            displayName = "XOR",-            chapter = ChapterId.FOUNDATION,-            description = "Build XOR: out = a ^ b",-            hint = "4 NANDs tricky build.",-            inputs = listOf("a", "b"),-            outputs = listOf("out"),-            targetChipId = "XOR",-            allowedChipIds = listOf("NAND", "NOT", "AND", "OR"),-            flavor = "The key to addition.",-            unlocksChipId = "XOR",-            prereqs = listOf("OR")-        ),-        LevelDef(-            id = "NOR",-            displayName = "NOR",-            chapter = ChapterId.FOUNDATION,-            description = "Build NOR: out = !(a | b)",-            hint = "OR then NOT.",-            inputs = listOf("a", "b"),-            outputs = listOf("out"),-            targetChipId = "NOR",-            allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR"),-            unlocksChipId = "NOR",-            prereqs = listOf("XOR")-        ),-        LevelDef(-            id = "XNOR",-            displayName = "XNOR",-            chapter = ChapterId.FOUNDATION,-            description = "Build XNOR: equality",-            hint = "XOR then NOT.",-            inputs = listOf("a", "b"),-            outputs = listOf("out"),-            targetChipId = "XNOR",-            allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "NOR"),-            unlocksChipId = "XNOR",-            prereqs = listOf("XOR")-        ),-        // ROUTING-        LevelDef(-            id = "MUX",-            displayName = "MUX",-            chapter = ChapterId.ROUTING,-            description = "If sel=0 out=a else b",-            hint = "(a & !sel) | (b & sel)",-            inputs = listOf("a", "b", "sel"),-            outputs = listOf("out"),-            targetChipId = "MUX",-            allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR"),-            flavor = "Choose between signals.",-            unlocksChipId = "MUX",-            prereqs = listOf("NOR", "XNOR")-        ),-        LevelDef(-            id = "DMUX",-            displayName = "DMUX",-            chapter = ChapterId.ROUTING,-            description = "Route in to a if sel=0 else b",-            hint = "a = in & !sel, b = in & sel",-            inputs = listOf("in", "sel"),-            outputs = listOf("a", "b"),-            targetChipId = "DMUX",-            allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX"),-            unlocksChipId = "DMUX",-            prereqs = listOf("MUX")-        ),-        LevelDef(-            id = "MUX4",-            displayName = "MUX4",-            chapter = ChapterId.ROUTING,-            description = "sel1 sel0: 00->a 01->b 10->c 11->d",-            hint = "3 MUXes.",-            inputs = listOf("a", "b", "c", "d", "sel0", "sel1"),-            outputs = listOf("out"),-            targetChipId = "MUX4",-            allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX", "DMUX"),-            unlocksChipId = "MUX4",-            prereqs = listOf("MUX")-        ),-        // ARITH-        LevelDef(-            id = "HALF_ADDER",-            displayName = "Half Adder",-            chapter = ChapterId.ARITH,-            description = "sum=a^b carry=a&b",-            hint = "XOR + AND",-            inputs = listOf("a", "b"),-            outputs = listOf("sum", "carry"),-            targetChipId = "HALF_ADDER",-            allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX"),-            flavor = "1-bit addition.",-            unlocksChipId = "HALF_ADDER",-            prereqs = listOf("DMUX", "MUX4")-        ),-        LevelDef(-            id = "FULL_ADDER",-            displayName = "Full Adder",-            chapter = ChapterId.ARITH,-            description = "Add with carry",-            hint = "Two half-adders + OR",-            inputs = listOf("a", "b", "cin"),-            outputs = listOf("sum", "cout"),-            targetChipId = "FULL_ADDER",-            allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX", "HALF_ADDER"),-            flavor = "Brick of binary addition.",-            unlocksChipId = "FULL_ADDER",-            prereqs = listOf("HALF_ADDER")-        ),-        LevelDef(-            id = "ADDER_4",-            displayName = "Adder4",-            chapter = ChapterId.ARITH,-            description = "Add two 4-bit numbers",-            hint = "Chain FullAdders",-            inputs = listOf("a0","a1","a2","a3","b0","b1","b2","b3"),-            outputs = listOf("s0","s1","s2","s3","cout"),-            targetChipId = "ADDER_4",-            allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "HALF_ADDER", "FULL_ADDER"),-            unlocksChipId = "ADDER_4",-            prereqs = listOf("HALF_ADDER")-        ),-        LevelDef(-            id = "ADDER_8",-            displayName = "Adder8",-            chapter = ChapterId.ARITH,-            description = "Add two 8-bit numbers",-            hint = "Chain 8 FullAdders",-            inputs = (0..7).map { "a$it" } + (0..7).map { "b$it" },-            outputs = (0..7).map { "s$it" } + listOf("cout"),-            targetChipId = "ADDER_8",-            allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "HALF_ADDER", "FULL_ADDER", "ADDER_4"),-            flavor = "Heart of CPU.",-            unlocksChipId = "ADDER_8",-            prereqs = listOf("FULL_ADDER", "ADDER_4")-        ),-        // MEMORY-        LevelDef(-            id = "DFF",-            displayName = "DFF",-            chapter = ChapterId.MEMORY,-            description = "On tick, Q = D",-            hint = "NAND latch combinational sim.",-            inputs = listOf("d", "clk"),-            outputs = listOf("q"),-            targetChipId = "DFF",-            allowedChipIds = listOf("NAND", "NOT", "AND", "OR", "XOR", "MUX"),-            flavor = "Time enters.",-            unlocksChipId = "DFF",-            prereqs = listOf("ADDER_8")-        ),-        LevelDef(-            id = "BIT",-            displayName = "Bit",-            chapter = ChapterId.MEMORY,-            description = "If load=1 store in",-            hint = "MUX + DFF",-            inputs = listOf("in", "load"),-            outputs = listOf("out"),-            targetChipId = "BIT",-            allowedChipIds = ChipLibrary.all.keys.filter { it != "CPU_8" && it != "REG_8" && it != "ALU_8" }.toList(),-            unlocksChipId = "BIT",-            prereqs = listOf("DFF")-        ),-        LevelDef(-            id = "REG_8",-            displayName = "Reg8",-            chapter = ChapterId.MEMORY,-            description = "8-bit register with load",-            hint = "8x BIT sharing load",-            inputs = (0..7).map { "in$it" } + listOf("load"),-            outputs = (0..7).map { "out$it" },-            targetChipId = "REG_8",-            allowedChipIds = ChipLibrary.all.keys.filter { it != "CPU_8" && it != "ALU_8" }.toList(),-            unlocksChipId = "REG_8",-            prereqs = listOf("BIT")-        ),-        // CPU-        LevelDef(-            id = "ALU_8",-            displayName = "ALU",-            chapter = ChapterId.CPU,-            description = "op 00=ADD 01=AND 10=OR 11=XOR + flags",-            hint = "Mux between results",-            inputs = (0..7).map { "a$it" } + (0..7).map { "b$it" } + listOf("op0","op1"),-            outputs = (0..7).map { "out$it" } + listOf("zero","carry"),-            targetChipId = "ALU_8",-            allowedChipIds = ChipLibrary.all.keys.filter { it != "CPU_8" }.toList(),-            flavor = "Calculator of CPU.",-            unlocksChipId = "ALU_8",-            prereqs = listOf("REG_8")-        ),-        LevelDef(-            id = "CPU_8",-            displayName = "CPU",-            chapter = ChapterId.CPU,-            description = "8-bit CPU capstone",-            hint = "ALU + Registers + MUX",-            inputs = (0..7).map { "in$it" } + listOf("clk", "reset"),-            outputs = (0..7).map { "out$it" } + (0..7).map { "addr$it" } + listOf("write"),-            targetChipId = "CPU_8",-            allowedChipIds = ChipLibrary.all.keys.toList(),-            flavor = "NAND to computer. Done.",-            unlocksChipId = "CPU_8",-            prereqs = listOf("ALU_8")-        )+        // FOUNDATION 6+        LevelDef("NOT","NOT",ChapterId.FOUNDATION,"Build NOT from NAND only","NAND(in,in)=NOT",listOf("in"),outputs=listOf("out"),targetChipId="NOT",allowedChipIds=listOf("NAND"),flavor="Everything starts with NAND",unlocksChipId="NOT"),+        LevelDef("AND","AND",ChapterId.FOUNDATION,"Build AND: a AND b","NOT(NAND(a,b))",listOf("a","b"),outputs=listOf("out"),targetChipId="AND",allowedChipIds=listOf("NAND","NOT"),unlocksChipId="AND",prereqs=listOf("NOT")),+        LevelDef("OR","OR",ChapterId.FOUNDATION,"Build OR: a OR b","NAND(NOT a, NOT b)",listOf("a","b"),outputs=listOf("out"),targetChipId="OR",allowedChipIds=listOf("NAND","NOT","AND"),flavor="De Morgan",unlocksChipId="OR",prereqs=listOf("AND")),+        LevelDef("XOR","XOR",ChapterId.FOUNDATION,"XOR a^b – adder brick","(a&!b)|(!a&b)",listOf("a","b"),outputs=listOf("out"),targetChipId="XOR",allowedChipIds=listOf("NAND","NOT","AND","OR"),flavor="Key to addition",unlocksChipId="XOR",prereqs=listOf("OR")),+        LevelDef("NOR","NOR",ChapterId.FOUNDATION,"NOR !(a|b) – cross for SR latch","OR+NOT",listOf("a","b"),outputs=listOf("out"),targetChipId="NOR",allowedChipIds=listOf("NAND","NOT","AND","OR","XOR"),flavor="NOR->SR latch first memory",unlocksChipId="NOR",prereqs=listOf("XOR")),+        LevelDef("XNOR","XNOR",ChapterId.FOUNDATION,"XNOR equality","NOT XOR",listOf("a","b"),outputs=listOf("out"),targetChipId="XNOR",allowedChipIds=listOf("NAND","NOT","AND","OR","XOR","NOR"),unlocksChipId="XNOR",prereqs=listOf("XOR")),++        // ROUTING BIT – address decode for RAM+        LevelDef("MUX","MUX",ChapterId.ROUTING,"MUX bit sel?b:a steering – CPU control decoder","(a&!sel)|(b&sel)",listOf("a","b","sel"),outputs=listOf("out"),targetChipId="MUX",allowedChipIds=listOf("NAND","NOT","AND","OR","XOR"),flavor="Select like CPU",unlocksChipId="MUX",prereqs=listOf("NOR","XNOR")),+        LevelDef("DMUX","DMUX",ChapterId.ROUTING,"DMUX bit in,sel->a,b route – enables RAM","a=in&!sel b=in&sel",listOf("in","sel"),outputs=listOf("a","b"),targetChipId="DMUX",allowedChipIds=listOf("NAND","NOT","AND","OR","XOR","MUX"),unlocksChipId="DMUX",prereqs=listOf("MUX")),+        LevelDef("MUX4","MUX4",ChapterId.ROUTING,"MUX4 2-bit select 00:a 01:b 10:c 11:d","3 MUXes",listOf("a","b","c","d","sel0","sel1"),outputs=listOf("out"),targetChipId="MUX4",allowedChipIds=listOf("NAND","NOT","AND","OR","XOR","MUX","DMUX"),unlocksChipId="MUX4",prereqs=listOf("MUX")),+        LevelDef("DMUX4","DMUX4",ChapterId.ROUTING,"DMUX4 – 1 address -> 4 cells – RAM write decode core","DMUX tree",listOf("in","sel0","sel1"),outputs=listOf("a","b","c","d"),targetChipId="DMUX4",allowedChipIds=listOf("NAND","NOT","AND","OR","XOR","MUX","DMUX","MUX4"),flavor="Addr->cell for RAM",unlocksChipId="DMUX4",prereqs=listOf("DMUX","MUX4")),+        LevelDef("MUX8","MUX8",ChapterId.ROUTING,"MUX8 tree – RAM read bit from 8 sources","2xMUX4+MUX",listOf("a","b","c","d","e","f","g","h","sel0","sel1","sel2"),outputs=listOf("out"),targetChipId="MUX8",allowedChipIds=listOf("NAND","NOT","AND","OR","XOR","MUX","DMUX","MUX4","DMUX4"),unlocksChipId="MUX8",prereqs=listOf("DMUX4")),+        LevelDef("DMUX8","DMUX8",ChapterId.ROUTING,"DMUX8 write-enable tree – selects one reg to write for bit RAM","DMUX4+ branches",listOf("in","sel0","sel1","sel2"),outputs=listOf("a","b","c","d","e","f","g","h"),targetChipId="DMUX8",allowedChipIds=listOf("NAND","NOT","AND","OR","XOR","MUX","DMUX","MUX4","DMUX4","MUX8"),flavor="Write decode",unlocksChipId="DMUX8",prereqs=listOf("MUX8")),++        // BUS expanders (JOIN bits->bus thick) / contractors (SPLIT bus->bits) – makes heavy levels less tedious+        LevelDef(id="JOIN_8",displayName="JOIN8 Exp 8b",chapter=ChapterId.ROUTING,description="JOIN8 Expander: 8 bits -> BUS8[8] thick blue byte bus – one wire instead of 8 thin","OUT[0]=b0 .. OUT[7]=b7 concat",inputs=(0..7).map{"b$it"},inputWidths=List(8){1},outputs=listOf("OUT"),outputWidths=listOf(8),targetChipId="JOIN_8",allowedChipIds=listOf("NAND","NOT","AND","OR","XOR","MUX","DMUX"),flavor="Bits->Bus expander cuts 8 wires to 1",unlocksChipId="JOIN_8",prereqs=listOf("DMUX8")),+        LevelDef(id="SPLIT_8",displayName="SPLIT8 Cont 8b",chapter=ChapterId.ROUTING,description="SPLIT8 Contractor: BUS8[8] thick blue -> 8 bits – split for bit logic","b0=IN[0]..b7=IN[7]",inputs=listOf("IN"),inputWidths=listOf(8),outputs=(0..7).map{"b$it"},outputWidths=List(8){1},targetChipId="SPLIT_8",allowedChipIds=listOf("NAND","JOIN_8"),flavor="Bus->bits contractor",unlocksChipId="SPLIT_8",prereqs=listOf("JOIN_8")),+        LevelDef(id="JOIN_4",displayName="JOIN4 Exp 4b",chapter=ChapterId.ROUTING,description="JOIN4 Expander: 4 bits->BUS4[4] orange opcode nibble bus","concat nibble",inputs=(0..3).map{"b$it"},inputWidths=List(4){1},outputs=listOf("OUT"),outputWidths=listOf(4),targetChipId="JOIN_4",allowedChipIds=listOf("NAND","NOT","AND","OR","JOIN_8","SPLIT_8"),flavor="4-bit bus for opcode decode",unlocksChipId="JOIN_4",prereqs=listOf("JOIN_8")),+        LevelDef(id="SPLIT_4",displayName="SPLIT4 Cont 4b",chapter=ChapterId.ROUTING,description="SPLIT4 Contractor: BUS4[4] orange -> 4 bits","split nibble",inputs=listOf("IN"),inputWidths=listOf(4),outputs=(0..3).map{"b$it"},outputWidths=List(4){1},targetChipId="SPLIT_4",allowedChipIds=listOf("NAND","JOIN_4","JOIN_8","SPLIT_8"),unlocksChipId="SPLIT_4",prereqs=listOf("JOIN_4")),+        LevelDef(id="MUX_B8",displayName="MUX B8 [8]",chapter=ChapterId.ROUTING,description="MUX_B8 bus: A[8],B[8],sel->OUT[8] byte-wide – CPU addr mux PC vs data","Byte MUX via bit MUXes",inputs=listOf("A","B","sel"),inputWidths=listOf(8,8,1),outputs=listOf("OUT"),outputWidths=listOf(8),targetChipId="MUX_B8",allowedChipIds=ChipLibrary.all.keys.filter{it!="CPU" && it!="COMPUTER"}.toList(),flavor="Byte bus MUX – address mux for program-from-RAM",unlocksChipId="MUX_B8",prereqs=listOf("SPLIT_4")),+        LevelDef(id="MUX4_B8",displayName="MUX4 B8 [8]",chapter=ChapterId.ROUTING,description="MUX4_B8 bus: 4xBUS8 -> BUS8 – RAM64 read stage","2xMUX_B8+MUX_B8",inputs=listOf("A","B","C","D","sel0","sel1"),inputWidths=listOf(8,8,8,8,1,1),outputs=listOf("OUT"),outputWidths=listOf(8),targetChipId="MUX4_B8",allowedChipIds=ChipLibrary.all.keys.filter{it!="CPU" && it!="COMPUTER"}.toList(),unlocksChipId="MUX4_B8",prereqs=listOf("MUX_B8")),++        // ARITH – bus versions reduce tedium+        LevelDef("HALF_ADDER","HalfAdd",ChapterId.ARITH,"Half adder sum=a^b carry=a&b","XOR+AND",listOf("a","b"),outputs=listOf("sum","carry"),targetChipId="HALF_ADDER",allowedChipIds=listOf("NAND","NOT","AND","OR","XOR","MUX","JOIN_8","SPLIT_8"),flavor="1-bit addition",unlocksChipId="HALF_ADDER",prereqs=listOf("MUX4_B8")),+        LevelDef("FULL_ADDER","FullAdd",ChapterId.ARITH,"Full adder with carry","2 half+OR",listOf("a","b","cin"),outputs=listOf("sum","cout"),targetChipId="FULL_ADDER",allowedChipIds=listOf("NAND","NOT","AND","OR","XOR","MUX","HALF_ADDER"),unlocksChipId="FULL_ADDER",prereqs=listOf("HALF_ADDER")),+        LevelDef(id="ADDER_4B",displayName="Adder4 B [4]",chapter=ChapterId.ARITH,description="Adder4 bus A[4]+B[4]->S[4],cout – orange [4] wire","Chain FullAdders, use JOIN_4/SPLIT_4",inputs=listOf("A","B"),inputWidths=listOf(4,4),outputs=listOf("S","cout"),outputWidths=listOf(4,1),targetChipId="ADDER_4B",allowedChipIds=listOf("NAND","NOT","AND","OR","XOR","HALF_ADDER","FULL_ADDER","JOIN_4","SPLIT_4"),unlocksChipId="ADDER_4B",prereqs=listOf("FULL_ADDER")),+        LevelDef(id="ADDER_8B",displayName="Adder8 B [8]",chapter=ChapterId.ARITH,description="Adder8 bus A[8]+B[8]->S[8],cout – data path of CPU – thick blue [8]","2xAdder4B bus or 8xFA, JOIN_8 expander",inputs=listOf("A","B"),inputWidths=listOf(8,8),outputs=listOf("S","cout"),outputWidths=listOf(8,1),targetChipId="ADDER_8B",allowedChipIds=listOf("NAND","NOT","AND","OR","XOR","HALF_ADDER","FULL_ADDER","ADDER_4B","JOIN_8","SPLIT_8"),flavor="Bus data path",unlocksChipId="ADDER_8B",prereqs=listOf("FULL_ADDER","ADDER_4B")),+        LevelDef(id="INC_8",displayName="INC8 Bus [8]",chapter=ChapterId.ARITH,description="INC8 Bus: A[8]->S[8] +1 – needed for PC=PC+1","A+1",inputs=listOf("A"),inputWidths=listOf(8),outputs=listOf("S","cout"),outputWidths=listOf(8,1),targetChipId="INC_8",allowedChipIds=listOf("NAND","NOT","AND","OR","XOR","HALF_ADDER","FULL_ADDER","ADDER_8B"),flavor="PC increments via INC_8",unlocksChipId="INC_8",prereqs=listOf("ADDER_8B")),+        LevelDef(id="SUB_8",displayName="SUB8 B [8]",chapter=ChapterId.ARITH,description="SUB8 bus A[8]-B[8]->S[8],borrow – ALU sub op","A+~B+1",inputs=listOf("A","B"),inputWidths=listOf(8,8),outputs=listOf("S","borrow"),outputWidths=listOf(8,1),targetChipId="SUB_8",allowedChipIds=listOf("NAND","NOT","AND","OR","XOR","ADDER_8B","INC_8","JOIN_8","SPLIT_8"),unlocksChipId="SUB_8",prereqs=listOf("INC_8")),++        // MEMORY – toward program-from-RAM computer+        LevelDef("SR_LATCH","SR Latch",ChapterId.MEMORY,"SR latch NOR cross-coupled – first memory hold via feedback – S=1 sets, R=1 resets","2 NOR cross",listOf("S","R"),outputs=listOf("Q","nQ"),targetChipId="SR_LATCH",allowedChipIds=listOf("NAND","NOR","NOT","AND","OR"),flavor="Time enters – bit remembers via feedback",unlocksChipId="SR_LATCH",prereqs=listOf("SUB_8")),+        LevelDef("DFF","DFF",ChapterId.MEMORY,"D Flip-Flop edge-triggered – on clk rise Q=D","Master-slave",listOf("d","clk"),outputs=listOf("q"),targetChipId="DFF",allowedChipIds=listOf("NAND","NOT","AND","OR","XOR","MUX","SR_LATCH"),flavor="Clocked remember D",unlocksChipId="DFF",prereqs=listOf("SR_LATCH")),+        LevelDef("BIT","Bit",ChapterId.MEMORY,"1-bit register with load – if load=1 store in","MUX+DFF",listOf("in","load"),outputs=listOf("out"),targetChipId="BIT",allowedChipIds=ChipLibrary.all.keys.filter{it!="CPU" && it!="COMPUTER" && it!="RAM_256B"}.toList(),unlocksChipId="BIT",prereqs=listOf("DFF")),+        LevelDef(id="REG_8B",displayName="Reg8 B [8]",chapter=ChapterId.MEMORY,description="Reg8 bus IN[8],load->OUT[8] – accumulator A – thick blue [8]","8xBIT common load – JOIN_8 makes one bus",inputs=listOf("IN","load"),inputWidths=listOf(8,1),outputs=listOf("OUT"),outputWidths=listOf(8),targetChipId="REG_8B",allowedChipIds=ChipLibrary.all.keys.filter{it!="CPU" && it!="COMPUTER"}.toList(),unlocksChipId="REG_8B",prereqs=listOf("BIT")),+        LevelDef(id="RAM_8B",displayName="RAM8 B [8]",chapter=ChapterId.MEMORY,description="RAM8 bus 8x8: IN[8],load,ADDR[3]->OUT[8] – DMUX8_B+ MUX8_B8 – small program mem","DMUX8_B + MUX8_B8 bus",inputs=listOf("IN","load","ADDR"),inputWidths=listOf(8,1,3),outputs=listOf("OUT"),outputWidths=listOf(8),targetChipId="RAM_8B",allowedChipIds=ChipLibrary.all.keys.filter{it!="CPU" && it!="COMPUTER"}.toList(),unlocksChipId="RAM_8B",prereqs=listOf("REG_8B")),+        LevelDef(id="RAM_64B",displayName="RAM64 B [8]",chapter=ChapterId.MEMORY,description="RAM64 bus 64x8 data – 6-bit address","high bits via MUX",inputs=listOf("IN","load","ADDR"),inputWidths=listOf(8,1,6),outputs=listOf("OUT"),outputWidths=listOf(8),targetChipId="RAM_64B",allowedChipIds=ChipLibrary.all.keys.filter{it!="CPU" && it!="COMPUTER"}.toList(),unlocksChipId="RAM_64",prereqs=listOf("RAM_8B")),+        LevelDef(id="PC_8",displayName="PC Bus [8]",chapter=ChapterId.MEMORY,description="Program Counter bus: IN[8],inc,load,reset->OUT[8] – instruction pointer","REG_8B+INC_8+MUX_B8",inputs=listOf("IN","inc","load","reset"),inputWidths=listOf(8,1,1,1),outputs=listOf("OUT"),outputWidths=listOf(8),targetChipId="PC_8",allowedChipIds=ChipLibrary.all.keys.filter{it!="CPU" && it!="COMPUTER"}.toList(),flavor="Where next instruction? PC needed",unlocksChipId="PC_8",prereqs=listOf("REG_8B")),+        LevelDef(id="RAM_256B",displayName="RAM256 Main [8]",chapter=ChapterId.MEMORY,description="RAM256 unified main memory 256x8 von Neumann – program+data share SAME RAM","4xRAM64B hierarchy, thick bus",inputs=listOf("IN","load","ADDR"),inputWidths=listOf(8,1,8),outputs=listOf("OUT"),outputWidths=listOf(8),targetChipId="RAM_256B",allowedChipIds=ChipLibrary.all.keys.filter{it!="CPU" && it!="COMPUTER"}.toList(),flavor="Main memory – programs live here too",unlocksChipId="RAM_256B",prereqs=listOf("RAM_64B","PC_8")),++        // CPU – fetch/decode/execute FROM RAM+        LevelDef(id="ALU_8",displayName="ALU Bus [8]",chapter=ChapterId.CPU,description="ALU bus 8-bit: A[8],B[8],OP[3]->OUT[8],zero,carry,neg – OP 000ADD 001SUB 010AND 011OR 100XOR 101NOT 110INC 111DEC","Byte ALU – bus cuts tedium from 16 thin to 2 thick",inputs=listOf("A","B","OP"),inputWidths=listOf(8,8,3),outputs=listOf("OUT","zero","carry","neg"),outputWidths=listOf(8,1,1,1),targetChipId="ALU_8",allowedChipIds=ChipLibrary.all.keys.filter{it!="CPU" && it!="COMPUTER"}.toList(),flavor="Calculator of CPU – ALU with flags",unlocksChipId="ALU_8",prereqs=listOf("RAM_256B","SUB_8")),+        LevelDef(id="CPU",displayName="CPU Bus [4][8]",chapter=ChapterId.CPU,description="CPU bus accumulator fetch-decode-execute FROM RAM: Inputs OPCODE[4] orange bus via SPLIT_4 decode, ADDR[8] blue bus, DATA[8] blue from RAM main memory reset->OUT[8],writeM,ADDR_M[8],PC[8]. ISA: LDA addr A=RAM[addr], STA RAM[addr]=A, ADD, SUB, JMP, JZ (needs zero flag), LDI, HLT. Needs PC_8 inc via INC_8, ALU_8, REG_8B A register, DMUX8 opcode->control, MUX_B8 bus address mux PC vs ADDR_M because RAM shared program+data.","PC_8+ALU_8+REG_8B+MUX_B8",inputs=listOf("OPCODE","ADDR","DATA","reset"),inputWidths=listOf(4,8,8,1),outputs=listOf("OUT","writeM","ADDR_M","PC"),outputWidths=listOf(8,1,8,8),targetChipId="CPU",allowedChipIds=ChipLibrary.all.keys.toList(),flavor="Fetch-decode-execute – program code FROM RAM",unlocksChipId="CPU",prereqs=listOf("ALU_8")),+        LevelDef(id="CPU_8",displayName="CPU compat",chapter=ChapterId.CPU,description="CPU compat alias for old saves","Same as CPU bus",inputs=listOf("OPCODE","ADDR","DATA","reset"),inputWidths=listOf(4,8,8,1),outputs=listOf("OUT","writeM","ADDR_M","PC"),outputWidths=listOf(8,1,8,8),targetChipId="CPU_8",allowedChipIds=ChipLibrary.all.keys.toList(),unlocksChipId="CPU_8",prereqs=listOf("CPU")),+        LevelDef(id="COMPUTER",displayName="Computer RAM [8]",chapter=ChapterId.CPU,description="Final stored-program Computer: CPU+RAM_256B Main Memory unified + MUX_B8 address mux + JOIN/SPLIT bus [4][8]. von Neumann: RAM holds both instruction bytes (OPCODE[4] orange + ADDR[8] blue) and data bytes same space. Ref program mem[16]=5,17=3 prog @0 LDA16 ADD17 STA18 HLT -> RAM[18]=8 -> OUT[8]=8. Must wire CPU.PC[8] blue->MUX_B8 A[8] for fetch, CPU.ADDR_M[8]->MUX_B8 B[8] for data, MUX.OUT[8]->RAM ADDR[8] bus, RAM.OUT[8]->CPU.DATA[8] bus and via SPLIT_4 contractor->OPCODE[4] orange for decode, CPU.OUT[8]->RAM.IN[8] bus. Need bus converters.","Von Neumann: PC[8]->MUX_B8 A, ADDR_M->B, MUX->RAM ADDR, RAM OUT[8]->CPU DATA + SPLIT_4 opcode",inputs=listOf("reset"),inputWidths=listOf(1),outputs=listOf("OUT"),outputWidths=listOf(8),targetChipId="COMPUTER",allowedChipIds=ChipLibrary.all.keys.toList(),flavor="NAND->Computer running program FROM RAM (von Neumann) 1/4/8-bit buses",unlocksChipId="COMPUTER",prereqs=listOf("CPU_8"))     )      val chapters: List<Chapter> = listOf(-        Chapter(ChapterId.FOUNDATION, "Foundation", "Build basic gates", all.filter { it.chapter == ChapterId.FOUNDATION }.map { it.id }),-        Chapter(ChapterId.ROUTING, "Routing", "Steer signals", all.filter { it.chapter == ChapterId.ROUTING }.map { it.id }),-        Chapter(ChapterId.ARITH, "Arithmetic", "Make numbers add", all.filter { it.chapter == ChapterId.ARITH }.map { it.id }),-        Chapter(ChapterId.MEMORY, "Memory", "Remember", all.filter { it.chapter == ChapterId.MEMORY }.map { it.id }),-        Chapter(ChapterId.CPU, "CPU", "The machine", all.filter { it.chapter == ChapterId.CPU }.map { it.id }),+        Chapter(ChapterId.FOUNDATION,"Foundation","NAND->XNOR basics",all.filter{it.chapter==ChapterId.FOUNDATION}.map{it.id}),+        Chapter(ChapterId.ROUTING,"Routing + Bus","Muxes + JOIN/SPLIT expander/contractor bus [4][8] – less tedious – address decode",all.filter{it.chapter==ChapterId.ROUTING}.map{it.id}),+        Chapter(ChapterId.ARITH,"Arithmetic Bus","Bus adders orange [4] blue [8] + INC_8 PC+1 + SUB_8 ALU",all.filter{it.chapter==ChapterId.ARITH}.map{it.id}),+        Chapter(ChapterId.MEMORY,"Memory -> Main","Latch->DFF->REG_B bus->RAM hierarchy bus->PC->RAM256B unified prog+data",all.filter{it.chapter==ChapterId.MEMORY}.map{it.id}),+        Chapter(ChapterId.CPU,"CPU -> Computer RAM","ALU bus -> CPU bus fetch from RAM -> COMPUTER stored-program",all.filter{it.chapter==ChapterId.CPU}.map{it.id}),     )      val byId: Map<String, LevelDef> = all.associateBy { it.id }-    fun get(id: String): LevelDef = byId[id] ?: error("Unknown level $id")+    fun get(id: String): LevelDef = byId[id] ?: error("Unknown level $id – use JOIN_8 expander or SPLIT_8 contractor")      val timelineRows: List<List<String>> = listOf(-        listOf("NOT"),-        listOf("AND"),-        listOf("OR"),-        listOf("XOR"),-        listOf("NOR", "XNOR"),-        listOf("MUX"),-        listOf("DMUX", "MUX4"),-        listOf("HALF_ADDER"),-        listOf("FULL_ADDER", "ADDER_4"),-        listOf("ADDER_8"),-        listOf("DFF"),-        listOf("BIT"),-        listOf("REG_8"),-        listOf("ALU_8"),-        listOf("CPU_8")+        listOf("NOT"),listOf("AND"),listOf("OR"),listOf("XOR"),listOf("NOR","XNOR"),+        listOf("MUX"),listOf("DMUX","MUX4"),listOf("DMUX4"),listOf("MUX8"),listOf("DMUX8"),+        listOf("JOIN_8","JOIN_4"),listOf("SPLIT_8","SPLIT_4"),listOf("MUX_B8","MUX4_B8"),+        listOf("HALF_ADDER"),listOf("FULL_ADDER","ADDER_4B"),listOf("ADDER_8B"),listOf("INC_8"),listOf("SUB_8"),+        listOf("SR_LATCH"),listOf("DFF"),listOf("BIT"),listOf("REG_8B"),listOf("RAM_8B","PC_8"),listOf("RAM_64B"),listOf("RAM_256B"),+        listOf("ALU_8"),listOf("CPU"),listOf("CPU_8"),listOf("COMPUTER")     ) -    fun availableLevels(completed: Set<String>): Set<String> {-        return all.filter { it.id !in completed && it.prereqs.all { p -> p in completed } }.map { it.id }.toSet()-    }+    fun availableLevels(completed: Set<String>): Set<String> = all.filter{ it.id !in completed && it.prereqs.all{ p-> p in completed } }.map{ it.id }.toSet() }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CanvasTransform.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CanvasTransform.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CanvasTransform.ktnew file mode 100644index 0000000000..2ebb01b9ed--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CanvasTransform.kt@@ -0,0 +1,58 @@+package com.vayunmathur.games.logicgate.ui++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size++/**+ * Viewport + clamping. World can be larger than screen; canvas responsive.+ * Fixes bug: hardcoded 920f output terminals off-screen portrait.+ */+data class CanvasViewport(val offset: Offset = Offset.Zero, val scale: Float = 1f) {+  fun worldToScreen(p: Offset): Offset = (p - offset) * scale+  fun screenToWorld(p: Offset): Offset = p / scale + offset+}++fun clampGate(pos: Offset, w: Float, h: Float, canvasSize: Size): Offset {+  if (canvasSize.width <= 0f || canvasSize.height <= 0f) return Offset(pos.x.coerceAtLeast(0f), pos.y.coerceAtLeast(0f))+  val half = 12f+  val minX = half+  val minY = half+  val maxX = (canvasSize.width - w - half).coerceAtLeast(minX)+  val maxY = (canvasSize.height - h - half).coerceAtLeast(minY)+  return Offset(pos.x.coerceIn(minX, maxX), pos.y.coerceIn(minY, maxY))+}++fun clampTerm(center: Offset, pillW: Float, canvasSize: Size, padding: Float): Offset {+  if (canvasSize.width <= 0f || canvasSize.height <= 0f) return center+  val half = pillW / 2f + padding+  val maxX = (canvasSize.width - half).coerceAtLeast(half)+  val minX = half+  val minY = padding + 22f+  val maxY = (canvasSize.height - padding - 22f).coerceAtLeast(minY)+  return Offset(center.x.coerceIn(minX, maxX), center.y.coerceIn(minY, maxY))+}++/**+ * Responsive default positions for I/O terminals – fixes portrait off-screen bug.+ * Inputs left side, outputs right edge relative to current canvasSize.+ */+fun defaultInputPos(idx: Int, canvasSize: Size, pillW: Float = 86f): Offset {+  val padding = 20f+  val spacing = if (canvasSize.height > 0f) {+    val available = canvasSize.height - padding * 2f - 44f+    val per = available / 8f+    per.coerceIn(42f, 62f)+  } else 56f+  return Offset(padding + pillW / 2f, padding + 44f + idx * spacing)+}++fun defaultOutputPos(idx: Int, canvasSize: Size, pillW: Float = 86f): Offset {+  val padding = 20f+  val spacing = if (canvasSize.height > 0f) {+    val available = canvasSize.height - padding * 2f - 44f+    val per = available / 8f+    per.coerceIn(42f, 62f)+  } else 56f+  val x = if (canvasSize.width > 0f) canvasSize.width - padding - pillW / 2f else 320f+  return Offset(x, padding + 44f + idx * spacing)+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.ktindex 94c32e5a8e..76d2cd12bc 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.kt@@ -10,36 +10,51 @@ import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.PathEffect import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.input.pointer.changedToUpIgnoreConsumed import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.drawText import androidx.compose.ui.text.rememberTextMeasurer+import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.vayunmathur.games.logicgate.data.*+import kotlin.math.abs+import kotlin.math.hypot import kotlin.math.max import kotlin.math.min -data class GateRect(val chip: PlacedChip, val left: Float, val top: Float, val width: Float, val height: Float) {+data class GateBox(val chip: PlacedChip, val left: Float, val top: Float, val w: Float, val h: Float) {     fun inputPos(i: Int, count: Int): Offset {-        if (count <= 1) return Offset(left, top + height / 2f)-        val gap = height / (count + 1)+        if (count <= 1) return Offset(left, top + h / 2f)+        val gap = h / (count + 1)         return Offset(left, top + gap * (i + 1))     }     fun outputPos(i: Int, count: Int): Offset {-        if (count <= 1) return Offset(left + width, top + height / 2f)-        val gap = height / (count + 1)-        return Offset(left + width, top + gap * (i + 1))+        if (count <= 1) return Offset(left + w, top + h / 2f)+        val gap = h / (count + 1)+        return Offset(left + w, top + gap * (i + 1))     }-    fun bodyContains(p: Offset): Boolean = p.x in left..left + width && p.y in top..top + height+    fun bodyContains(p: Offset): Boolean = p.x in left..left + w && p.y in top..top + h } -data class IoTerminalLayout(val index: Int, val center: Offset, val name: String, val isInput: Boolean)-private enum class DragMode { None, Gate, InputTerm, OutputTerm, Wire }-private data class HitOutput(val end: WireEnd, val pos: Offset)-private data class HitInput(val end: WireEnd, val pos: Offset)+data class TerminalBox(val idx: Int, val center: Offset, val name: String, val isInput: Boolean, val pillW: Float)+data class HitOutput(val end: WireEnd, val pos: Offset)+data class HitInput(val end: WireEnd, val pos: Offset)++sealed class DragMode {+    object None : DragMode()+    data class Gate(val id: String, val grabOffset: Offset, val start: Offset, val startLeft: Float, val startTop: Float) : DragMode()+    data class InputTerm(val idx: Int, val start: Offset) : DragMode()+    data class OutputTerm(val idx: Int, val start: Offset) : DragMode()+    data class Wiring(val from: WireEnd, val fromPos: Offset, var cur: Offset) : DragMode()+}  @Composable fun CircuitCanvas(@@ -54,8 +69,11 @@ fun CircuitCanvas(     onStartWiring: (WireEnd) -> Unit,     onCancelWiring: () -> Unit,     onGateMove: (id: String, x: Float, y: Float) -> Unit,+    onGateMoveFinished: (id: String, x: Float, y: Float) -> Unit,     onInputTermMove: (idx: Int, x: Float, y: Float) -> Unit,+    onInputTermMoveFinished: (idx: Int, x: Float, y: Float) -> Unit,     onOutputTermMove: (idx: Int, x: Float, y: Float) -> Unit,+    onOutputTermMoveFinished: (idx: Int, x: Float, y: Float) -> Unit,     onGateDelete: (String) -> Unit,     onWireDelete: (String) -> Unit,     onOutputMapDelete: (Int) -> Unit,@@ -63,139 +81,144 @@ fun CircuitCanvas(     onGhostLine: (Offset?) -> Unit,     modifier: Modifier = Modifier ) {+    val density = LocalDensity.current+    val haptic = LocalHapticFeedback.current     val textMeasurer = rememberTextMeasurer()-    fun computeRects(): List<GateRect> = gates.map { g ->-        val def = ChipLibrary.get(g.chipId)-        val w = when {-            def.inputCount > 8 || def.outputCount > 8 -> 154f-            def.inputCount > 4 || def.outputCount > 4 -> 134f-            else -> 118f-        }-        val h = max(54f, 19f * max(def.inputCount, def.outputCount) + 28f)-        GateRect(g, g.x, g.y, w, h)-    }+    var canvasSizePx by remember { mutableStateOf(Size.Zero) } -    var rects by remember(gates) { mutableStateOf(computeRects()) }-    rects = computeRects()-    val rectById = rects.associateBy { it.chip.instanceId }-    val chipDefs = gates.associate { it.instanceId to ChipLibrary.get(it.chipId) }+    val pinHitR = with(density) { 24.dp.toPx() }+    val termMoveHitR = with(density) { 40.dp.toPx() }+    val termWireDotR = with(density) { 20.dp.toPx() }+    val wireHitThreshold = with(density) { 32.dp.toPx() } -    fun defaultInputPos(idx: Int) = Offset(32f, 78f + idx * 56f)-    fun defaultOutputPos(idx: Int) = Offset(920f, 78f + idx * 56f)--    val inputLayouts = level.inputs.mapIndexed { i, name ->-        val p = inputPositions[i]-        IoTerminalLayout(i, if (p != null) Offset(p.x, p.y) else defaultInputPos(i), name, true)-    }-    val outputLayouts = level.outputs.mapIndexed { i, name ->-        val p = outputPositions[i]-        IoTerminalLayout(i, if (p != null) Offset(p.x, p.y) else defaultOutputPos(i), name, false)+    fun gateSizeFor(def: ChipDef): Pair<Float, Float> {+        val maxPins = max(def.inputCount, def.outputCount)+        val wDp = when { maxPins > 8 -> 154.dp; maxPins > 4 -> 134.dp; else -> 118.dp }+        val hDp = if (maxPins <= 2) 54.dp else (19.dp * maxPins + 28.dp).coerceAtLeast(54.dp)+        return with(density) { wDp.toPx() to hDp.toPx() }     } -    val latestRects by rememberUpdatedState(rects)-    val latestInputLayouts by rememberUpdatedState(inputLayouts)-    val latestOutputLayouts by rememberUpdatedState(outputLayouts)-    val latestWires by rememberUpdatedState(wires)-    val latestOutputMaps by rememberUpdatedState(outputMaps)-    val latestWiringFrom by rememberUpdatedState(wiringFrom)-    val latestChipDefs by rememberUpdatedState(chipDefs)-    val latestRectById by rememberUpdatedState(rectById)--    val currentOnCreateWire by rememberUpdatedState(onCreateWire)-    val currentOnStartWiring by rememberUpdatedState(onStartWiring)-    val currentOnCancelWiring by rememberUpdatedState(onCancelWiring)-    val currentOnGateMove by rememberUpdatedState(onGateMove)-    val currentOnInputMove by rememberUpdatedState(onInputTermMove)-    val currentOnOutputMove by rememberUpdatedState(onOutputTermMove)-    val currentOnGateDelete by rememberUpdatedState(onGateDelete)-    val currentOnWireDelete by rememberUpdatedState(onWireDelete)-    val currentOnOutputMapDelete by rememberUpdatedState(onOutputMapDelete)-    val currentOnGhostLine by rememberUpdatedState(onGhostLine)--    var dragMode by remember { mutableStateOf(DragMode.None) }-    var draggedGateId by remember { mutableStateOf<String?>(null) }-    var wiringStart by remember { mutableStateOf<HitOutput?>(null) }--    val pinHitR = 26f-    val termMoveHitR = 44f-    val termWireDotR = 18f+    val gateBoxes: List<GateBox> = remember(gates) {+        gates.map { g ->+            val def = ChipLibrary.get(g.chipId)+            val (w, h) = gateSizeFor(def)+            GateBox(g, g.x, g.y, w, h)+        }+    }+    val rectById = remember(gateBoxes) { gateBoxes.associateBy { it.chip.instanceId } }+    val chipDefs = remember(gates) { gates.associate { it.instanceId to ChipLibrary.get(it.chipId) } } -    fun pillW(name: String) = 70f + name.length * 3.6f-    fun dotForInput(t: IoTerminalLayout) = Offset(t.center.x + pillW(t.name) / 2f - 10f, t.center.y)-    fun dotForOutput(t: IoTerminalLayout) = Offset(t.center.x - pillW(t.name) / 2f + 10f, t.center.y)+    fun pillW(name: String): Float = with(density) { 72.dp.toPx() + name.length * 3.6f } -    fun hitOutputDot(pos: Offset): HitOutput? {-        for (t in latestInputLayouts) if ((pos - dotForInput(t)).getDistance() < termWireDotR) return HitOutput(WireEnd("__IN_${t.index}", 0), dotForInput(t))-        for (gr in latestRects) {-            val def = latestChipDefs[gr.chip.instanceId] ?: continue-            for (j in 0 until def.outputCount) {-                val pp = gr.outputPos(j, def.outputCount)-                if ((pos - pp).getDistance() < pinHitR) return HitOutput(WireEnd(gr.chip.instanceId, j), pp)-            }+    val inputLayouts: List<TerminalBox> = remember(level.inputs, inputPositions, canvasSizePx) {+        level.inputs.mapIndexed { i, name ->+            val default = defaultInputPos(i, canvasSizePx, pillW(name))+            val p = inputPositions[i]+            val center = if (p != null) Offset(p.x, p.y) else default+            TerminalBox(i, center, name, true, pillW(name))         }-        return null     }-    fun hitInputDot(pos: Offset): HitInput? {-        for (gr in latestRects) {-            val def = latestChipDefs[gr.chip.instanceId] ?: continue-            for (j in 0 until def.inputCount) {-                val pp = gr.inputPos(j, def.inputCount)-                if ((pos - pp).getDistance() < pinHitR) return HitInput(WireEnd(gr.chip.instanceId, j), pp)-            }+    val outputLayouts: List<TerminalBox> = remember(level.outputs, outputPositions, canvasSizePx) {+        level.outputs.mapIndexed { i, name ->+            val default = defaultOutputPos(i, canvasSizePx, pillW(name))+            val p = outputPositions[i]+            val center = if (p != null) Offset(p.x, p.y) else default+            TerminalBox(i, center, name, false, pillW(name))         }-        for (t in latestOutputLayouts) if ((pos - dotForOutput(t)).getDistance() < termWireDotR) return HitInput(WireEnd("__OUT_${t.index}", 0), dotForOutput(t))-        return null     }-    fun hitGateBody(pos: Offset): PlacedChip? = latestRects.reversed().firstOrNull { it.bodyContains(pos) }?.chip-    fun hitInputTermMove(pos: Offset): IoTerminalLayout? = latestInputLayouts.firstOrNull { (pos - it.center).getDistance() < termMoveHitR }-    fun hitOutputTermMove(pos: Offset): IoTerminalLayout? = latestOutputLayouts.firstOrNull { (pos - it.center).getDistance() < termMoveHitR }++    fun dotForInput(t: TerminalBox): Offset = Offset(t.center.x + t.pillW / 2f - with(density) { 10.dp.toPx() }, t.center.y)+    fun dotForOutput(t: TerminalBox): Offset = Offset(t.center.x - t.pillW / 2f + with(density) { 10.dp.toPx() }, t.center.y)      fun resolveSource(end: WireEnd): Offset? {         if (end.instanceId.startsWith("__IN_")) {             val idx = end.instanceId.removePrefix("__IN_").toIntOrNull() ?: return null-            return latestInputLayouts.find { it.index == idx }?.let { dotForInput(it) }+            return inputLayouts.find { it.idx == idx }?.let { dotForInput(it) }         }-        val gr = latestRectById[end.instanceId] ?: return null-        val def = latestChipDefs[end.instanceId] ?: return null+        val gr = rectById[end.instanceId] ?: return null+        val def = chipDefs[end.instanceId] ?: return null         return gr.outputPos(end.pinIndex.coerceIn(0, max(0, def.outputCount - 1)), def.outputCount)     }     fun resolveSink(end: WireEnd): Offset? {         if (end.instanceId.startsWith("__OUT_")) {             val idx = end.instanceId.removePrefix("__OUT_").toIntOrNull() ?: return null-            return latestOutputLayouts.find { it.index == idx }?.let { dotForOutput(it) }+            return outputLayouts.find { it.idx == idx }?.let { dotForOutput(it) }         }-        val gr = latestRectById[end.instanceId] ?: return null-        val def = latestChipDefs[end.instanceId] ?: return null+        val gr = rectById[end.instanceId] ?: return null+        val def = chipDefs[end.instanceId] ?: return null         return gr.inputPos(end.pinIndex.coerceIn(0, max(0, def.inputCount - 1)), def.inputCount)     }++    fun hitOutputDot(pos: Offset): HitOutput? {+        for (t in inputLayouts) if ((pos - dotForInput(t)).getDistance() < termWireDotR) return HitOutput(WireEnd("__IN_${t.idx}", 0), dotForInput(t))+        for (box in gateBoxes) {+            val def = chipDefs[box.chip.instanceId] ?: continue+            for (j in 0 until def.outputCount) {+                val pp = box.outputPos(j, def.outputCount)+                if ((pos - pp).getDistance() < pinHitR) return HitOutput(WireEnd(box.chip.instanceId, j), pp)+            }+        }+        return null+    }+    fun hitInputDot(pos: Offset): HitInput? {+        for (box in gateBoxes) {+            val def = chipDefs[box.chip.instanceId] ?: continue+            for (j in 0 until def.inputCount) {+                val pp = box.inputPos(j, def.inputCount)+                if ((pos - pp).getDistance() < pinHitR) return HitInput(WireEnd(box.chip.instanceId, j), pp)+            }+        }+        for (t in outputLayouts) if ((pos - dotForOutput(t)).getDistance() < termWireDotR) return HitInput(WireEnd("__OUT_${t.idx}", 0), dotForOutput(t))+        return null+    }+    fun hitGateBody(pos: Offset): GateBox? = gateBoxes.reversed().firstOrNull { it.bodyContains(pos) }+    fun hitInputTermMove(pos: Offset): TerminalBox? = inputLayouts.firstOrNull { (pos - it.center).getDistance() < termMoveHitR }+    fun hitOutputTermMove(pos: Offset): TerminalBox? = outputLayouts.firstOrNull { (pos - it.center).getDistance() < termMoveHitR }+     fun findClosestWire(pos: Offset): Wire? {-        var best: Wire? = null-        var bestD = 28f-        for (w in latestWires) {-            val a = resolveSource(w.from) ?: continue-            val b = resolveSink(w.to) ?: continue+        var best: Wire? = null; var bestD = wireHitThreshold+        for (w in wires) {+            val a = resolveSource(w.from) ?: continue; val b = resolveSink(w.to) ?: continue             val d = distPointToBezier(pos, a, b)             if (d < bestD) { bestD = d; best = w }         }         return best     }     fun findClosestOutputMap(pos: Offset): OutputMapping? {-        var best: OutputMapping? = null-        var bestD = 28f-        for (om in latestOutputMaps) {+        var best: OutputMapping? = null; var bestD = wireHitThreshold+        for (om in outputMaps) {             val a = resolveSource(om.from) ?: continue-            val b = latestOutputLayouts.find { it.index == om.outputIndex }?.let { dotForOutput(it) } ?: continue+            val b = outputLayouts.find { it.idx == om.outputIndex }?.let { dotForOutput(it) } ?: continue             val d = distPointToBezier(pos, a, b)             if (d < bestD) { bestD = d; best = om }         }         return best     } +    var draggedGateId by remember { mutableStateOf<String?>(null) }+    var wiringStartLocal by remember { mutableStateOf<HitOutput?>(null) }++    val currentOnCreateWire by rememberUpdatedState(onCreateWire)+    val currentOnStartWiring by rememberUpdatedState(onStartWiring)+    val currentOnCancelWiring by rememberUpdatedState(onCancelWiring)+    val currentOnGateMove by rememberUpdatedState(onGateMove)+    val currentOnGateMoveFinished by rememberUpdatedState(onGateMoveFinished)+    val currentOnInputMove by rememberUpdatedState(onInputTermMove)+    val currentOnInputMoveFinished by rememberUpdatedState(onInputTermMoveFinished)+    val currentOnOutputMove by rememberUpdatedState(onOutputTermMove)+    val currentOnOutputMoveFinished by rememberUpdatedState(onOutputTermMoveFinished)+    val currentOnGateDelete by rememberUpdatedState(onGateDelete)+    val currentOnWireDelete by rememberUpdatedState(onWireDelete)+    val currentOnOutputMapDelete by rememberUpdatedState(onOutputMapDelete)+    val currentOnGhostLine by rememberUpdatedState(onGhostLine)+    val latestWiringFrom by rememberUpdatedState(wiringFrom)+     Canvas(         modifier = modifier             .fillMaxSize()             .background(Color(0xFF0C141D))-            .pointerInput(Unit) {+            .onSizeChanged { canvasSizePx = Size(it.width.toFloat(), it.height.toFloat()) }+            .pointerInput(gates, wires, inputPositions, outputPositions, canvasSizePx) {                 awaitPointerEventScope {                     while (true) {                         val down = awaitFirstDown(requireUnconsumed = false)@@ -203,49 +226,46 @@ fun CircuitCanvas(                         var currentPos = downPos                         var totalDrag = Offset.Zero                         var isDragStarted = false-                        var mode = DragMode.None-                        var gateId: String? = null+                        var mode: DragMode = DragMode.None                         var gateStartLeft = 0f                         var gateStartTop = 0f-                        var inputIdx: Int? = null-                        var outputIdx: Int? = null                         var inputStart = Offset.Zero                         var outputStart = Offset.Zero                         var wireStart: HitOutput? = null -                        // At down, check what's underneath – dot hits take priority for wiring                         val outDotAtDown = hitOutputDot(downPos)                         val inDotAtDown = hitInputDot(downPos)-                        val gateAtDown = if (outDotAtDown == null && inDotAtDown == null) hitGateBody(downPos) else null+                        val gateBoxAtDown = if (outDotAtDown == null && inDotAtDown == null) hitGateBody(downPos) else null+                        val gateAtDown = gateBoxAtDown?.chip                         val inTermMoveAtDown = if (outDotAtDown == null && gateAtDown == null) hitInputTermMove(downPos) else null                         val outTermMoveAtDown = if (outDotAtDown == null && gateAtDown == null && inTermMoveAtDown == null) hitOutputTermMove(downPos) else null                         val downTime = System.currentTimeMillis()                         var longPressHandled = false +                        if (outDotAtDown != null) {+                            wireStart = outDotAtDown+                            wiringStartLocal = outDotAtDown+                            mode = DragMode.Wiring(outDotAtDown.end, outDotAtDown.pos, outDotAtDown.pos)+                            currentOnStartWiring(outDotAtDown.end)+                            currentOnGhostLine(outDotAtDown.pos)+                        }+                         while (true) {                             val event = awaitPointerEvent()                             val main = event.changes.firstOrNull { it.id == down.id } ?: break                             if (main.changedToUpIgnoreConsumed()) {                                 if (!isDragStarted && !longPressHandled) {-                                    // Tap handling-                                    if (latestWiringFrom != null || wiringStart != null) {+                                    if (latestWiringFrom != null || wiringStartLocal != null) {                                         val dst = hitInputDot(main.position)                                         if (dst != null) {-                                            val from = latestWiringFrom ?: wiringStart?.end+                                            val from = latestWiringFrom ?: wiringStartLocal?.end                                             if (from != null && from.instanceId != dst.end.instanceId) currentOnCreateWire(from, dst.end)                                         }-                                        currentOnCancelWiring()-                                        wiringStart = null-                                        dragMode = DragMode.None-                                        currentOnGhostLine(null)+                                        currentOnCancelWiring(); wiringStartLocal = null; currentOnGhostLine(null)                                     } else {                                         val outHit = hitOutputDot(main.position)-                                        if (outHit != null) {-                                            wiringStart = outHit-                                            dragMode = DragMode.Wire-                                            currentOnStartWiring(outHit.end)-                                            currentOnGhostLine(outHit.pos)-                                        } else {+                                        if (outHit != null) { wiringStartLocal = outHit; currentOnStartWiring(outHit.end); currentOnGhostLine(outHit.pos) }+                                        else {                                             val wire = findClosestWire(main.position)                                             if (wire != null) currentOnWireDelete(wire.id)                                             else {@@ -254,167 +274,188 @@ fun CircuitCanvas(                                             }                                         }                                     }-                                } else if (isDragStarted && mode == DragMode.Wire) {+                                } else if (isDragStarted && mode is DragMode.Wiring) {                                     val dst = hitInputDot(currentPos)                                     if (dst != null && wireStart != null) {                                         val from = wireStart.end                                         if (from.instanceId != dst.end.instanceId) currentOnCreateWire(from, dst.end)                                     }-                                    currentOnGhostLine(null)-                                    currentOnCancelWiring()-                                    wiringStart = null-                                    dragMode = DragMode.None-                                    draggedGateId = null+                                    currentOnGhostLine(null); currentOnCancelWiring(); wiringStartLocal = null; draggedGateId = null                                 } else if (isDragStarted) {-                                    dragMode = DragMode.None+                                    when (mode) {+                                        is DragMode.Gate -> {+                                            val gid = (mode as DragMode.Gate).id+                                            val box = rectById[gid]+                                            if (box != null) {+                                                val clamped = clampGate(Offset(box.left, box.top), box.w, box.h, canvasSizePx)+                                                currentOnGateMoveFinished(gid, clamped.x, clamped.y)+                                            }+                                        }+                                        is DragMode.InputTerm -> {+                                            val idx = (mode as DragMode.InputTerm).idx+                                            val term = inputLayouts.find { it.idx == idx }+                                            term?.let {+                                                val clamped = clampTerm(it.center, it.pillW, canvasSizePx, 8f)+                                                currentOnInputMoveFinished(idx, clamped.x, clamped.y)+                                            }+                                        }+                                        is DragMode.OutputTerm -> {+                                            val idx = (mode as DragMode.OutputTerm).idx+                                            val term = outputLayouts.find { it.idx == idx }+                                            term?.let {+                                                val clamped = clampTerm(it.center, it.pillW, canvasSizePx, 8f)+                                                currentOnOutputMoveFinished(idx, clamped.x, clamped.y)+                                            }+                                        }+                                        else -> {}+                                    }                                     draggedGateId = null                                 }                                 break                             }-                             if (longPressHandled) continue                             val pos = main.position                             totalDrag = pos - downPos-                             if (!isDragStarted) {                                 val elapsed = System.currentTimeMillis() - downTime-                                if (elapsed > 460 && totalDrag.getDistance() < 14f) {-                                    if (gateAtDown != null) currentOnGateDelete(gateAtDown.instanceId)-                                    longPressHandled = true-                                    break+                                if (mode is DragMode.None && gateAtDown != null && elapsed > 500 && totalDrag.getDistance() < 12f) {+                                    try { haptic.performHapticFeedback(HapticFeedbackType.LongPress) } catch (_: Exception) {}+                                    currentOnGateDelete(gateAtDown.instanceId); longPressHandled = true; break                                 }-                                if (totalDrag.getDistance() > 14f) {-                                    isDragStarted = true-                                    when {-                                        outDotAtDown != null -> {-                                            mode = DragMode.Wire-                                            wireStart = outDotAtDown-                                            wiringStart = outDotAtDown-                                            dragMode = DragMode.Wire-                                            currentOnStartWiring(outDotAtDown.end)-                                            currentOnGhostLine(outDotAtDown.pos)-                                        }-                                        inTermMoveAtDown != null -> {-                                            mode = DragMode.InputTerm-                                            inputIdx = inTermMoveAtDown.index-                                            inputStart = inTermMoveAtDown.center-                                            dragMode = DragMode.InputTerm-                                        }-                                        outTermMoveAtDown != null -> {-                                            mode = DragMode.OutputTerm-                                            outputIdx = outTermMoveAtDown.index-                                            outputStart = outTermMoveAtDown.center-                                            dragMode = DragMode.OutputTerm-                                        }-                                        gateAtDown != null -> {-                                            mode = DragMode.Gate-                                            gateId = gateAtDown.instanceId-                                            val gr = latestRects.find { it.chip.instanceId == gateId }-                                            if (gr != null) {-                                                gateStartLeft = gr.left-                                                gateStartTop = gr.top+                                if (totalDrag.getDistance() > 12f) {+                                    if (mode is DragMode.Wiring) isDragStarted = true else {+                                        isDragStarted = true+                                        when {+                                            outDotAtDown != null -> {+                                                mode = DragMode.Wiring(outDotAtDown.end, outDotAtDown.pos, pos)+                                                wireStart = outDotAtDown; wiringStartLocal = outDotAtDown+                                                if (latestWiringFrom == null) currentOnStartWiring(outDotAtDown.end)+                                                currentOnGhostLine(pos)                                             }-                                            draggedGateId = gateAtDown.instanceId-                                            dragMode = DragMode.Gate+                                            inTermMoveAtDown != null -> { mode = DragMode.InputTerm(inTermMoveAtDown.idx, inTermMoveAtDown.center); inputStart = inTermMoveAtDown.center }+                                            outTermMoveAtDown != null -> { mode = DragMode.OutputTerm(outTermMoveAtDown.idx, outTermMoveAtDown.center); outputStart = outTermMoveAtDown.center }+                                            gateAtDown != null && gateBoxAtDown != null -> {+                                                val grabOff = downPos - Offset(gateBoxAtDown.left, gateBoxAtDown.top)+                                                mode = DragMode.Gate(gateAtDown.instanceI

Diff truncated.