Commits

spencercw committed fb788c0

#50 Fix graphical glitches caused by the line counter being incremented at the wrong time.

The line counter needs to be incremented before the line is drawn, rather than at the beginning of the HBLANK period.

Comments (0)

Files changed (1)

gb_emulator/src/gb_video.cpp

 		return LINE_CYCLES;
 	}
 
+	// Increment the line counter at the beginning of each line
+	if ((gb_.mem_->ioPorts[STAT] & 0x03) == 0x00 ||
+	    (gb_.mem_->ioPorts[STAT] & 0x03) == 0x01)
+	{
+		gb_.mem_->ioPorts[STAT] &= 0xfc;
+		gb_.mem_->ioPorts[LY] = (gb_.mem_->ioPorts[LY] + 1) % 154;
+	}
+
 	// Draw a line
 	if (gb_.mem_->ioPorts[LY] < VBLANK_START)
 	{
 		{
 		// HBLANK -> OAM read
 		case 0x00:
-			gb_.mem_->ioPorts[STAT] &= 0xfc;
 			gb_.mem_->ioPorts[STAT] |= 0x02;
 			if (gb_.mem_->ioPorts[STAT] & LCD_STAT_OAM_READ_INTR)
 				gb_.mem_->ioPorts[IF] |= LCD_STAT_INTR;
 	// Reset the priority map
 	memset(priorityMap, 0, sizeof(priorityMap));
 
-	// Increment the line counter
-	gb_.mem_->ioPorts[LY] = (gb_.mem_->ioPorts[LY] + 1) % 154;
-
 	// Check for HBLANK or VBLANK
 	int cycles;
 	if (gb_.mem_->ioPorts[LY] < VBLANK_START)
 			if (type == DRAW_BACKGROUND)
 			{
 				x -= gb_.mem_->ioPorts[SCX];
-				x = (x % 256 + 256) % 256;
+				x  = (x + 256) % 256;
 			}
 			else if (type == DRAW_WINDOW)
 			{