71 lines
2.3 KiB
C++
71 lines
2.3 KiB
C++
#include "../include/instruction_handler.h"
|
|
#include "../include/logger.h"
|
|
|
|
InstructionHandler::InstructionHandler() {
|
|
this->handlers[0x0000] = handle0000;
|
|
this->handlers[0x1000] = handle1000;
|
|
}
|
|
|
|
/**
|
|
* Attempts to handle the Chip8 instruction by the given instruction number.
|
|
* If the handler doesn't exist for the instruction, an error is logged, but the program resumes.
|
|
*
|
|
* @param instructionNumber the 16-bit value to determine the instruction
|
|
* @param chip8 the Chip8 instance
|
|
* @param instruction the Instruction instance
|
|
*/
|
|
void InstructionHandler::handleInstruction(unsigned short instructionNumber, Chip8& chip8, Instruction instruction) {
|
|
if (!this->handlers.contains(instructionNumber)) {
|
|
Logger::error("Unregistered instruction", instructionNumber);
|
|
return;
|
|
}
|
|
|
|
this->handlers[instructionNumber](chip8, instruction);
|
|
}
|
|
|
|
/**
|
|
* Handles the 0x0000 Chip-8 instruction.
|
|
* This handles 2 other instructions:
|
|
* - 0x00E0 which is used to clear the screen.
|
|
* - 0x00EE which is used to return from a subroutine.
|
|
*
|
|
* In older interpreters, 0x0NNN was also used to jump to a machine code at NNN, but this shouldn't be implemented.
|
|
*
|
|
* @param chip8 The Chip8 instance
|
|
* @param instruction The Instruction instance
|
|
*/
|
|
void InstructionHandler::handle0000(Chip8& chip8, Instruction instruction) {
|
|
switch (instruction.kk()) {
|
|
case 0x00E0:
|
|
chip8.getDisplay().clear();
|
|
break;
|
|
case 0x00EE:
|
|
chip8.setProgramCounter(chip8.popFromStack());
|
|
break;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Handles the 0x1NNN Chip8 instruction which is used to jump to location NNN.
|
|
* This will set the program counter to the NNN value.
|
|
*
|
|
* @param chip8 The Chip8 instance
|
|
* @param instruction The Instruction instance
|
|
*/
|
|
void InstructionHandler::handle1000(Chip8& chip8, Instruction instruction) {
|
|
chip8.setProgramCounter(instruction.nnn());
|
|
}
|
|
|
|
/**
|
|
* Handles the 0x2NNN Chip8 instruction which is used to call a subroutine at NNN.
|
|
* This will increments the stack pointer and puts PC on top of the stack.
|
|
*
|
|
* @param chip8 The Chip8 instance
|
|
* @param instruction The Instruction instance
|
|
*/
|
|
void InstructionHandler::handle2000(Chip8& chip8, Instruction instruction) {
|
|
chip8.pushToStack(chip8.getProgramCounter());
|
|
chip8.setProgramCounter(instruction.nnn());
|
|
}
|
|
|