257. 解码图案表

实现完整的图案表解码。

257 / 356 · tests/chapter_03_ppu_memory_and_graphics_data/test_257_decode_pattern_table.py

参考资料

https://www.nesdev.org/wiki/PPU_pattern_tables

需要更新的文件

emulator/ppu/chr_decoder.py

需要实现的函数

decode_pattern_table(pattern_table_bytes: bytes) -> PatternTable

需要添加的常量

PATTERN_TABLE_SIZE = 0x1000
CHR_TILE_SIZE = 16
PATTERN_TABLE_TILE_COUNT = 256

什么是图案表?图案表是一块包含 256 个图块的 CHR 图形数据块。

基础计算

one CHR tile      = 16 bytes
one pattern table = 4096 bytes = $1000
4096 / 16         = 256 tiles

NES 的 PPU 有两个图案表地址范围

$0000-$0FFF -> pattern table 0
$1000-$1FFF -> pattern table 1

这一步只是把一个 4096 字节的图案表解码成 256 个已解码的图块,还不会绘制图像。

建议的实现示例

PATTERN_TABLE_SIZE = 0x1000
CHR_TILE_SIZE = 16
PATTERN_TABLE_TILE_COUNT = 256

PatternTile = list[list[int]]
PatternTable = list[PatternTile]

def decode_pattern_table(pattern_table_bytes: bytes) -> PatternTable:
    if len(pattern_table_bytes) != PATTERN_TABLE_SIZE:
        raise ValueError("Pattern table must be 4096 bytes")

    tiles = []

    for tile_index in range(PATTERN_TABLE_TILE_COUNT):
        start = tile_index * CHR_TILE_SIZE
        end = start + CHR_TILE_SIZE
        tiles.append(decode_chr_tile(pattern_table_bytes[start:end]))

    return tiles

不在本步骤范围内

  • 把图块排列成 128x128 的调试网格
  • PNG/图像输出
  • RGB/NES 调色板颜色
  • 名称表背景渲染
  • PPU 时序

运行本课

uv run pytest tests/chapter_03_ppu_memory_and_graphics_data/test_257_decode_pattern_table.py -v