# SPDX-License-Identifier: MIT """Suzy's sprite engine: the SCB walk, unpacking, sizing, stretch, tilt, quadrants, clipping, the eight sprite types, the collision buffer and depository, EVERON. Modelling level: functional per destination row (milestone 4), with each RAM access charged to the bus so the CPU, display DMA and refresh interleave; the per-access costs are milestone 5's (``COSTS`` below). Sources (no emulator source was read; restart rules): - DOC "Spec §6": the Epyx specification, chapter 6 "Sprite/Collision" (SCB layout, types, collision process, stretch, tilt, skip, size offsets, packing notes, bugs). - DOC "Appx 2": the hardware address appendix (SPRCTL0, SPRCTL1, SPRCOLL, SPRGO, SPRSYS, the SCB register file). - DOC "App 4": the Epyx appendix 4 "Sprite Engine" (data lines: offset 0 ends the sprite, 1 changes quadrant counter-clockwise; clipping and super-clipping). - TEST ROM / LT: lynx-tests ``lynx-sprite-performance.md`` (MIT; measured on consoles by its author): the packet header layout, 8.8 size accumulators, the pen behaviour by type table, the literal end-of-row counts, Everon. """ from __future__ import annotations import os # SCB register file offsets (DOC Appx 2, $FC00 + offset; words, low byte first). TILTACUM = 0x02 HOFF = 0x04 VOFF = 0x06 VIDBAS = 0x08 COLLBAS = 0x0A VIDADR = 0x0C COLLADR = 0x0E SCBNEXT = 0x10 SPRDLINE = 0x12 HPOSSTRT = 0x14 VPOSSTRT = 0x16 SPRHSIZ = 0x18 SPRVSIZ = 0x1A STRETCH = 0x1C TILT = 0x1E SPRDOFF = 0x20 SPRVPOS = 0x22 COLLOFF = 0x24 VSIZACUM = 0x26 HSIZOFF = 0x28 VSIZOFF = 0x2A SCBADR = 0x2C PROCADR = 0x2E SCREEN_W, SCREEN_H = 160, 102 # DOC Spec §5: 160 x 102 pens, 80 bytes a line # Suzy's time (milestone 5), in ticks. The spec gives no cycle counts (Spec §6 names the # pipeline: source FIFO, unpacker, pixel builder, pixel FIFO, merger, collision unit). # LT (lynx-sprite-performance.md, measured on consoles): a destination row costs about # the *maximum* of its overlapping paths plus fixed work, not their sum. Built so: # row = ROW + max(PEN * pens decoded, OUT * outputs, BUS * (source bytes + video # bytes) + RMW * merged bytes + collision groups) + XOR * video bytes # + STRETCH_ROW / TILT_ROW when enabled COSTS = { # HYPOTHESIS: one SCB byte read (no measurement isolates it). "scb": 4, # TEST ROM (LT "Stretch and tilt"): a source record's offset read takes 2 ticks; a # record that generates no row adds an 18-tick reject stage. "offset": 2, "reject": 18, # FITTED (scripts/m5_fit.py, coordinate descent) to sprites1 1-8, the literal and # expansion rows: fixed row work, ticks per decoded pen, per generated output (LT: # "72 + 2 * outputs" for one pen expanded), per bus byte (LT: the 4,2,2,2 # destination-word slots, 2.5 a byte); started from those LT values (76, 2, 2, # 2.56). Only 3 of the 8 fitting tests land inside their windows: the structure is # short of the hardware's (1 bpp and 2 bpp full rows differ on hardware, not here). # Held out (sprites2-5): validation.md "M5". "row": 68, "pen16": 32, # sixteenths of a tick "out16": 32, "bus16": 40, # TEST ROM (LT): a read/write merge adds about 2 ticks per destination byte; XOR # about 2 per destination byte; collision RAM transactions per 8-pixel screen group: # write or read 10, read plus write or detect 18; stretch 8 and tilt 18 per row. "rmw": 2, "xor": 2, "coll": 10, "coll_detect": 18, "stretch": 8, "tilt": 18, } YIELD_TICKS = 40 # DOC Spec §4: Suzy yields the bus to Mikey within 40 ticks # The named switch between the two row timelines (docs/validation.md "M5 structure"): # "paths" = the max-of-paths model above (LT's rule, four constants FITTED on # sprites1); "measured" = the timeline read from the Batman Returns capture # (Suzy._measured_row). The default is the one that scores better on held-out windows: # on sprites2-5 (held out from the paths fit; nothing was fitted for "measured") the # measured timeline puts 15 of 32 inside their windows, the paths model 13 (2026-11-14). TIMELINE = os.environ.get("LYNX_SUZY_TIMELINE", "measured") # MEASURED (scripts/la_sprite.py --dest E000-FFE0 on lynx2-mikey-batman-75hz, first 80 ms; # the most common gap of each phase, Suzy's RAS groups only, display DMA and refresh set # aside): a RAS group's first CAS 4 ticks after the previous group's last, then one CAS # every 2 ticks; 32 ticks from the line's offset byte to its first data group; 22 from # the last destination group to the next line; a destination group of 4 pixels-pairs # starts 16 ticks after the one before when not bus-bound (8 pixels: 2 a pixel). MEASURED = {"offset": 4, "start": 32, "ras": 4, "pixel": 2, "end": 22} # The eight types (DOC Appx 2 SPRCTL0 B2-B0; DOC Spec §6 table with the shadow error; # LT "Pen behavior by type"). Per type, per pen class: (video, collision) where video # is "T" transparent, "O" opaque, "X" exclusive-or, and collision is None (no activity), # "P" preserve (no detect, no write), "D" detect then write the sprite's number, "W" # write without detecting (background). # pen 0 pen E pen F other pens TYPES = ( (("O", "W"), ("O", "P"), ("O", "W"), ("O", "W")), # 0 background, shadow (("O", None), ("O", None), ("O", None), ("O", None)), # 1 background, no collision (("T", None), ("O", "P"), ("T", "D"), ("O", "D")), # 2 boundary-shadow (("T", None), ("O", "D"), ("T", "D"), ("O", "D")), # 3 boundary (("T", None), ("O", "D"), ("O", "D"), ("O", "D")), # 4 normal (("T", None), ("O", None), ("O", None), ("O", None)), # 5 non-collideable (("T", None), ("X", "P"), ("X", "D"), ("X", "D")), # 6 exclusive-or, shadow (("T", None), ("O", "P"), ("O", "D"), ("O", "D")), # 7 shadow ) # DOC Spec §6: "At the completion of the processing of each collideable sprite, the # hardware writes a byte into the 'collision depository'"; background types write no # depository (Spec §6 "Background-Shadow Sprites"); LT: types 2, 3, 4, 6, 7. DEPOSITORY_TYPES = (2, 3, 4, 6, 7) def _signed(value: int) -> int: return value - 0x10000 if value & 0x8000 else value class SpriteEngine: """Runs one sprite list from SCBNEXT. ``start`` arms it; ``run(bus)`` advances it by one destination row (or one SCB header) and returns True when the list is done.""" __slots__ = ("bus", "consumed", "pens", "steps", "suzy") def __init__(self, suzy) -> None: self.suzy = suzy self.pens = bytearray(16) # the pen index palette (DOC Spec §6: 16 nybbles) self.steps = None self.bus = None self.consumed = 0 # bits of the current source line decoded so far def start(self) -> None: # DOC Spec §6: "This engine starts only from its beginning." self.steps = self._walk() def run(self, bus) -> bool: if self.steps is None: return True self.bus = bus try: next(self.steps) except StopIteration: self.steps = None return True return False # -- RAM, through the bus ------------------------------------------------------------ def _charge(self, ticks: int) -> None: """Hold the bus for ``ticks``, yielding to display DMA and refresh between chunks (DOC Spec §4: within 40 ticks).""" bus = self.bus while ticks > 0: chunk = min(ticks, YIELD_TICKS) bus.suzy_cycles(chunk) ticks -= chunk def _read(self, address: int) -> int: """An SCB byte read (the row traffic is charged per row by ``_row``).""" self._charge(COSTS["scb"]) return self.bus.ram[address & 0xFFFF] def _read16(self, address: int) -> int: return self._read(address) | (self._read(address + 1) << 8) def _write(self, address: int, value: int) -> None: self._charge(COSTS["scb"]) self.bus.ram[address & 0xFFFF] = value # -- the SCB walk -------------------------------------------------------------------- def _walk(self): suzy = self.suzy while True: scb = suzy.word(SCBNEXT) # DOC Spec §16 bug list: only the upper byte of SCBNEXT is tested for the end. if not scb >> 8: return suzy.set_word(SCBADR, scb) # DOC Spec §6 "Skip Sprite": the first 5 bytes are always read and loaded. suzy.sprctl0 = self._read(scb) suzy.sprctl1 = self._read(scb + 1) suzy.sprcoll = self._read(scb + 2) suzy.set_word(SCBNEXT, self._read16(scb + 3)) yield ctl1 = suzy.sprctl1 if not ctl1 & 0x04: address = scb + 5 for offset in (SPRDLINE, HPOSSTRT, VPOSSTRT): suzy.set_word(offset, self._read16(address)) address += 2 # DOC Appx 2 SPRCTL1 B5-B4, reload depth: 1 = H/V size, 2 = + stretch, # 3 = + tilt. depth = (ctl1 >> 4) & 3 for offset in (SPRHSIZ, SPRVSIZ, STRETCH, TILT)[: (depth + 1) if depth else 0]: suzy.set_word(offset, self._read16(address)) address += 2 if not ctl1 & 0x08: # DOC Appx 2 SPRCTL1 B3: 0 = reload the palette for i in range(8): byte = self._read(address + i) # DOC Spec §6 "Bits in Bytes": PIN 0 is the upper nybble of byte 0. self.pens[2 * i] = byte >> 4 self.pens[2 * i + 1] = byte & 0x0F yield from self._sprite(scb, depth) # DOC Appx 2 SPRSYS B1: stop at the end of the current sprite. if suzy.stop_request: return # -- one sprite ---------------------------------------------------------------------- def _sprite(self, scb: int, depth: int): suzy = self.suzy ram = self.bus.ram ctl0, ctl1 = suzy.sprctl0, suzy.sprctl1 bpp = (ctl0 >> 6) + 1 # DOC Appx 2 SPRCTL0 B7-B6: bits per pixel - 1 kind = ctl0 & 7 # DOC Spec §6 "Anti-Collision Devices": SPRCOLL B5 or SPRSYS B5 disable all # collision activity for the sprite. collide = not (suzy.sprcoll & 0x20) and not (suzy.sprsys & 0x20) number = suzy.sprcoll & 0x0F state = [0, False] # fred (DOC Spec §6 "Collision Process"), ever on screen hoff, voff = _signed(suzy.word(HOFF)), _signed(suzy.word(VOFF)) ref_h, ref_v = suzy.word(HPOSSTRT), suzy.word(VPOSSTRT) # DOC Appx 2 SPRCTL1 B0 = start drawing left, B1 = start drawing up; DOC App 4: # quadrants follow counter-clockwise: right-down, right-up, left-up, left-down. quadrant = {(0, 0): 0, (0, 1): 1, (1, 1): 2, (1, 0): 3}[(ctl1 & 1, (ctl1 >> 1) & 1)] first_left = first_up = None suzy.set_word(TILTACUM, 0) # LT: the tilt accumulator starts from zero data = suzy.word(SPRDLINE) while True: left = quadrant in (2, 3) up = quadrant in (1, 2) # DOC Spec §6 "Horizontal and Vertical Size Offset": up and left start from 0, # down and right from VSIZOFF / HSIZOFF. TEST ROM (sprites2 8, the Alpine # Games protection SCB: H-flipped, drawn leftwards, HSIZOFF $7F needed for # its third pen to reach x = 159): the quadrant's direction before the flip # chooses the offset. hacc0 = 0 if left else suzy.word(HSIZOFF) vacc0 = 0 if up else suzy.word(VSIZOFF) if ctl0 & 0x20: # DOC Appx 2 SPRCTL0 B5: H flip (the pivot is the reference) left = not left if ctl0 & 0x10: # B4: V flip up = not up if first_left is None: first_left, first_up = left, up hstep, vstep = (-1 if left else 1), (-1 if up else 1) # HYPOTHESIS: a quadrant drawn the other way from the first one starts one # pixel (line) beyond the reference, so the reference line is drawn once # (DOC Spec §6: "there will be a positional alteration if the starting # quadrant is changed"). Settled by lynx-tests where a test covers it. y = _signed(ref_v) - voff + (vstep if up != first_up else 0) hpos = _signed(ref_h) + (hstep if left != first_left else 0) suzy.set_word(HPOSSTRT, ref_h) vacc = vacc0 while True: self._charge(COSTS["offset"]) offset = ram[data & 0xFFFF] if offset == 0: # DOC App 4: end of sprite data self._depository(scb, kind, collide, state) return if offset == 1: # DOC App 4: end of quadrant data += 1 quadrant = (quadrant + 1) & 3 break line = (data + 1) & 0xFFFF # LT: 8.8 size accumulators; the integer part is the row count. vacc += suzy.word(SPRVSIZ) rows, vacc = vacc >> 8, vacc & 0xFF suzy.set_word(VSIZACUM, vacc) if not rows: self._charge(COSTS["reject"]) for _ in range(rows): if 0 <= y < SCREEN_H: ticks = self._row(ram, line, offset - 1, bpp, kind, collide, number, hpos - hoff, y, left, hacc0, state) # fmt: skip else: ticks = COSTS["reject"] # HYPOTHESIS: an off-window row is rejected ticks += COSTS["stretch"] if depth >= 2 else 0 ticks += COSTS["tilt"] if depth >= 3 else 0 self._charge(ticks) y += vstep # DOC Spec §6 "Horizontal Stretch", "Vertical Stretch", "Tilt": after # every destination line, when the reload depth enables them. if depth >= 2: stretch = suzy.word(STRETCH) suzy.set_word(SPRHSIZ, suzy.word(SPRHSIZ) + stretch) if suzy.sprsys & 0x10: # DOC Appx 2 SPRSYS B4: Vstretch suzy.set_word(SPRVSIZ, suzy.word(SPRVSIZ) + stretch) if depth >= 3: total = suzy.word(TILTACUM) + _signed(suzy.word(TILT)) hpos += total >> 8 suzy.set_word(TILTACUM, total & 0xFF) suzy.set_word(HPOSSTRT, hpos) yield data = (data + offset) & 0xFFFF def _row(self, ram, line, length, bpp, kind, collide, number, x, y, left, hacc, state): """One destination row of one source line; returns its ticks (``COSTS``).""" suzy = self.suzy pens = self.pens rules = TYPES[kind] hsize = suzy.word(SPRHSIZ) step = -1 if left else 1 video = suzy.word(VIDBAS) + y * 80 colls = suzy.word(COLLBAS) + y * 80 decoded = outputs = 0 # Destination bytes touched: x >> 1 -> (pixels written opaque/XOR, pixels seen). touched: dict[int, list[int]] = {} groups: dict[int, bool] = {} # collision 8-pixel screen group -> detected xor = False source = self._decode(line, length, bpp) for index in source: decoded += 1 hacc += hsize count, hacc = hacc >> 8, hacc & 0xFF if not count: continue pen = pens[index] rule = rules[0 if pen == 0 else 1 if pen == 0x0E else 2 if pen == 0x0F else 3] stop = False for _ in range(count): outputs += 1 if 0 <= x < SCREEN_W: state[1] = True cell = touched.setdefault(x >> 1, [0, 0]) cell[1] += 1 if rule[0] != "T": cell[0] += 1 xor = xor or rule[0] == "X" if collide and rule[1] in ("D", "W"): groups[x >> 3] = groups.get(x >> 3, False) or rule[1] == "D" self._plot(ram, video, colls, x, pen, rule, collide, number, state) elif (x >= SCREEN_W and step > 0) or (x < 0 and step < 0): stop = True # App 4 + LT: the first off-window output ends the line break x += step if stop: break source_bytes = min(length, (self.consumed + 7) >> 3) merged = sum(1 for opaque, seen in touched.values() if opaque and opaque < 2) merged += sum(1 for opaque, seen in touched.values() if opaque == 0 and seen) bus = (COSTS["bus16"] * (source_bytes + len(touched))) >> 4 bus += COSTS["rmw"] * merged bus += sum(COSTS["coll_detect"] if d else COSTS["coll"] for d in groups.values()) if TIMELINE == "measured": return self._measured_row(video, touched, groups, source_bytes, xor) paths = ((COSTS["pen16"] * decoded) >> 4, (COSTS["out16"] * outputs) >> 4, bus) ticks = COSTS["row"] + max(paths) if xor: ticks += COSTS["xor"] * len(touched) return ticks @staticmethod def _measured_row(video, touched, groups, source_bytes, xor) -> int: """A destination row on the timeline read from a game capture (``MEASURED`` below: scripts/la_sprite.py on lynx2-mikey-batman-75hz, modes of the gaps): the line's offset byte, a wait, the source bytes in RAS groups of up to four 2-tick CAS cycles, then the destination bytes in 4-byte-aligned RAS groups, each as long as its bus cycles or its pixels at 2 ticks each, whichever is longer, then the line-end wait. Collision groups are charged like destination groups (HYPOTHESIS: the capture's game draws without visible collision runs).""" m = MEASURED ticks = m["offset"] + m["start"] ticks += sum( m["ras"] + 2 * (min(4, source_bytes - k) - 1) for k in range(0, source_bytes, 4) ) cells: dict[int, list[int]] = {} for byte, (opaque, seen) in touched.items(): group = cells.setdefault(((video + byte) & 0xFFFF) >> 2, [0, 0]) group[0] += 1 + (1 if (opaque and opaque < 2) or (not opaque and seen) else 0) group[1] += seen for cas, pixels in cells.values(): ticks += max(m["ras"] + 2 * (cas - 1), m["pixel"] * pixels) for detected in groups.values(): ticks += m["ras"] + 2 * ((8 if detected else 4) - 1) if xor: ticks += 2 * len(touched) # TEST ROM (LT): XOR about 2 per destination byte return ticks + m["end"] def _plot(self, ram, video, colls, x, pen, rule, collide, number, state) -> None: shift = 0 if x & 1 else 4 # DOC Spec §6 "Bits in Bytes": left pixel in bits 7-4 address = (video + (x >> 1)) & 0xFFFF mode, collision = rule if mode != "T": byte = ram[address] old = (byte >> shift) & 0x0F new = old ^ pen if mode == "X" else pen ram[address] = (byte & ~(0x0F << shift) & 0xFF) | (new << shift) if collision is None or collision == "P" or not collide: return address = (colls + (x >> 1)) & 0xFFFF byte = ram[address] if collision == "D": state[0] = max(state[0], (byte >> shift) & 0x0F) ram[address] = (byte & ~(0x0F << shift) & 0xFF) | (number << shift) def _decode(self, line: int, length: int, bpp: int): """The pen indices of one source line (DOC Spec §6 "Data Packing Format"; LT). The line's last bit is never decoded: DOC Spec §6 "the last meaningful bit of the data packet at the end of a scan line [must] not occur in the last bit of a byte"; TEST ROM (LT "End-of-row hardware bug": 7/3/2/1 extra zero indices from a pad byte at 1/2/3/4 bpp) agrees with a stream one bit shorter than the line. """ ram = self.bus.ram data = [ram[(line + i) & 0xFFFF] for i in range(length)] bits = 8 * length - 1 position = 0 self.consumed = 0 def take(n: int) -> int: nonlocal position value = 0 for _ in range(n): byte = data[position >> 3] value = (value << 1) | ((byte >> (7 - (position & 7))) & 1) position += 1 self.consumed = position return value if self.suzy.sprctl1 & 0x80: # DOC Appx 2 SPRCTL1 B7: totally literal while position + bpp <= bits: yield take(bpp) return while position + 5 <= bits: header = take(5) if header == 0: # DOC Spec §6: '00000' ends the line return count = (header & 0x0F) + 1 # LT: bit 4 literal, bits 3-0 count - 1 if header & 0x10: for _ in range(count): if position + bpp > bits: return yield take(bpp) else: if position + bpp > bits: return index = take(bpp) for _ in range(count): yield index def _depository(self, scb: int, kind: int, collide: bool, state: list) -> None: suzy = self.suzy address = (scb + _signed(suzy.word(COLLOFF))) & 0xFFFF everon = suzy.sprgo & 0x04 # DOC Appx 2 SPRGO B2: enable the everon detector value = None if collide and kind in DEPOSITORY_TYPES: value = state[0] if everon: # DOC Spec §12.5 + LT: bit 7 is 1 only when the sprite never touched the # screen. HYPOTHESIS (U16): written for every type, the low bits being the # collision result where there is one and kept otherwise. low = value if value is not None else self.bus.ram[address] & 0x7F value = low | (0 if state[1] else 0x80) if value is not None: self._write(address, value)