tuanp.dev

Part 7 of 20 · about an hour

See the tiles hidden in the cartridge

Last time our emulator opened a real cartridge file and ran the program inside it. But we skipped the last 8,192 bytes of the file. Today we find out what they are, and get our first picture.

By the end of this part

  • You can pick a single bit out of a byte.
  • Your emulator decodes the cartridge's pictures and prints them in the terminal.
  • The trace has an on/off switch.

Squint at this

The last exercise of Part 6 printed sixteen of the unexplored bytes in binary. Here is what comes out:

$ cargo run -q
PRG ROM: 32768 bytes
01101100
10010010
11000010
10000010
01000100
00101000
00010000
00000000
01101100
11111110
10111110
11111110
01111100
00111000
00010000
00000000

(I printed them before running the Cpu, so there is no trace in the way.) Look at the ones in the first eight rows. It is the outline of a heart. The second eight rows are a heart too, filled in this time. Those bytes are not numbers to calculate with. They are a drawing.

Tiles

The cartridge file from Part 6 again: header, PRG ROM, CHR ROM. This time the CHR ROM section at the end is the shaded one.headerPRG ROMCHR ROM16 bytes32,768 bytes8,192 bytesused since Part 6today
Remember this picture? Today is the other end of the file.

The last section of the file is the CHR ROM. What is CHR ROM? CHR ROM is the part of a cartridge that holds its pictures. ("CHR" is short for character, an old word for a small picture such as a letter.)

The pictures all have the same size. Each one is a tile. What is a tile? A tile is a picture 8 pixels wide and 8 pixels high. Everything a NES ever shows, every letter, cloud and brick, is built out of tiles. Each tile takes 16 bytes, so our 8,192 bytes have room for 512 of them, numbered from 0. Our cartridge uses the first eight and leaves the rest empty. The heart is tile 7, which is why the exercise started at 7 * 16.

Two bits for every pixel

Why two hearts? A pixel in a tile is not just on or off. It can be one of four colours, numbered 0 to 3, and counting to 3 takes two bits. So every pixel needs two bits, and the NES stores them in an unusual way: not side by side, but in two separate layers.

Each layer is called a bit plane. What is a bit plane? A bit plane is one layer of a picture, holding just one bit of every pixel. A tile's first 8 bytes are the plane of low bits, one byte per row. Its last 8 bytes are the plane of high bits.

The sixteen bytes of tile 7 in a row. Bytes 0 to 7 are labelled "low bits, rows 0 to 7" and bytes 8 to 15 are labelled "high bits, rows 0 to 7". Byte 2, holding C2, and byte 10, holding BE, are highlighted: together they are row 2 of the tile.01237810156C92C282442810006CFEBEFE7C381000low bits, rows 0 to 7high bits, rows 0 to 7row 2 of the tile is byte 2 together with byte 2 + 8
One tile, sixteen bytes. The two halves of any row are always eight bytes apart.

So to find the colour of the pixel at column x of row y, we need bit x of byte y, and bit x of byte y + 8. Which raises a question we have not faced yet: how do you get one bit out of a byte?

Picking one bit out of a byte

Rust, like most languages, has operators that work on the individual bits of a number. We need two.

The first is the shift, written >>. What is a shift? A shift slides all the bits of a number sideways by some number of places; bits pushed off the end are lost. 0b11000010 >> 6 slides everything six places to the right and leaves 0b00000011. (0b is how Rust spells binary, as 0x spells hex.) The bit we care about is now at the right-hand end.

The second is the mask, written &. What is a mask? A mask keeps only the bits of a number that are also set in a second number, and clears the rest. 0b00000011 & 1 keeps only the last bit: the answer is 1. (Yes, this is the same character as the borrow from Part 6. Between two numbers it means mask; in front of a value it means borrow.)

Shift the bit you want to the end, then mask off everything else. Watch it decode row 2 of the heart, C2 and BE.

