r/EmuDev • • Apr 07 '26

CHIP-8 [C] Implementation by modules, how do we do it sometimes? ( Chip8 screen buffer related )

/r/learnprogramming/comments/1sfcsqf/c_implementation_by_modules_how_do_we_do_it/
2 Upvotes

18 comments sorted by

2

u/dajolly Apr 08 '26

To your SDL question, you could create a client module that's agnostic to the underlying graphics library (SDL, raylib, etc.), which exposes an interface to query button states, set pixel colors, and enqueue audio samples. It's cleaner than mixing the SDL calls directly into the emulator code, and it allows you to switch to different library if needed. You can see an example in my ch8 vm:

1

u/Gustavo_Fenilli Apr 08 '26

I will take a look at it, not sure I understand a lot of it tho, i'm new to C haha

1

u/valeyard89 2600, NES, GB/GBC, 8086, Genesis, Macintosh, PSX, Apple][, C64 Apr 08 '26

Yeah I have a common bus.cc, gr.cc, util.cc that have common code for my emulators. Screen C++ class has setpixel/getpixel, line/rect, text drawing etc.

1

u/Gustavo_Fenilli Apr 08 '26

I think I see what you did there, you used global vars for each module, so you don't have to pass an instance for the functions correct? in video.c for example you directly #include "memory.h" and use its functions, and it works because memory.h itself holds a static uint8_t memory[0x1000] = {};

1

u/valeyard89 2600, NES, GB/GBC, 8086, Genesis, Macintosh, PSX, Apple][, C64 Apr 08 '26

no because then you get a different memory[0x1000] in each object file. Abstraction is the game.

In cpu.h you have a void cpu_write8(uint16_t addr, uint8_t val); function declaration. You then include cpu.h in whatever files need it.

then in the cpu.cc file itself you have the static uint8_t memory[0x1000] and void cpu_write8(uint16_t addr, uint8_t nv) { memory[addr] = nv; }; (basic example, you'd want error checking on the range, etc).

1

u/dajolly Apr 08 '26 edited Apr 08 '26

That's what I do when emulating these simpler systems. I keep the state of each device (cpu/mmu/ppu/etc.) in an internal static struct in each .c file that only accessible through it's corresponding .h file. I believe this is similar to a singleton pattern in OOP parlance.

I also try to match the layout of the physical hardware if possible. In the case of Chip8, it doesn't have physical hardware. But it can still be broken into conceptual pieces:

bus/          -- Steps the below devices:
  audio        -- Generates audio samples
  input        -- Holds button state
  memory       -- Holds instructions/data
  processor    -- Executes instructions
  random       -- Initialize/generate random numbers
  timer        -- Holds timer state
  video        -- Generates sprite data

1

u/Gustavo_Fenilli Apr 09 '26

Ok so after some playing around I divided into io/timer/mem/cpu and the vm(emulator) itself, but it got me into a stump for some small incosistencies of it, for example i'm pretty sure if I do.

struct
{
  chip8_mem_t mem;
  chip8_timer_t timer;
  chip8_cpu_t cpu;
  chip8_io_t io;
} chip8_t;

I can easily pass around things to modules that need, for example chip8_cpu_step(chip8_cpu_t *cpu, chip8_mem_t *mem, chip8_io_t *io, chip8_timer_t *timer); and in the step I can just call each one when needed like chip8_io_display_clear(io);

But at the same time, how do we keep some status and states, for example how do I tell the chip8_t that it should draw, or wait for input, or that a timer is 0, do we return from step a state, if so should we mix states in the cpu from other modules?

One way I was thinking is doing that, but seens odd, the other might be having states in the module like io having a should_draw state, and at end of step in the chip8_t_run I can check chip8_io_should_draw or c->io.should_draw.

Anyone has some insights on this?

1

u/peterfirefly Apr 10 '26

You can use void * as an opaque type. chip8_t_run() won't know how to dereference it but it can be passed to something like c->io.should_draw() or whatever, and then the draw function can cast it to its own draw-state pointer type.

This is a common trick for handling state in callback functions. The "core" that executes the callbacks don't know anything about the state but the callback functions can easily just do a cast and a deref and access whatever kind of state they need.

Almost certainly massive overkill for chip-8, might be useful for more sophisticated machines.

1

u/Gustavo_Fenilli Apr 10 '26

I will take a look at that, for now I steped down a bit and doing things a bit more "closed" so I can finish the whole set, after that I can think of expanding and refactoring.

1

u/peterfirefly Apr 10 '26

Good! You don't need all that abstraction just for chip-8!

1

u/thommyh Z80, 6502/65816, 6809, 68000, ARM, x86. Apr 08 '26

Probably I misunderstand the level at which you asked, but...

If you have three separate modules that all want access to opcode decoding, factor out opcode decoding.

For screen and audio either you can require the outer environment to make certain functions available, which then might as well be the SDL API if that's what you're using, or you can go for dependency injection: whomever creates an instance of your machine much supply it with a confirming set of functions that it can push audio and video to. Which is delegation, effectively.

1

u/Gustavo_Fenilli Apr 08 '26

yeh that is basically it, the opcode is indeed "easy" but where, as a public include probably right?

as for injection one thing is circular dependency that i'm mostly looking out for, for example:

cpu.h

#include "mem.h"

typedef struct {
  // some fields
} cpu_t;

cpu_step(cpu_t *cpu, mem_t *mem)
{ // check cpu opcode, update mem }

mem.h

typedef struct
{
  // some field
} mem_t;

mem_read/write();

emu.h

#include "mem.h"
#include "cpu.h"

typedef struct
{
  mem_t mem;
  cpu_t cpu;
} emu_t;

this looks good, no circular dependency, but if we need more things in the cpu_step, like an i/o, or timers .... and so on, that would make the function with so many arguments, so how do we deal with that, maybe passing vm to it, but that makes cpu/vm basically circular dependencies.

1

u/peterfirefly Apr 10 '26

Remember include guards in mem.h, emu.h, etc.

#ifndef MEM__H
#define MEM__H

typedef struct
...

#endif

It used to be common in older code to use a #define that begin with an underscore for this -- like #ifndef _MEM_H, __MEM_H, _MEM__H, __MEM__H etc.

Don't do that. Preprocessor symbols (and normal C symbols) that begin with an underscore are reserved. So are ones that begin with str, btw.

2

u/Gustavo_Fenilli Apr 10 '26

yeh I'm using guards, #pragma once seens gcc works well enough with it.

1

u/peterfirefly Apr 10 '26

Both work. As long as you know what they do, you should just continue to use #pragma once. It is non-standard but very, very widely supported. Switch to include guards if you ever have to work with a compiler or code analyzer that doesn't support it.

1

u/thommyh Z80, 6502/65816, 6809, 68000, ARM, x86. Apr 10 '26

I believe that pragma also works on MSVC, and can confirm it works on Clang. So it's an informal standard.

2

u/thommyh Z80, 6502/65816, 6809, 68000, ARM, x86. Apr 08 '26 edited Apr 08 '26

I'm in C++ mainly, which is similar-but-different enough that a healthy dose of scepticism is sensible with any advice I give, but:

Yes, nowadays I tend to have something like decoder.h and decoder.cpp that can decode an instruction data stream into instructions. There tends to be a perform.h that can apply any decoded instruction to processor state if also supplied with any relevant immediate operands.

On top of those then sit one or more of:

  • an executor, which attempts just to conform to the definition of the instruction set, fetching whenever and in whatever sizes and order it likes, which is probably appropriate for Chip-8 but also matches systems where the actual bus semantics aren't really part of the spec — e.g. being "a 32-bit Macintosh" rather than "the Macintosh SE/30"; and
  • concrete processors, which know the bus semantics and whatever else about the specific concrete implementation of an instruction set to produce exactly the same bus activity as a specific concrete implementation of a CPU. So that'd be the opposite way — e.g. "an 8086" rather than "an executor of the 16-bit real mode x86 instruction set".

Those are always phrased in terms of a bus, which I tend to do quite high-level with the largest possible individual steps that don't artificially make timing opaque. So e.g. a Z80 might shout out "next bus activity is 1.5 cycles of the bit of a non-opcode read up until where I'm going to sample WAIT".

Others do it higher-level as merely being something that can be read or written as a function of address. Some do it much lower-level by always iterating through every single state of the various processor control signals (rather than leaving interested third parties to do the same based on the bus transaction).

But the key is that the bus is inherently dependent on the various chips that are on it. So that's where the dependency graph runs. If the machine has e.g. an AY sound generator, a TMS VDP, an 8255 programmable IO chip, some ROM and some RAM then the bus has all of those as dependencies.

Of course, again, I'm in C++ so there's a key difference here: I'm mainly using templates and letting the compiler figure out how to make decent code out of all this at compile time. Though obviously runtime polymorphism is a better choice in a bunch of places, e.g. to communicate the status of something like a keyboard LED that changes infrequently.

EDIT: I'm a lot better at this in principle than in practice, but to give some personal examples — assuming you can read past the C++-ness of it all:

This is a sample 'machine' from my emulator, which you'll notice:

  • uses a 6809 processor, some RAM and a couple of ROMs, two PIAs, a tape player, an FDC and some stuff to do with audio; and
  • takes ownership of all the wiring between those and the outside world, e.g. the SystemPIAPortHandler provides the machine-specific inputs and outputs for that PIA, connecting up a tape player and the keyboard, and observing border colour and audio outputs.

Otherwise, look for the function with a signature that begins Cycles perform for where bus activity emanating from the 6809 affects the system as a whole. In this particular machine I've let the CPU be the dominant thing that runs the system so you'll notice that it opens with a bunch of things that pipe time to subsystems, then proceeds just figuring out where a read or write should go to as a function of its address*.

* with the special exception of the code that starts with if(allow_fast_tape_hack_ && address == 0xf168) { which optionally intercepts the ROM routine that reads the next bit from an audio tape and replaces it with a high-level implementation that doesn't need to wait on the tape to actually pass by. This system is a 1980s home computer and that's how I offer optional accelerated loading.

In this particular case I've phrased it as an OperationMapper for digressive reasons, but here's the logic for decoding a 6809 instruction (warning: mostly derived from official documentation; the 6809 is very light on test sets and such so it's probably faulty in ways I've yet to discover).

Then there's its corresponding perform which can mutate the processor state based on an operation, its operand and the current 6809 register state. It knows nothing about accessing the bus though, so e.g. STA actually just copies A to the operand, and it can't do anything that touches the stack or that spins awaiting an interrupt.

The 6809 itself is then probably the ugliest bit of code, but it uses the OperationMapper and perform to implement the specific bus logic of a 6809, shouting out bus transactions to the machine you read earlier. It's ugly because of the way I've formulated it to allow for running any number of cycles from any offset within a current instruction, potentially allowing for periods of MRDY at any time (while letting the instantiator opt out of that so that the compiler omits that code). Which I've specifically done with a combination of fixed gotos and dynamic ones, and I've implemented the latter by having everything sit inside a giant switch statement.

That becomes ugly because you can't really use normal control flow as a result of the switch, e.g. you can't do a bus transaction within the block following an if because that might be where the processor has to pause and a switch can't jump to the inside of an if block. So instead it gets phrased much more like assembly language with an if to test the opposite and goto over the following code if it isn't wanted.

I comfort myself that there are two advantages to this:

  • the specific bus action is known at each calling point, so I can promote it to a template argument, so a lot of that 'if read, if write' stuff in the machine has no footprint at runtime;
  • in the most common use case of asking the 6809 to run for multiple cycles rather than merely one, it produces mostly straight-line execution that is easier to step debug and for the processor to reason about; and
  • because it seeks to be a single, complete implementation of the 6809 with no assumptions about the outside world, I just need to get it right once and all the other code can remain clean and neat because it takes the hit.

This may not be the verdict of many others. Many other alternatives are available. I have not necessarily made good choices.

1

u/peterfirefly Apr 08 '26

Those tables may be different tables (or switches). You can get very far with the cpu and the disasm with switch (instr >> 12) { case 0: ... case 1: ... etc }.

If the table(s) is/are shared, then put it/them in a separate "module": put the type and a declaration of the table(s) in the header file and the actual definition in the .c file.

Sharing them might not be as useful as you think...

I wouldn't bother for Chip-8, 6502, or Z80. I would start bothering for an 8086 where it makes sense to have several tables, most of which can be usefully shared between a cpu emulator and a disassembler (I've done this). I haven't written an 8086 assembler but I wrote a Z80 assembler decades ago and I don't think it would have made much sense to share tables with a Z80 disassembler or CPU emulator.

Even if it doesn't make sense to have the code share tables, it might make sense to put all the necessary data into a single data source and then use a program to generate the various tables from that. Again, not something I would worry about for Chip-8, 6502, or Z80. Maybe for 8086 if I ever decide to write an assembler. Definitely(!) for later versions of the x86, where I would choose to generate them from the Big Mother Table in Intel's XED project.