Permalink
Browse files

Run save/load state on the same goroutine as the CPU to prevent banks…

…witching while the state is being saved
  • Loading branch information...
1 parent 357e3e5 commit 98de8536bebc105494728e3b79bcd4404568f89e @scottferg committed Jan 1, 2013
Showing with 29 additions and 14 deletions.
  1. +3 −5 controller.go
  2. +26 −9 machine.go
View
@@ -166,7 +166,7 @@ func (c *Controller) Init() {
}
}
-func ReadInput(r chan [2]int) {
+func ReadInput(r chan [2]int, i chan int) {
for {
select {
case ev := <-sdl.Events:
@@ -215,8 +215,7 @@ func ReadInput(r chan [2]int) {
}
case sdl.K_l:
if e.Type == sdl.KEYDOWN {
- // Trigger reset interrupt
- LoadState()
+ i <- LoadState
}
case sdl.K_p:
if e.Type == sdl.KEYDOWN {
@@ -225,8 +224,7 @@ func ReadInput(r chan [2]int) {
}
case sdl.K_s:
if e.Type == sdl.KEYDOWN {
- // Trigger reset interrupt
- SaveState()
+ i <- SaveState
}
case sdl.K_o:
if e.Type == sdl.KEYDOWN {
View
@@ -33,14 +33,19 @@ var (
cpuprofile = flag.String("cprof", "", "write cpu profile to file")
)
+const (
+ SaveState = iota
+ LoadState
+)
+
func setResetVector() {
high, _ := Ram.Read(0xFFFD)
low, _ := Ram.Read(0xFFFC)
ProgramCounter = (uint16(high) << 8) + uint16(low)
}
-func LoadState() {
+func LoadGameState() {
fmt.Println("Loading state")
state, err := ioutil.ReadFile(saveStateFile)
@@ -94,7 +99,7 @@ func LoadState() {
}
}
-func SaveState() {
+func SaveGameState() {
fmt.Println("Saving state")
buf := new(bytes.Buffer)
@@ -231,21 +236,33 @@ func main() {
return
}
+ interrupt := make(chan int)
+
// Main runloop, in a separate goroutine so that
// the video rendering can happen on this one
- go func() {
+ go func(c <-chan int) {
for {
- cycles := cpu.Step()
-
- for i := 0; i < 3*cycles; i++ {
- ppu.Step()
+ select {
+ case s := <-c:
+ switch s {
+ case LoadState:
+ LoadGameState()
+ case SaveState:
+ SaveGameState()
+ }
+ default:
+ cycles := cpu.Step()
+
+ for i := 0; i < 3*cycles; i++ {
+ ppu.Step()
+ }
}
}
- }()
+ }(interrupt)
r := video.Init(v, gamename)
- go ReadInput(r)
+ go ReadInput(r, interrupt)
// This needs to happen on the main thread for OSX
runtime.LockOSThread()

0 comments on commit 98de853

Please sign in to comment.