Two rows of eight bits: the low byte 1 1 0 0 0 0 1 0 and, under it, the high byte 1 0 1 1 1 1 1 0. A frame moves across the columns from left to right. For each column, the high bit times two plus the low bit gives a colour, and the matching character is written below: hash, plus, o, o, o, o, hash, dot.lohi1100001010111110out#+oooo#.x = ?colour = ?
let shift = 7 - x;
let lo_bit = (lo >> shift) & 1;
let hi_bit = (hi >> shift) & 1;
hi_bit * 2 + lo_bit
  1. Row 2 of the heart: the low-bit byte C2 on top, the high-bit byte BE under it.
  2. Pixel 0 is the leftmost bit, so it must be shifted 7 places to reach the end. Low bit 1, high bit 1: colour 3, which we print as #.
  3. Pixel 1: shift by 6. Low bit 1, high bit 0. Colour 1, printed as +.
  4. Pixel 2: shift by 5. Low bit 0, high bit 1. The high bit counts double: colour 2, printed as o.
  5. Pixels 3, 4 and 5 have the same two bits as pixel 2. Three more of colour 2.
  6. Pixel 6: both bits are 1 again. Colour 3.
  7. Pixel 7 needs no shift at all. Both bits are 0: colour 0, printed as . The row is done.

Build it: one tile

First, main must cut the CHR ROM out of the file, the same way it cut out the program. Byte 5 of the header says how many 8,192-byte blocks there are:

src/main.rsSnapshot
    let prg_size = rom[4] as usize * 16384;
    let chr_size = rom[5] as usize * 8192;
    let prg = &rom[16..16 + prg_size];
    let chr = &rom[16 + prg_size..16 + prg_size + chr_size];
    println!("PRG ROM: {} bytes, CHR ROM: {} bytes", prg.len(), chr.len());

Then the decoder itself. It is not a method of Cpu, because it has nothing to do with the processor. It is a plain function, written outside any impl, above main:

const SHADES: [char; 4] = ['.', '+', 'o', '#'];
 
// The colour (0 to 3) of one pixel of one tile.
fn tile_pixel(chr: &[u8], tile: usize, x: usize, y: usize) -> u8 {
    let lo = chr[tile * 16 + y];
    let hi = chr[tile * 16 + y + 8];
    let shift = 7 - x;
    let lo_bit = (lo >> shift) & 1;
    let hi_bit = (hi >> shift) & 1;
    hi_bit * 2 + lo_bit
}
  • const defines a value that is fixed for the whole program. By convention its name is in capitals. SHADES is an array of four characters; a char is written in single quotes.
  • tile * 16 is where the tile starts; + y picks the row in the low plane; + 8 more gives the same row in the high plane. That is the anatomy picture above, as arithmetic.
  • The last line has no semicolon, so it is the value the function returns: a colour from 0 to 3.

To try it, print tile 7 at the end of main, with one loop inside another: for each row, for each pixel in that row.

first stageSnapshot
    for y in 0..8 {
        for x in 0..8 {
            let colour = tile_pixel(chr, 7, x, y);
            print!("{}", SHADES[colour as usize]);
        }
        println!();
    }
$ cargo run -q
PRG ROM: 32768 bytes, CHR ROM: 8192 bytes
.##.##..
#oo#oo#.
#+oooo#.
#ooooo#.
.#ooo#..
..#o#...
...#....
........

(Your output will have the trace in front of it; we deal with that in a moment.) There is the heart, in four "colours". The single + is the little highlight we decoded in the stepper.

Build it: all the tiles

One tile is nice; a row of them is better. To print tiles side by side we cannot finish one tile before starting the next, because a terminal prints line by line. So the loops go: for each row, for each tile, for each pixel.

// Print some tiles side by side.
fn print_tiles(chr: &[u8], first: usize, count: usize) {
    for y in 0..8 {
        for tile in first..first + count {
            for x in 0..8 {
                let colour = tile_pixel(chr, tile, x, y);
                print!("{}", SHADES[colour as usize]);
            }
            print!(" ");
        }
        println!();
    }
}

