From 42145a5b8a0f7fb5295abede1ce7a63274ef2e03 Mon Sep 17 00:00:00 2001
From: Thomas Harte <thomas.harte@gmail.com>
Date: Mon, 1 Nov 2021 14:18:58 -0700
Subject: [PATCH] Delay bitplane installation until end of slot.

---
 Machines/Amiga/Chipset.cpp | 39 +++++++++++++++++++++++---------------
 Machines/Amiga/Chipset.hpp |  3 ++-
 2 files changed, 26 insertions(+), 16 deletions(-)

diff --git a/Machines/Amiga/Chipset.cpp b/Machines/Amiga/Chipset.cpp
index 7bd634f2d..4b8e1dde9 100644
--- a/Machines/Amiga/Chipset.cpp
+++ b/Machines/Amiga/Chipset.cpp
@@ -272,16 +272,28 @@ template <int cycle> void Chipset::output() {
 			if(cycle == line_length_ - 1) {
 				flush_output();
 			}
-
-			// Update all active pixel shifters.
-			bitplane_pixels_.shift(is_high_res_);
-			sprite_shifters_[0].shift();
-			sprite_shifters_[1].shift();
-			sprite_shifters_[2].shift();
-			sprite_shifters_[3].shift();
 		}
 	}
 
+	// Update all active pixel shifters.
+	bitplane_pixels_.shift(is_high_res_);
+	sprite_shifters_[0].shift();
+	sprite_shifters_[1].shift();
+	sprite_shifters_[2].shift();
+	sprite_shifters_[3].shift();
+
+	// Reload if anything is pending.
+	if(has_next_bitplanes_) {
+		has_next_bitplanes_ = false;
+		bitplane_pixels_.set(
+			previous_bitplanes_,
+			next_bitplanes_,
+			odd_delay_,
+			even_delay_
+		);
+		previous_bitplanes_ = next_bitplanes_;
+	}
+
 #undef LINK
 }
 
@@ -510,14 +522,11 @@ template <bool stop_on_cpu> Chipset::Changes Chipset::run(HalfCycles length) {
 }
 
 void Chipset::post_bitplanes(const BitplaneData &data) {
-	// Expand this
-	bitplane_pixels_.set(
-		previous_bitplanes_,
-		data,
-		odd_delay_,
-		even_delay_
-	);
-	previous_bitplanes_ = data;
+	// Posted bitplanes should be received at the end of the
+	// current memory slot. So put them aside for now, and
+	// deal with them momentarily.
+	has_next_bitplanes_ = true;
+	next_bitplanes_ = data;
 }
 
 void Chipset::BitplaneShifter::set(const BitplaneData &previous, const BitplaneData &next, int odd_delay, int even_delay) {
diff --git a/Machines/Amiga/Chipset.hpp b/Machines/Amiga/Chipset.hpp
index a9f33a9dc..399157cb6 100644
--- a/Machines/Amiga/Chipset.hpp
+++ b/Machines/Amiga/Chipset.hpp
@@ -245,7 +245,8 @@ class Chipset: private ClockingHint::Observer {
 		} bitplanes_;
 
 		void post_bitplanes(const BitplaneData &data);
-		BitplaneData previous_bitplanes_;
+		BitplaneData next_bitplanes_, previous_bitplanes_;
+		bool has_next_bitplanes_ = false;
 
 		class BitplaneShifter {
 			public: