Skip to content

Commit

Permalink
Fixed #13: Properly buffer screen transitions to prevent memory corru…
Browse files Browse the repository at this point in the history
…ption
  • Loading branch information
agg23 committed Feb 25, 2021
1 parent 92d9db6 commit bcdf874
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 23 deletions.
46 changes: 27 additions & 19 deletions main.mfk
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,15 @@ void main() {

while(true) {
// Wait for NMI to complete rendering frame
while (new_frame) {}

sprite_tick()
input_and_screen_tick()
clear_remaining_oam()

while (new_frame && not(buffer_screen_draw)) {}

if (buffer_screen_draw) {
screen_draw_tick()
} else {
sprite_tick()
input_and_screen_tick()
clear_remaining_oam()
}
// wait_for_sprite0_clear()

new_frame = true
Expand All @@ -68,17 +71,6 @@ void main() {
}

void nmi() {
if (buffer_screen_draw) {
screen_transfer_tick()
nmi_always_run()
return
}

if (not(drawing_enabled)) {
nmi_always_run()
return
}

if in_nmi != 0 {
// Overran NMI
nmi_fail = 1
Expand All @@ -89,15 +81,31 @@ void nmi() {

in_nmi = 1

nmi_work()

in_nmi = 0
}

inline void nmi_work() {
if (buffer_screen_blank) {
screen_transfer_tick()
nmi_always_run()
new_frame = false
return
}

if (not(drawing_enabled)) {
nmi_always_run()
return
}

if (new_frame) {
nmi_frame()

new_frame = false
}

nmi_always_run()

in_nmi = 0
}

void nmi_frame() {
Expand Down
15 changes: 11 additions & 4 deletions ui/screen.mfk
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ enum Screen {
}

bool buffer_screen_draw = false
bool buffer_screen_blank = false
Screen current_screen

bool screen_tick() {
Expand Down Expand Up @@ -47,7 +48,7 @@ void draw_screen() {

void set_screen_forcibly(Screen new_screen) {
current_screen = new_screen
buffer_screen_draw = true
buffer_screen_blank = true
}

void set_screen(Screen new_screen) {
Expand All @@ -56,18 +57,24 @@ void set_screen(Screen new_screen) {
}

current_screen = new_screen
buffer_screen_draw = true
buffer_screen_blank = true
}

void screen_transfer_tick() {
// Wait for NMI to disable rendering and NMIs
// Draw new screen
drawing_enabled = false
buffer_screen_draw = false
buffer_screen_blank = false
read_ppu_status()
ppu_ctrl = standard_ppu_ctrl
ppu_mask = 0

buffer_screen_draw = true
}

void screen_draw_tick() {
// NMI has cleared screen, now write it
// Draw new screen
buffer_screen_draw = false
ppu_wait_vblank()

clear_buffer()
Expand Down

0 comments on commit bcdf874

Please sign in to comment.