Replace the experiment at the end of main with one call:

    print_tiles(chr, 0, 8);

Give the trace a switch

The trace has been invaluable, but now it buries the picture. Add a field trace: bool to the Cpu, set it to false in new, and wrap the trace line in an if:

            if self.trace {
                println!(
                    "{:04X}  {:02X}  A={:02X} X={:02X} Z={}",
                    self.pc, self.read(self.pc), self.a, self.x, self.zero as u8
                );
            }

While you are there, remove the "jumping to itself" message from JMP and leave just the break. Whenever you want the trace back, write cpu.trace = true; in main before cpu.run().

$ cargo run -q
PRG ROM: 32768 bytes, CHR ROM: 8192 bytes
........ ##..##.. ######.. ##...... .####... ##..##.. .#####.. .##.##..
........ ##..##.. ##...... ##...... ##..##.. ###.##.. ##...... #oo#oo#.
........ ##..##.. ##...... ##...... ##..##.. ######.. ##...... #+oooo#.
........ ######.. #####... ##...... ##..##.. ######.. .####... #ooooo#.
........ ##..##.. ##...... ##...... ##..##.. ##.###.. ....##.. .#ooo#..
........ ##..##.. ##...... ##...... ##..##.. ##..##.. ....##.. ..#o#...
........ ##..##.. ######.. ######.. .####... ##..##.. #####... ...#....
........ ........ ........ ........ ........ ........ ........ ........

Tiles 0 to 7: a blank, six letters and a heart. These pictures were inside the file the whole time.

Now recall the ten bytes of data at the start of the cartridge's program, the ones it sends one by one to address $2007:

01 02 03 03 04 00 05 02 06 07

Read them as tile numbers, and look them up in the row above.

Shortcuts we took on purpose

  • We show the four colours as four characters. On a real NES, a separate table called a palette says which actual colour each number means, and it can change while the game runs. Left open.
  • The trace switch is a line of source code, not a command-line option. Left open; Part 6's exercise 2 shows the way.

What changed today

  • main slices the CHR ROM out of the file.
  • tile_pixel combines one bit from each bit plane into a colour, using shift and mask.
  • print_tiles prints any run of tiles side by side.
  • The Cpu has a trace switch, off by default.

Now you

  1. On paper: decode row 1 of the heart, 10010010 and 11111110, into eight colours. Check it against the printed tile.
  2. Change SHADES to four characters you like better. A space and '█' at the two ends work well.
  3. Terminal characters are taller than they are wide, so the tiles look squeezed. Print every pixel twice, side by side, to square them up.
  4. Write a function print_message(chr: &[u8], tiles: &[u8]) that prints the listed tiles side by side with no gap between them, and call it with &[1, 2, 3, 3, 4, 0, 5, 2, 6, 7]. You will have put a picture on the screen by telling your emulator which tiles go where. In Part 8, the cartridge's own program does the telling.
    HintIt is print_tiles with for tile in tiles as the middle loop. Each tile is then a borrowed u8; write *tile as usize to get the number itself.

Check your understanding

  1. What is CHR ROM?
    AnswerThe part of a cartridge that holds its pictures.
  2. What is a tile?
    AnswerA picture 8 pixels wide and 8 pixels high, stored in 16 bytes.
  3. What is a bit plane?
    AnswerOne layer of a picture, holding just one bit of every pixel. A tile has two: low bits, then high bits.
  4. What is a shift?
    AnswerSliding all the bits of a number sideways by some number of places; bits pushed off the end are lost.
  5. What is a mask?
    AnswerKeeping only the bits of a number that are also set in a second number. & 1 keeps only the last bit.

Next time

Right now we have a program that hands out tile numbers and a decoder that can draw tiles, and nothing connecting the two. In Part 8 we build the missing piece, the chip the program has been talking to all along, and the cartridge draws its own picture.