Skip to content

Commit

Permalink
Fix ldk instruction timing bug.
Browse files Browse the repository at this point in the history
  • Loading branch information
nyancient committed Jan 1, 2022
1 parent 27918a7 commit 2008c7d
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ a [Korone](https://twitter.com/KoroneNoises/)-based sound chip.
## Usage
1. Download the JAR from the [latest release](https://github.com/foxolotl/koro8/releases/latest).
2. Get some [roms](https://github.com/loktar00/chip8/tree/master/roms) to run.
3. Run koro8 with the path to one of your downloaded roms as argument: `java -jar koro8-0.1-min.jar /path/to/some/rom.ch8`
3. Run koro8 with the path to one of your downloaded roms as argument: `java -jar koro8-0.1.1-min.jar /path/to/some/rom.ch8`
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ plugins {
}

group = "com.github.foxolotl"
version = "0.1"
version = "0.1.1"

repositories {
mavenCentral()
Expand Down
21 changes: 17 additions & 4 deletions src/main/kotlin/com/github/foxolotl/koro8/CPU.kt
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class CPU(
private val cycleTimeNanos: Long = 1000000000L / cyclesPerSecond
private val cycleSleepMillis: Long = cycleTimeNanos / 1000000L
private var cycles: Long = 0
private var nextCycleDeadline: Long = 0

private val heap: Heap = Heap(HEAP_SIZE)
private val stack: Stack = Stack(STACK_SIZE)
Expand Down Expand Up @@ -74,7 +75,12 @@ class CPU(
display.clear()
}

tailrec fun run(ticks: Long = Long.MAX_VALUE, nextCycleDeadline: Long = System.nanoTime()) {
fun run(ticks: Long = Long.MAX_VALUE) {
nextCycleDeadline = System.nanoTime()
execute(ticks)
}

private tailrec fun execute(ticks: Long) {
if (ticks == 0L) {
return
}
Expand All @@ -84,10 +90,11 @@ class CPU(
val now = System.nanoTime()
if (now >= nextCycleDeadline) {
step()
run(ticks - 1, nextCycleDeadline + cycleTimeNanos)
nextCycleDeadline += cycleTimeNanos
execute(ticks - 1)
} else {
Thread.sleep(cycleSleepMillis)
run(ticks, nextCycleDeadline)
execute(ticks)
}
}

Expand Down Expand Up @@ -152,7 +159,13 @@ class CPU(
}
}

private inline fun ldk(reg: Register) = ld(reg, keyboard.waitKey())
private inline fun ldk(reg: Register) {
val t0 = System.nanoTime()
val key = keyboard.waitKey()
val t1 = System.nanoTime()
nextCycleDeadline += (t1 - t0)
ld(reg, key)
}
private inline fun stdt(reg: Register) = ld(reg, regs.DT)
private inline fun ld(reg1: Register, reg2: Register) = ld(reg1, regs.V[reg2])
private inline fun sne(reg1: Register, reg2: Register) = sne(reg1, regs.V[reg2])
Expand Down

0 comments on commit 2008c7d

Please sign in to comment.