logic-arrows-lac 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
lac/__init__.py ADDED
@@ -0,0 +1,1034 @@
1
+ """Build Logic Arrows 3D .labp blueprints from Python.
2
+
3
+ A saved .labp is the game's native Base64-wrapped binary record (block_codec.h),
4
+ not the legacy JSON blueprint format. No game-side changes are required.
5
+
6
+ Coordinates are (x, y, z), with y up. Directions are Dir objects:
7
+ Dir.X, Dir.Z, Dir.NX, Dir.NZ, Dir.Y and Dir.NY (negate with -Dir.X).
8
+ Block kinds are Block objects: Block.ARROW, Block.AND, Block.CAPACITOR, ...
9
+
10
+ Example:
11
+
12
+ bp = Blueprint()
13
+ bp.place(Block.CAPACITOR, (0, 0, 0), N=12, K=2)
14
+ bp.place(Block.PULSE_STRETCHER, (2, 0, 0), D=8)
15
+ bp.place(Block.KEY_BUTTON, (4, 0, 0), key=65) # 65 = A
16
+
17
+ palette = bp.add_palette([(255, 0, 0, 255), (0, 0, 255, 255)])
18
+ bp.place(Block.PALETTE_BULB, (6, 0, 0), palette=palette)
19
+ bp.save("my_circuit.labp")
20
+
21
+ # For linkable blocks, place both endpoints first:
22
+ bp.place(Block.LINKED_ARROW, (8, 0, 0), facing=Dir.X)
23
+ bp.place(Block.LINKED_ARROW, (12, 0, 0), facing=Dir.X)
24
+ bp.link((8, 0, 0), (12, 0, 0))
25
+
26
+ # Add live simulation checks (stored beside the .labp as .tests.json):
27
+ bp.press((4, 0, 0), at=1)
28
+ check = bp.test("the key button responds")
29
+ check.eventually_on((4, 0, 0), within=2)
30
+ result = bp.run(ticks=40) # uses headless/lasim
31
+ result.assert_passed()
32
+
33
+ The game's .labp file contains only the circuit. Probes, scheduled test inputs,
34
+ and runtime assertions are stored in a separate .tests.json sidecar that the
35
+ headless runner reads; the game ignores that sidecar.
36
+ """
37
+
38
+ from pathlib import Path
39
+ import base64
40
+ import json
41
+ import os
42
+ import subprocess
43
+ import tempfile
44
+ import zlib
45
+
46
+
47
+ # ---------------------------------------------------------------------------
48
+ # Directions
49
+
50
+ class Dir:
51
+ """One of the six axis directions. Compare with ==; negate with -Dir.X."""
52
+ ALL = [] # index is the game's `dir` value
53
+
54
+ def __init__(self, name, step, right):
55
+ self.index = len(Dir.ALL)
56
+ self.name = name
57
+ self.step = step
58
+ self.right = right
59
+ Dir.ALL.append(self)
60
+
61
+ @property
62
+ def axis(self):
63
+ """0 for x, 1 for y, 2 for z."""
64
+ return next(i for i, value in enumerate(self.step) if value)
65
+
66
+ @property
67
+ def vertical(self):
68
+ return self.axis == 1
69
+
70
+ @staticmethod
71
+ def from_step(step):
72
+ step = tuple(step)
73
+ for direction in Dir.ALL:
74
+ if direction.step == step:
75
+ return direction
76
+ raise ValueError(f"{step} is not a single step along one axis")
77
+
78
+ def __neg__(self):
79
+ return Dir.from_step(tuple(-value for value in self.step))
80
+
81
+ def __repr__(self):
82
+ return f"Dir({self.name})"
83
+
84
+
85
+ # Must match DIRS / blockcodec's 0..5 orientation order.
86
+ Dir.X = Dir("+x", (1, 0, 0), (0, 0, 1))
87
+ Dir.Z = Dir("+z", (0, 0, 1), (-1, 0, 0))
88
+ Dir.NX = Dir("-x", (-1, 0, 0), (0, 0, -1))
89
+ Dir.NZ = Dir("-z", (0, 0, -1), (1, 0, 0))
90
+ Dir.Y = Dir("+y", (0, 1, 0), (0, 0, 1))
91
+ Dir.NY = Dir("-y", (0, -1, 0), (0, 0, 1))
92
+
93
+
94
+ # ---------------------------------------------------------------------------
95
+ # Block IDs (must match BlockType in block_atlas.h)
96
+
97
+ class Block:
98
+ """A block kind. `id` is the game's BlockType number."""
99
+ def __init__(self, name, block_id):
100
+ self.name = name
101
+ self.id = block_id
102
+
103
+ def __repr__(self):
104
+ return f"Block.{self.name.upper()}"
105
+
106
+
107
+ Block.ARROW = Block("arrow", 1)
108
+ Block.SOURCE = Block("source", 2)
109
+ Block.DETECTOR = Block("detector", 3)
110
+ Block.BLUE_ARROW = Block("blue_arrow", 4)
111
+ Block.BLOCKER = Block("blocker", 5)
112
+ Block.I_SPLITTER = Block("i_splitter", 6)
113
+ Block.T_SPLITTER = Block("t_splitter", 7)
114
+ Block.L_SPLITTER = Block("l_splitter", 8)
115
+ Block.DIAGONAL_ARROW = Block("diagonal_arrow", 9)
116
+ Block.AND = Block("and", 10)
117
+ Block.NOT = Block("not", 11)
118
+ Block.XOR = Block("xor", 12)
119
+ # 13 is PROJECTILE: transient and deliberately not a valid blueprint block.
120
+ Block.TRANSMITTER = Block("transmitter", 14)
121
+ Block.LATCH = Block("latch", 15)
122
+ Block.BLUE_I_SPLITTER = Block("blue_i_splitter", 16)
123
+ Block.BLUE_L_SPLITTER = Block("blue_l_splitter", 17)
124
+ Block.DIAGONAL_SPLITTER = Block("diagonal_splitter", 18)
125
+ Block.TFLIPFLOP = Block("tflipflop", 19)
126
+ Block.DELAY_ARROW = Block("delay_arrow", 20)
127
+ Block.PULSE_GENERATOR = Block("pulse_generator", 21)
128
+ Block.PULSE = Block.PULSE_GENERATOR # backwards-compatible alias
129
+ Block.DIRECTIONAL_BUTTON = Block("directional_button", 22)
130
+ Block.QUAD_BUTTON = Block("quad_button", 23)
131
+ Block.KEY_BUTTON = Block("key_button", 24)
132
+ Block.LIGHT_BULB = Block("light_bulb", 25)
133
+ Block.BULB = Block.LIGHT_BULB # backwards-compatible alias
134
+ Block.CONNECTIVE_LIGHT_BULB = Block("connective_light_bulb", 26)
135
+ Block.INTERVAL_BLOCK = Block("interval_block", 27)
136
+ Block.DIAGONAL_BLOCKER = Block("diagonal_blocker", 28)
137
+ Block.LINKED_ARROW = Block("linked_arrow", 29)
138
+ Block.WALL = Block("wall", 30)
139
+ Block.CAPACITOR = Block("capacitor", 31)
140
+ Block.PULSE_STRETCHER = Block("pulse_stretcher", 32)
141
+ Block.PALETTE_BULB = Block("palette_bulb", 33)
142
+ Block.MIXER = Block("mixer", 34)
143
+
144
+
145
+ # ---------------------------------------------------------------------------
146
+ # Binary helpers (matching block_codec.h)
147
+
148
+ _FAMILY = 0x05
149
+ _DIMENSIONS = 0x03
150
+ _BODY_RAW = 0x00
151
+ _BODY_ZLIB = 0x01
152
+ _COMPRESS_THRESHOLD = 56
153
+ _SEGMENT_BYTES = 8 * 1024 * 1024
154
+ _MAX_BLOCKS = 4_000_000
155
+ _MAX_EXTENT = 4096
156
+ _MAX_PALETTES = 1024
157
+ _MAX_PALETTE_COLORS = 16
158
+ _KEY_NULL = 0
159
+ _MAX_KEY = 512
160
+
161
+
162
+ def _as_int(value, name):
163
+ if isinstance(value, bool) or not isinstance(value, int):
164
+ raise TypeError(f"{name} must be an integer")
165
+ return value
166
+
167
+
168
+ def _position(pos, name="position"):
169
+ try:
170
+ values = tuple(pos)
171
+ except TypeError as exc:
172
+ raise TypeError(f"{name} must be an (x, y, z) tuple") from exc
173
+ if len(values) != 3:
174
+ raise ValueError(f"{name} must contain exactly three coordinates")
175
+ result = tuple(_as_int(value, f"{name} coordinate") for value in values)
176
+ if any(value < 0 or value >= _MAX_EXTENT for value in result):
177
+ raise ValueError(f"{name} {result}: coordinates must be between 0 and {_MAX_EXTENT - 1}")
178
+ return result
179
+
180
+
181
+ def _put_varint(out, value):
182
+ value = _as_int(value, "varint")
183
+ if value < 0 or value > 0xFFFFFFFFFFFFFFFF:
184
+ raise ValueError("varint is outside the unsigned 64-bit range")
185
+ while value >= 0x80:
186
+ out.append((value & 0x7F) | 0x80)
187
+ value >>= 7
188
+ out.append(value)
189
+
190
+
191
+ def _put_zigzag(out, value):
192
+ value = _as_int(value, "zigzag value")
193
+ if value < -(1 << 63) or value >= (1 << 63):
194
+ raise ValueError("zigzag value is outside the signed 64-bit range")
195
+ _put_varint(out, (value << 1) ^ (value >> 63))
196
+
197
+
198
+ def _rgba(color, name="colour"):
199
+ try:
200
+ channels = tuple(color)
201
+ except TypeError as exc:
202
+ raise TypeError(f"{name} must be an (r, g, b, a) tuple") from exc
203
+ if len(channels) != 4:
204
+ raise ValueError(f"{name} must contain exactly four channels (RGBA)")
205
+ channels = tuple(_as_int(channel, f"{name} channel") for channel in channels)
206
+ if any(channel < 0 or channel > 255 for channel in channels):
207
+ raise ValueError(f"{name} channels must be between 0 and 255")
208
+ return channels
209
+
210
+
211
+ def _encode_compressed_body(body):
212
+ """Encode the codec's segmented zlib body, returning None if not beneficial."""
213
+ packed = bytearray()
214
+ chunks = [body[start:start + _SEGMENT_BYTES]
215
+ for start in range(0, len(body), _SEGMENT_BYTES)]
216
+ _put_varint(packed, len(chunks))
217
+ for chunk in chunks:
218
+ compressed = zlib.compress(chunk)
219
+ _put_varint(packed, len(chunk))
220
+ _put_varint(packed, len(compressed))
221
+ packed.extend(compressed)
222
+ return bytes(packed) if len(packed) < len(body) else None
223
+
224
+
225
+ # ---------------------------------------------------------------------------
226
+ # Simulation tests
227
+
228
+ class CircuitTest:
229
+ """A named group of runtime assertions for a Blueprint."""
230
+
231
+ def __init__(self, blueprint, name):
232
+ self.blueprint = blueprint
233
+ self.name = str(name).strip()
234
+ if not self.name:
235
+ raise ValueError("test name cannot be empty")
236
+ self.assertions = []
237
+
238
+ def _add(self, kind, pos, **values):
239
+ pos = _position(pos, "test position")
240
+ if pos not in self.blueprint.blocks:
241
+ raise ValueError(f"test position {pos} does not contain a block")
242
+ item = {"kind": kind, "pos": list(pos)}
243
+ item.update(values)
244
+ self.assertions.append(item)
245
+ return self
246
+
247
+ def on(self, pos, *, at):
248
+ """Assert the block's signal is ON after the given tick (0 = before running)."""
249
+ at = _as_int(at, "at")
250
+ if at < 0:
251
+ raise ValueError("at must be >= 0")
252
+ return self._add("state", pos, at=at, on=True)
253
+
254
+ def off(self, pos, *, at):
255
+ """Assert the block's signal is OFF after the given tick (0 = before running)."""
256
+ at = _as_int(at, "at")
257
+ if at < 0:
258
+ raise ValueError("at must be >= 0")
259
+ return self._add("state", pos, at=at, on=False)
260
+
261
+ def eventually_on(self, pos, *, within):
262
+ """Pass when the block becomes ON at any tick from 1 through `within`."""
263
+ within = _as_int(within, "within")
264
+ if within < 1:
265
+ raise ValueError("within must be >= 1")
266
+ return self._add("eventually", pos, within=within, on=True)
267
+
268
+ def eventually_off(self, pos, *, within):
269
+ """Pass when the block becomes OFF at any tick from 1 through `within`."""
270
+ within = _as_int(within, "within")
271
+ if within < 1:
272
+ raise ValueError("within must be >= 1")
273
+ return self._add("eventually", pos, within=within, on=False)
274
+
275
+ def always_on(self, pos, *, from_tick=1, through):
276
+ """Assert ON at every tick in the inclusive [from_tick, through] range."""
277
+ return self._always(pos, True, from_tick, through)
278
+
279
+ def always_off(self, pos, *, from_tick=1, through):
280
+ """Assert OFF at every tick in the inclusive [from_tick, through] range."""
281
+ return self._always(pos, False, from_tick, through)
282
+
283
+ def _always(self, pos, expected, from_tick, through):
284
+ from_tick = _as_int(from_tick, "from_tick")
285
+ through = _as_int(through, "through")
286
+ if from_tick < 0 or through < from_tick:
287
+ raise ValueError("require 0 <= from_tick <= through")
288
+ return self._add("always", pos, **{"from": from_tick, "through": through, "on": expected})
289
+
290
+ def rising_edges(self, pos, *, count, from_tick=1, through):
291
+ """Assert an exact number of OFF-to-ON transitions in an inclusive tick range."""
292
+ return self._edges(pos, "rising", count, from_tick, through)
293
+
294
+ def falling_edges(self, pos, *, count, from_tick=1, through):
295
+ """Assert an exact number of ON-to-OFF transitions in an inclusive tick range."""
296
+ return self._edges(pos, "falling", count, from_tick, through)
297
+
298
+ def _edges(self, pos, edge, count, from_tick, through):
299
+ count = _as_int(count, "count")
300
+ from_tick = _as_int(from_tick, "from_tick")
301
+ through = _as_int(through, "through")
302
+ if count < 0 or from_tick < 1 or through < from_tick:
303
+ raise ValueError("require count >= 0 and 1 <= from_tick <= through")
304
+ return self._add("edges", pos, edge=edge, count=count,
305
+ **{"from": from_tick, "through": through})
306
+
307
+ # Readable aliases for people who prefer temporal wording.
308
+ becomes_on = eventually_on
309
+ becomes_off = eventually_off
310
+ stays_on = always_on
311
+ stays_off = always_off
312
+
313
+
314
+ class SimulationResult:
315
+ """Result returned by Blueprint.run(). Truthy only when every test passed."""
316
+
317
+ def __init__(self, result_json, stdout, stderr, returncode):
318
+ self.passed = bool(result_json.get("passed", False))
319
+ self.passed_count = int(result_json.get("passed_count", 0))
320
+ self.failed_count = int(result_json.get("failed_count", 0))
321
+ self.ticks = int(result_json.get("ticks", 0))
322
+ self.tests = result_json.get("tests", [])
323
+ self.stdout = stdout
324
+ self.stderr = stderr
325
+ self.returncode = returncode
326
+ self.trace = [line for line in stdout.splitlines() if not line.startswith("TEST_RESULTS ")]
327
+
328
+ def __bool__(self):
329
+ return self.passed
330
+
331
+ def assert_passed(self):
332
+ """Raise AssertionError with failing test details; otherwise return self."""
333
+ if not self.passed:
334
+ failures = [f"{item['name']}: {item.get('message') or 'failed'}"
335
+ for item in self.tests if not item.get("passed")]
336
+ raise AssertionError("circuit tests failed:\n" + "\n".join(failures))
337
+ return self
338
+
339
+
340
+ # ---------------------------------------------------------------------------
341
+ # Blueprint builder
342
+
343
+ class Blueprint:
344
+ """Build a portable Logic Arrows 3D blueprint and save it as native .labp."""
345
+
346
+ def __init__(self):
347
+ self.blocks = {}
348
+ self.probes = {} # test metadata only; not part of the .labp format
349
+ self.palettes = []
350
+ self.tests = []
351
+ self.actions = []
352
+ self._explicit_size = None
353
+
354
+ def place(self, kind, pos, facing=Dir.X, mirrored=False, *, roll=0,
355
+ key=None, cover_tile=None, fill=None,
356
+ N=None, K=None, D=None, palette=None):
357
+ """Place a block.
358
+
359
+ Common options:
360
+ facing: Dir; mirrored: bool; roll: 0..3
361
+ For blue/diagonal signal blocks, roll rotates the lateral axis:
362
+ 0=right, 1=up, 2=left, 3=down, relative to facing.
363
+ mirrored=True reverses that lateral direction without changing facing.
364
+ For a diagonal arrow/blocker, its offset is facing.step + lateral.step.
365
+ This roll affects BLUE_ARROW, BLUE_I_SPLITTER, BLUE_L_SPLITTER,
366
+ DIAGONAL_ARROW, DIAGONAL_SPLITTER, and DIAGONAL_BLOCKER.
367
+ key: raylib keyboard code (KEY_BUTTON only; A is 65)
368
+ cover_tile: atlas tile 0..63 (light bulbs only)
369
+ fill: RGBA tuple for both states, (off_rgba, on_rgba), or
370
+ {"off": rgba, "on": rgba} (bulbs and walls)
371
+ N, K: capacitor settings (N=1..255, K=1..16)
372
+ D: pulse-stretcher duration (1..255)
373
+ palette: palette-table index (PALETTE_BULB only)
374
+ """
375
+ if not isinstance(kind, Block):
376
+ raise TypeError(f"kind must be a Block (like Block.ARROW), got {kind!r}")
377
+ if kind.id <= 0 or kind.id >= 35 or kind.id == 13:
378
+ raise ValueError(f"{kind} is not a placeable blueprint block")
379
+ if not isinstance(facing, Dir):
380
+ raise TypeError(f"facing must be a Dir (like Dir.X), got {facing!r}")
381
+ if not isinstance(mirrored, bool):
382
+ raise TypeError("mirrored must be True or False")
383
+
384
+ pos = _position(pos)
385
+ if pos in self.blocks:
386
+ raise ValueError(f"{kind} at {pos}: cell already holds a block")
387
+
388
+ roll = _as_int(roll, "roll")
389
+ if roll < 0 or roll > 3:
390
+ raise ValueError("roll must be between 0 and 3")
391
+
392
+ block = {
393
+ "x": pos[0], "y": pos[1], "z": pos[2],
394
+ "type": kind.id, "dir": facing.index,
395
+ "roll": roll, "mirrored": mirrored,
396
+ }
397
+
398
+ if key is not None:
399
+ if kind is not Block.KEY_BUTTON:
400
+ raise ValueError("key is only valid for Block.KEY_BUTTON")
401
+ key = _as_int(key, "key")
402
+ if key < _KEY_NULL or key > _MAX_KEY:
403
+ raise ValueError(f"key must be between 0 and {_MAX_KEY}")
404
+ if key != _KEY_NULL:
405
+ block["key"] = key
406
+
407
+ if cover_tile is not None:
408
+ if kind.id not in (Block.LIGHT_BULB.id, Block.CONNECTIVE_LIGHT_BULB.id):
409
+ raise ValueError("cover_tile is only valid for light bulbs")
410
+ cover_tile = _as_int(cover_tile, "cover_tile")
411
+ if cover_tile < 0 or cover_tile > 63:
412
+ raise ValueError("cover_tile must be between 0 and 63")
413
+ block["cover_tile"] = cover_tile
414
+
415
+ if fill is not None:
416
+ if kind.id not in (Block.LIGHT_BULB.id, Block.CONNECTIVE_LIGHT_BULB.id, Block.WALL.id):
417
+ raise ValueError("fill is only valid for light bulbs and walls")
418
+ if isinstance(fill, dict):
419
+ if "off" not in fill or "on" not in fill:
420
+ raise ValueError('fill dictionary must contain "off" and "on"')
421
+ off = _rgba(fill["off"], "fill off colour")
422
+ on = _rgba(fill["on"], "fill on colour")
423
+ else:
424
+ try:
425
+ values = tuple(fill)
426
+ except TypeError as exc:
427
+ raise TypeError("fill must be an RGBA tuple or an (off, on) pair") from exc
428
+ if len(values) == 2 and all(hasattr(value, "__iter__") for value in values):
429
+ off = _rgba(values[0], "fill off colour")
430
+ on = _rgba(values[1], "fill on colour")
431
+ else:
432
+ off = on = _rgba(values, "fill colour")
433
+ block["fill"] = (off, on)
434
+
435
+ if N is not None or K is not None:
436
+ if kind is not Block.CAPACITOR:
437
+ raise ValueError("N and K are only valid for Block.CAPACITOR")
438
+ N = 10 if N is None else _as_int(N, "N")
439
+ K = 1 if K is None else _as_int(K, "K")
440
+ if not 1 <= N <= 255:
441
+ raise ValueError("capacitor N must be between 1 and 255")
442
+ if not 1 <= K <= 16:
443
+ raise ValueError("capacitor K must be between 1 and 16")
444
+ block["settings"] = (N, K)
445
+
446
+ if D is not None:
447
+ if kind is not Block.PULSE_STRETCHER:
448
+ raise ValueError("D is only valid for Block.PULSE_STRETCHER")
449
+ D = _as_int(D, "D")
450
+ if not 1 <= D <= 255:
451
+ raise ValueError("pulse-stretcher D must be between 1 and 255")
452
+ block["settings"] = (D, 0)
453
+
454
+ if palette is not None or kind is Block.PALETTE_BULB:
455
+ if kind is not Block.PALETTE_BULB:
456
+ raise ValueError("palette is only valid for Block.PALETTE_BULB")
457
+ palette = 0 if palette is None else _as_int(palette, "palette")
458
+ self._ensure_default_palette()
459
+ if palette < 0 or palette >= len(self.palettes):
460
+ raise ValueError(f"palette id {palette} does not exist; add it with bp.add_palette() first")
461
+ block["settings"] = (palette, 0)
462
+
463
+ self.blocks[pos] = block
464
+ return pos
465
+
466
+ def wire(self, *points, end=None):
467
+ """Lay arrows along straight x/y/z segments, turning at listed points.
468
+
469
+ Every listed cell gets an arrow. The last arrow faces `end` (a Dir), or
470
+ carries on in the direction of the final segment. Returns arrow count.
471
+ """
472
+ if not points:
473
+ raise ValueError("wire needs at least one point")
474
+ cells = [_position(points[0], "wire point")]
475
+ for target in points[1:]:
476
+ target = _position(target, "wire point")
477
+ here = cells[-1]
478
+ moved = [axis for axis in range(3) if here[axis] != target[axis]]
479
+ if len(moved) != 1:
480
+ raise ValueError(f"wire {here} -> {target}: segments must be straight, along x, y or z")
481
+ axis = moved[0]
482
+ sign = 1 if target[axis] > here[axis] else -1
483
+ while here != target:
484
+ here = tuple(value + sign if i == axis else value for i, value in enumerate(here))
485
+ cells.append(here)
486
+ if len(cells) == 1 and end is None:
487
+ raise ValueError("a one-cell wire needs end=")
488
+ if end is not None and not isinstance(end, Dir):
489
+ raise TypeError("end must be a Dir")
490
+ for index, cell in enumerate(cells):
491
+ if index + 1 < len(cells):
492
+ facing = Dir.from_step(tuple(b - a for a, b in zip(cell, cells[index + 1])))
493
+ else:
494
+ facing = end or Dir.from_step(tuple(b - a for a, b in zip(cells[index - 1], cell)))
495
+ self.place(Block.ARROW, cell, facing)
496
+ return len(cells)
497
+
498
+ def split(self, pos, facing, outputs):
499
+ """Place a splitter that faces `facing` and sends to exactly `outputs` (Dirs)."""
500
+ if not isinstance(facing, Dir):
501
+ raise TypeError("facing must be a Dir")
502
+ outputs = tuple(outputs)
503
+ if any(not isinstance(output, Dir) for output in outputs):
504
+ raise TypeError("outputs must contain Dir values")
505
+ sides = set()
506
+ for output in outputs:
507
+ if output == facing:
508
+ sides.add("F")
509
+ elif output.step == facing.right:
510
+ sides.add("R")
511
+ elif output.step == tuple(-value for value in facing.right):
512
+ sides.add("L")
513
+ else:
514
+ sides.add("back")
515
+ table = {
516
+ frozenset("FR"): (Block.L_SPLITTER, False),
517
+ frozenset("FL"): (Block.L_SPLITTER, True),
518
+ frozenset("LR"): (Block.I_SPLITTER, False),
519
+ frozenset("FLR"): (Block.T_SPLITTER, False),
520
+ }
521
+ choice = table.get(frozenset(sides))
522
+ if choice is None:
523
+ raise ValueError(f"no splitter facing {facing} outputs {list(outputs)}")
524
+ kind, mirrored = choice
525
+ return self.place(kind, pos, facing, mirrored)
526
+
527
+ def add_palette(self, colors):
528
+ """Add an RGBA palette and return its ID.
529
+
530
+ Palette 0 is the game's default white palette. The first custom palette
531
+ added this way therefore receives ID 1.
532
+ """
533
+ self._ensure_default_palette()
534
+ if len(self.palettes) >= _MAX_PALETTES:
535
+ raise ValueError(f"a blueprint can contain at most {_MAX_PALETTES} palettes")
536
+ try:
537
+ colors = list(colors)
538
+ except TypeError as exc:
539
+ raise TypeError("palette colours must be an iterable of RGBA tuples") from exc
540
+ if len(colors) > _MAX_PALETTE_COLORS:
541
+ raise ValueError(f"a palette can contain at most {_MAX_PALETTE_COLORS} colours")
542
+ parsed = [_rgba(color, f"palette colour {i}") for i, color in enumerate(colors)]
543
+ self.palettes.append(parsed)
544
+ return len(self.palettes) - 1
545
+
546
+ def set_palette(self, palette_id, colors):
547
+ """Replace an existing palette by ID (including palette 0)."""
548
+ self._ensure_default_palette()
549
+ palette_id = _as_int(palette_id, "palette_id")
550
+ if palette_id < 0 or palette_id >= len(self.palettes):
551
+ raise ValueError(f"palette id {palette_id} does not exist")
552
+ try:
553
+ colors = list(colors)
554
+ except TypeError as exc:
555
+ raise TypeError("palette colours must be an iterable of RGBA tuples") from exc
556
+ if len(colors) > _MAX_PALETTE_COLORS:
557
+ raise ValueError(f"a palette can contain at most {_MAX_PALETTE_COLORS} colours")
558
+ self.palettes[palette_id] = [_rgba(color, f"palette colour {i}") for i, color in enumerate(colors)]
559
+
560
+ def link(self, source, target):
561
+ """Create a saved link from one block to another.
562
+
563
+ LINKED_ARROW must target another LINKED_ARROW in its facing direction.
564
+ PALETTE_BULB and MIXER can target a MIXER. Place both blocks first.
565
+ """
566
+ source = _position(source, "link source")
567
+ target = _position(target, "link target")
568
+ if source not in self.blocks:
569
+ raise ValueError(f"link source {source} does not contain a block")
570
+ if target not in self.blocks:
571
+ raise ValueError(f"link target {target} does not contain a block")
572
+ if source == target:
573
+ raise ValueError("a block cannot link to itself")
574
+
575
+ source_block = self.blocks[source]
576
+ target_block = self.blocks[target]
577
+ source_type = source_block["type"]
578
+ target_type = target_block["type"]
579
+ if "link_to" in source_block:
580
+ raise ValueError(f"block at {source} already has an outgoing link")
581
+
582
+ if source_type == Block.LINKED_ARROW.id:
583
+ if target_type != Block.LINKED_ARROW.id:
584
+ raise ValueError("a linked arrow must target another linked arrow")
585
+ direction = Dir.ALL[source_block["dir"]]
586
+ delta = tuple(target[i] - source[i] for i in range(3))
587
+ distance = sum(delta[i] * direction.step[i] for i in range(3))
588
+ if distance <= 0 or any(delta[i] != distance * direction.step[i] for i in range(3)):
589
+ raise ValueError("linked-arrow target must lie ahead along the source arrow's facing direction")
590
+ for other_pos, other in self.blocks.items():
591
+ if other_pos != source and other.get("link_to") == target:
592
+ raise ValueError(f"linked arrow at {target} already has an incoming link")
593
+ cursor = target
594
+ visited = set()
595
+ while cursor in self.blocks:
596
+ if cursor == source:
597
+ raise ValueError("linked-arrow link would create a cycle")
598
+ if cursor in visited:
599
+ raise ValueError("linked-arrow link would extend an existing cycle")
600
+ visited.add(cursor)
601
+ next_pos = self.blocks[cursor].get("link_to")
602
+ if next_pos is None:
603
+ break
604
+ cursor = next_pos
605
+ elif source_type in (Block.PALETTE_BULB.id, Block.MIXER.id):
606
+ if target_type != Block.MIXER.id:
607
+ raise ValueError("a palette bulb or mixer must target a mixer")
608
+ # The mixer-link graph must remain acyclic.
609
+ cursor = target
610
+ visited = set()
611
+ while cursor in self.blocks:
612
+ if cursor == source:
613
+ raise ValueError("mixer link would create a cycle")
614
+ if cursor in visited:
615
+ raise ValueError("mixer link would extend an existing cycle")
616
+ visited.add(cursor)
617
+ next_pos = self.blocks[cursor].get("link_to")
618
+ if next_pos is None:
619
+ break
620
+ cursor = next_pos
621
+ else:
622
+ raise ValueError("only linked arrows, palette bulbs and mixers can contain links")
623
+
624
+ source_block["link_to"] = target
625
+ return target
626
+
627
+ def set_size(self, sx, sy, sz):
628
+ """Set the stored blueprint bounding-box size (must include every block)."""
629
+ size = tuple(_as_int(value, "blueprint size") for value in (sx, sy, sz))
630
+ if any(value < 1 or value > _MAX_EXTENT for value in size):
631
+ raise ValueError(f"blueprint dimensions must be between 1 and {_MAX_EXTENT}")
632
+ for pos in self.blocks:
633
+ if any(pos[axis] >= size[axis] for axis in range(3)):
634
+ raise ValueError(f"blueprint size {size} does not contain block at {pos}")
635
+ self._explicit_size = size
636
+
637
+ def probe(self, name, pos):
638
+ """Name an existing block for live trace output (stored in the test sidecar)."""
639
+ pos = _position(pos, "probe position")
640
+ if pos not in self.blocks:
641
+ raise ValueError(f"probe {name}: no block at {pos}")
642
+ self.probes[str(name)] = list(pos)
643
+
644
+ def test(self, name):
645
+ """Create a named group of assertions evaluated during simulation.
646
+
647
+ Example::
648
+
649
+ check = bp.test("bulb receives the pulse")
650
+ check.off((4, 0, 0), at=0)
651
+ check.eventually_on((4, 0, 0), within=8)
652
+ check.always_off((4, 0, 0), from_tick=10, through=20)
653
+ """
654
+ name = str(name).strip()
655
+ if any(existing.name == name for existing in self.tests):
656
+ raise ValueError(f"a test named {name!r} already exists")
657
+ test = CircuitTest(self, name)
658
+ self.tests.append(test)
659
+ return test
660
+
661
+ def press(self, pos, *, at, duration=1):
662
+ """Press a directional, quad, or key button during the run.
663
+
664
+ `at` is the 1-based simulation tick. `duration` is the number of ticks
665
+ to hold the button; a one-tick press is emitted as a button pulse.
666
+ """
667
+ pos = _position(pos, "button position")
668
+ if pos not in self.blocks:
669
+ raise ValueError(f"no block at {pos}")
670
+ if self.blocks[pos]["type"] not in (Block.DIRECTIONAL_BUTTON.id,
671
+ Block.QUAD_BUTTON.id,
672
+ Block.KEY_BUTTON.id):
673
+ raise ValueError("press() requires a directional, quad, or key button")
674
+ at = _as_int(at, "at")
675
+ duration = _as_int(duration, "duration")
676
+ if at < 1 or duration < 1:
677
+ raise ValueError("at and duration must both be >= 1")
678
+ self.actions.append({"kind": "press", "pos": list(pos), "at": at, "duration": duration})
679
+ return self
680
+
681
+ def set_source(self, pos, *, on, at):
682
+ """Schedule a SOURCE block to be on or off before a given simulation tick."""
683
+ pos = _position(pos, "source position")
684
+ if pos not in self.blocks or self.blocks[pos]["type"] != Block.SOURCE.id:
685
+ raise ValueError("set_source() requires a Block.SOURCE at the given position")
686
+ if not isinstance(on, bool):
687
+ raise TypeError("on must be True or False")
688
+ at = _as_int(at, "at")
689
+ if at < 1:
690
+ raise ValueError("at must be >= 1")
691
+ self.actions.append({"kind": "source", "pos": list(pos), "at": at, "on": on})
692
+ return self
693
+
694
+ def trigger_stretcher(self, pos, *, at):
695
+ """Manually trigger a PULSE_STRETCHER before the given simulation tick."""
696
+ pos = _position(pos, "pulse-stretcher position")
697
+ if pos not in self.blocks or self.blocks[pos]["type"] != Block.PULSE_STRETCHER.id:
698
+ raise ValueError("trigger_stretcher() requires a Block.PULSE_STRETCHER")
699
+ at = _as_int(at, "at")
700
+ if at < 1:
701
+ raise ValueError("at must be >= 1")
702
+ self.actions.append({"kind": "trigger_stretcher", "pos": list(pos), "at": at})
703
+ return self
704
+
705
+ def reset_pulse_generator(self, pos, *, at):
706
+ """Re-arm a PULSE_GENERATOR during a run."""
707
+ pos = _position(pos, "pulse-generator position")
708
+ if pos not in self.blocks or self.blocks[pos]["type"] != Block.PULSE_GENERATOR.id:
709
+ raise ValueError("reset_pulse_generator() requires a Block.PULSE_GENERATOR")
710
+ at = _as_int(at, "at")
711
+ if at < 1:
712
+ raise ValueError("at must be >= 1")
713
+ self.actions.append({"kind": "reset_pulse_generator", "pos": list(pos), "at": at})
714
+ return self
715
+
716
+ def _test_spec(self):
717
+ for test in self.tests:
718
+ if not test.assertions:
719
+ raise ValueError(f"test {test.name!r} has no assertions")
720
+ return {
721
+ "version": 1,
722
+ "probes": self.probes,
723
+ "actions": self.actions,
724
+ "tests": [
725
+ {"name": test.name, "assertions": test.assertions}
726
+ for test in self.tests
727
+ ],
728
+ }
729
+
730
+ def _ensure_default_palette(self):
731
+ if not self.palettes:
732
+ self.palettes.append([(255, 255, 255, 255)])
733
+
734
+ def _blueprint_size(self):
735
+ if not self.blocks:
736
+ raise ValueError("cannot save a blueprint with no blocks")
737
+ computed = tuple(max(pos[axis] for pos in self.blocks) + 1 for axis in range(3))
738
+ if self._explicit_size is None:
739
+ size = computed
740
+ else:
741
+ if any(computed[axis] > self._explicit_size[axis] for axis in range(3)):
742
+ raise ValueError(f"stored blueprint size {self._explicit_size} does not contain all blocks")
743
+ size = self._explicit_size
744
+ if any(value < 1 or value > _MAX_EXTENT for value in size):
745
+ raise ValueError(f"blueprint dimensions must be between 1 and {_MAX_EXTENT}")
746
+ return size
747
+
748
+ def _encode(self):
749
+ if not self.blocks:
750
+ raise ValueError("cannot save a blueprint with no blocks")
751
+ if len(self.blocks) > _MAX_BLOCKS:
752
+ raise ValueError(f"blueprint can contain at most {_MAX_BLOCKS} blocks")
753
+
754
+ sx, sy, sz = self._blueprint_size()
755
+ by_type = {}
756
+ for pos, block in self.blocks.items():
757
+ if _position(pos) != pos:
758
+ raise ValueError(f"invalid block position: {pos}")
759
+ block_type = block["type"]
760
+ if block_type <= 0 or block_type >= 35 or block_type == 13:
761
+ raise ValueError(f"invalid block type {block_type} at {pos}")
762
+ if block["dir"] < 0 or block["dir"] > 5 or block["roll"] < 0 or block["roll"] > 3:
763
+ raise ValueError(f"invalid orientation at {pos}")
764
+ by_type.setdefault(block_type, []).append((pos, block))
765
+
766
+ # Verify outgoing links and palette references before writing bytes.
767
+ links_in = {}
768
+ for source, block in self.blocks.items():
769
+ target = block.get("link_to")
770
+ if target is None:
771
+ continue
772
+ target = _position(target, "link target")
773
+ if target not in self.blocks:
774
+ raise ValueError(f"link from {source} points to missing block {target}")
775
+ if block["type"] == Block.LINKED_ARROW.id:
776
+ if self.blocks[target]["type"] != Block.LINKED_ARROW.id:
777
+ raise ValueError(f"linked arrow at {source} must target another linked arrow")
778
+ direction = Dir.ALL[block["dir"]]
779
+ delta = tuple(target[i] - source[i] for i in range(3))
780
+ distance = sum(delta[i] * direction.step[i] for i in range(3))
781
+ if distance <= 0 or any(delta[i] != distance * direction.step[i] for i in range(3)):
782
+ raise ValueError(f"linked-arrow target {target} is not ahead of source {source}")
783
+ if target in links_in:
784
+ raise ValueError(f"linked arrow at {target} has more than one incoming link")
785
+ links_in[target] = source
786
+ elif block["type"] in (Block.PALETTE_BULB.id, Block.MIXER.id):
787
+ if self.blocks[target]["type"] != Block.MIXER.id:
788
+ raise ValueError(f"mixer link from {source} must target a mixer")
789
+ else:
790
+ raise ValueError(f"block at {source} cannot contain a link")
791
+ if any(value < 0 or value >= _MAX_EXTENT for value in target):
792
+ raise ValueError(f"link target {target} is outside the supported blueprint size")
793
+
794
+ # Verify linked-arrow chains are acyclic even if a caller edited the public table.
795
+ for start, block in self.blocks.items():
796
+ if block["type"] != Block.LINKED_ARROW.id:
797
+ continue
798
+ seen = set()
799
+ cursor = start
800
+ while cursor in self.blocks:
801
+ if cursor in seen:
802
+ raise ValueError(f"linked-arrow links contain a cycle through {cursor}")
803
+ seen.add(cursor)
804
+ next_pos = self.blocks[cursor].get("link_to")
805
+ if next_pos is None:
806
+ break
807
+ cursor = next_pos
808
+
809
+ # Verify mixer-link acyclicity even if a caller edited the public block table.
810
+ for start, block in self.blocks.items():
811
+ if block["type"] not in (Block.PALETTE_BULB.id, Block.MIXER.id):
812
+ continue
813
+ seen = set()
814
+ cursor = start
815
+ while cursor in self.blocks:
816
+ if cursor in seen:
817
+ raise ValueError(f"mixer links contain a cycle through {cursor}")
818
+ seen.add(cursor)
819
+ next_pos = self.blocks[cursor].get("link_to")
820
+ if next_pos is None:
821
+ break
822
+ cursor = next_pos
823
+
824
+ for pos, block in self.blocks.items():
825
+ if "key" in block and (block["type"] != Block.KEY_BUTTON.id or not 1 <= block["key"] <= _MAX_KEY):
826
+ raise ValueError(f"invalid key binding at {pos}")
827
+ if "settings" in block:
828
+ setting1, setting2 = block["settings"]
829
+ if block["type"] == Block.CAPACITOR.id:
830
+ if not (1 <= setting1 <= 255 and 1 <= setting2 <= 16):
831
+ raise ValueError(f"invalid capacitor settings at {pos}")
832
+ elif block["type"] == Block.PULSE_STRETCHER.id:
833
+ if not (1 <= setting1 <= 255 and setting2 == 0):
834
+ raise ValueError(f"invalid pulse-stretcher settings at {pos}")
835
+ elif block["type"] == Block.PALETTE_BULB.id:
836
+ if not (0 <= setting1 < len(self.palettes) and setting2 == 0):
837
+ raise ValueError(f"palette bulb at {pos} references a missing palette")
838
+ else:
839
+ raise ValueError(f"block at {pos} cannot contain per-block settings")
840
+
841
+ if len(self.palettes) > _MAX_PALETTES:
842
+ raise ValueError(f"blueprint can contain at most {_MAX_PALETTES} palettes")
843
+ for palette_id, palette in enumerate(self.palettes):
844
+ if len(palette) > _MAX_PALETTE_COLORS:
845
+ raise ValueError(f"palette {palette_id} has more than {_MAX_PALETTE_COLORS} colours")
846
+
847
+ # Body: one group per block type; groups are ordered by the first coordinate
848
+ # in that group's sorted (x, y, z) member list.
849
+ groups = []
850
+ for members in by_type.values():
851
+ members.sort(key=lambda item: item[0])
852
+ groups.append(members)
853
+ groups.sort(key=lambda group: group[0][0])
854
+
855
+ body = bytearray()
856
+ _put_varint(body, len(groups))
857
+ for members in groups:
858
+ body.append(members[0][1]["type"])
859
+ _put_varint(body, len(members))
860
+ previous = (0, 0, 0)
861
+ for pos, block in members:
862
+ _put_zigzag(body, pos[0] - previous[0])
863
+ _put_zigzag(body, pos[1] - previous[1])
864
+ _put_zigzag(body, pos[2] - previous[2])
865
+ previous = pos
866
+
867
+ ext = 0
868
+ if block.get("key", _KEY_NULL) != _KEY_NULL:
869
+ ext |= 1
870
+ if "link_to" in block:
871
+ ext |= 2
872
+ if "cover_tile" in block:
873
+ ext |= 4
874
+ if "fill" in block:
875
+ ext |= 8
876
+ if "settings" in block:
877
+ ext |= 16
878
+
879
+ orientation = block["dir"] | (block["roll"] << 3)
880
+ if block["mirrored"]:
881
+ orientation |= 0x20
882
+ if ext:
883
+ orientation |= 0x40
884
+ body.append(orientation)
885
+ if not ext:
886
+ continue
887
+
888
+ body.append(ext)
889
+ if ext & 1:
890
+ _put_varint(body, block["key"])
891
+ if ext & 2:
892
+ target = block["link_to"]
893
+ _put_zigzag(body, target[0])
894
+ _put_zigzag(body, target[1])
895
+ _put_zigzag(body, target[2])
896
+ if ext & 4:
897
+ body.append(block["cover_tile"])
898
+ if ext & 8:
899
+ off, on = block["fill"]
900
+ body.extend(off)
901
+ body.extend(on)
902
+ if ext & 16:
903
+ setting1, setting2 = block["settings"]
904
+ _put_varint(body, setting1)
905
+ _put_varint(body, setting2)
906
+
907
+ # Header: blueprint frame + bounding-box size, optional portable palette table.
908
+ flags = 0x01 | 0x04
909
+ if self.palettes:
910
+ flags |= 0x08
911
+ header = bytearray((_FAMILY, _DIMENSIONS, _BODY_RAW, flags))
912
+ _put_varint(header, len(self.blocks))
913
+ _put_varint(header, sx)
914
+ _put_varint(header, sy)
915
+ _put_varint(header, sz)
916
+ if self.palettes:
917
+ _put_varint(header, len(self.palettes))
918
+ for palette in self.palettes:
919
+ _put_varint(header, len(palette))
920
+ for color in palette:
921
+ header.extend(color)
922
+
923
+ # The codec only uses its segmented zlib container when it makes the record smaller.
924
+ compressed = None
925
+ if len(body) > _COMPRESS_THRESHOLD:
926
+ compressed = _encode_compressed_body(body)
927
+ if compressed is not None:
928
+ header[2] = _BODY_ZLIB
929
+ header.extend(compressed)
930
+ else:
931
+ header.extend(body)
932
+ return bytes(header)
933
+
934
+ def save(self, path):
935
+ """Write the native Base64 .labp record to `path` and return its path.
936
+
937
+ If `path` has no suffix, `.labp` is appended. Other suffixes are rejected
938
+ to avoid accidentally writing the binary record under a JSON filename.
939
+ Runtime tests, scheduled inputs and probes are written beside it as
940
+ `<name>.tests.json`; they are not part of the game's .labp file format.
941
+ """
942
+ destination = Path(path)
943
+ if not destination.suffix:
944
+ destination = destination.with_suffix(".labp")
945
+ elif destination.suffix.lower() != ".labp":
946
+ raise ValueError("native blueprints must use the .labp extension")
947
+
948
+ raw = self._encode()
949
+ encoded = base64.b64encode(raw) + b"\n"
950
+ destination.parent.mkdir(parents=True, exist_ok=True)
951
+ temporary = destination.with_name(destination.name + ".tmp")
952
+ try:
953
+ with open(temporary, "wb") as output:
954
+ output.write(encoded)
955
+ output.flush()
956
+ os.fsync(output.fileno())
957
+ os.replace(temporary, destination)
958
+ except Exception:
959
+ try:
960
+ temporary.unlink(missing_ok=True)
961
+ except OSError:
962
+ pass
963
+ raise
964
+
965
+ test_path = destination.with_suffix(".tests.json")
966
+ if self.probes or self.actions or self.tests:
967
+ test_temporary = test_path.with_name(test_path.name + ".tmp")
968
+ try:
969
+ with open(test_temporary, "w", encoding="utf-8", newline="\n") as output:
970
+ json.dump(self._test_spec(), output, indent=2)
971
+ output.write("\n")
972
+ output.flush()
973
+ os.fsync(output.fileno())
974
+ os.replace(test_temporary, test_path)
975
+ except Exception:
976
+ try:
977
+ test_temporary.unlink(missing_ok=True)
978
+ except OSError:
979
+ pass
980
+ raise
981
+ else:
982
+ # Avoid accidentally reusing tests from an older save of the same name.
983
+ test_path.unlink(missing_ok=True)
984
+ return str(destination)
985
+
986
+ def run(self, ticks=100, *, runner=None):
987
+ """Save to a temporary .labp and execute the native headless simulator.
988
+
989
+ Build the runner once with ``headless/build.sh /path/to/game/include``.
990
+ `runner` can override the executable path. The returned SimulationResult
991
+ is truthy only when all named tests passed.
992
+ """
993
+ ticks = _as_int(ticks, "ticks")
994
+ if ticks < 0:
995
+ raise ValueError("ticks must be >= 0")
996
+ if runner is None:
997
+ executable = Path(__file__).resolve().parent / "headless" / (
998
+ "lasim.exe" if os.name == "nt" else "lasim"
999
+ )
1000
+ else:
1001
+ executable = Path(runner)
1002
+ if not executable.is_file():
1003
+ raise FileNotFoundError(
1004
+ f"headless simulator not found at {executable}; build it with "
1005
+ "headless/build.sh /path/to/Logic-Arrows-3D/include"
1006
+ )
1007
+
1008
+ with tempfile.TemporaryDirectory(prefix="lac_run_") as temporary:
1009
+ blueprint_path = Path(temporary) / "circuit.labp"
1010
+ self.save(blueprint_path)
1011
+ completed = subprocess.run(
1012
+ [str(executable), str(blueprint_path), str(ticks)],
1013
+ capture_output=True,
1014
+ text=True,
1015
+ check=False,
1016
+ )
1017
+
1018
+ result_line = next(
1019
+ (line[len("TEST_RESULTS "):] for line in completed.stderr.splitlines()
1020
+ if line.startswith("TEST_RESULTS ")),
1021
+ None,
1022
+ )
1023
+ if completed.returncode not in (0, 3) or result_line is None:
1024
+ raise RuntimeError(
1025
+ "headless simulation failed\n"
1026
+ f"exit code: {completed.returncode}\n"
1027
+ f"stdout:\n{completed.stdout}\n"
1028
+ f"stderr:\n{completed.stderr}"
1029
+ )
1030
+ try:
1031
+ result_json = json.loads(result_line)
1032
+ except json.JSONDecodeError as exc:
1033
+ raise RuntimeError(f"simulator returned invalid test results: {result_line}") from exc
1034
+ return SimulationResult(result_json, completed.stdout, completed.stderr, completed.returncode)