[Scummvm-git-logs] scummvm master -> 7d5b2522431d83602f35c423ad4f84b63728a3c5

sev- noreply at scummvm.org
Thu Jun 19 21:57:03 UTC 2025


This automated email contains information about 131 new commits which have been
pushed to the 'scummvm' repo located at https://api.github.com/repos/scummvm/scummvm .

Summary:
68ac9870fd COMMON: Minor code comment clarification
701b9ccfb1 ZVISION: Groundwork for widescreen mod.
faad317b3f ZVISION: Replace local blitting code with standard Osystem library functions.
185a1f7878 COMMON: Add detail to usage & functionality comment.
fda0e8ac89 GRAPHICS: Add efficient dirty rectangle PixelFormat conversion to Screen::update().
50f489bcec GRAPHICS: Additional documentation & comments.
ac0a7884de ZVISION: Adapt RenderManager structure for experimental widescreen support.
1db616d58d ZVISION: Improve scroller code.
422b72dc78 ZVISION: Amend erroneous ZGI working window height.
dcbb155f8b ZVISION: Menu code rework to minimise code duplication & support widescreen.
c61cefee89 ZVISION: Replace simpleBlit with transBlit.
1255ef3288 ZVISION: Improve widescreen descriptive text in options.
e442d4fab5 ZVISION: Code cleanup
6cd9acf642 ZVISION: Fix bug in renderSceneToScreen() that delays inventory item display.
ea13219757 ZVISION: Improve menu scrolling behaviour.
bddf8495d1 ZVISION: Rename MenuHandler to MenuManager for consistency.
23871b541b ZVISION: Alter puzzle debug message level.
9c0d5a8747 ZVISION: Unify video playback rendering & scene rendering.
d4ac1784f8 ZVISION: Fix failure of fullscreen video to refresh.
22fba73b8e ZVISION: Remove redundant copyToScreen() function.
26a30438b8 COMMON: Add center() & origin() utility functions to Rect.
961a6e6aed ZVISION: Refactor to improve renderManager encapsulation.
a7aedfedfe COMMON: Make center() const.
76fa0a120e ZVISION: Add isAvailable() to midi manager.
6850ebce0a ZVISION: Simplification of subtitle rendering system.
a5101e0fa1 ZVISION: Create new common directory for general purpose functions.
4746de599d ZVISION: Complete rework of subtitle & message system.
c83aa95a8d ZVISION: Add support for DVD edition in widescreen & original resolution.
fd68aaaf66 ZVISION: Fix menu hotspot bug in Nemesis.
4f80c8c904 ZVISION: Code cleanup.
c47e29b1a9 ZVISION: Fix sarcophagus video playback in Nemesis.
3a4de15fde ZVISION: Code cleanup, additional comments, debugging messages.
2de70968aa ZVISION: Restructure render table generation code to improve efficiency.
e003159d26 ZVISION: Add workaround for bug in MT-32 emulation.
1fa6ebd8d3 ZVISION: Add VolumeManager class with various volume scaling profiles.
292378a7c0 ZVISION: Sound system rework.
99f72d515e ZVISION: Modified ActionMusic::execute() behaviour to eliminate pan_track bug.
bffc3012f9 ZVISION: Code cleanup.  Additional code comments.
ea7e8180cb ZVISION: Fix bug in MusicNode fade/crossfade effect.
65f409bc99 ZVISION: Added capacity to read auxiliary scripts for extra directional audio.
9d87cfc597 ZVISION: Alter ~PanTrackNode() to restore audio balance to centre.
c7ec0b989c ZVISION: Added functionality to PanTrackNode() to support auxiliary scripts.
ed0f25b7b9 ZVISION: Add variable directionality to PanTrackNode & VolumeManager.
5f1b1591be ZVISION: First attempt at high quality panorama graphics filter.
e4bb107b73 ZVISION: Add single-pass bilinear panorama filter.
1e66fca9dc ZVISION: Add ability to alter panorama quality from in-game and launcher options menus.
23c1c8e793 ZVISION: Improve bilinear filter.
30a190c097 ZVISION: Replace bilinear filter with simpler code.
72862da379 ZVISION: Refine bilinear filter code; considerable speed improvement.
7b74779090 ZVISION: Refine render table generation code; considerable speed improvement.
9e887ac6e2 ZVISION: Improve panorama mutation code.
1b6891c338 ZVISION: Clean up framerate limiter code a bit.
536737ae9f ZVISION: Overhaul of render table generation code.
7f94d1186d ZVISION: Adapted render manager to use standard Gsystem frame limiter.
860e56aa24 ZVISION: Improve efficiency of panorama mutation code.  Increases FPS.
52f61a4b0e ZVISION: Ensure Nemesis saved games don't override current panorama settings.
346474f1e8 ZVISION: Code cleanup.
85140f3994 GRAPHICS: Improve precision of FrameLimiter when operating in non-Vsync mode.
b32eba27af ZVISION: Fix bug in script parser.
b4363314b3 ZVISION: Fixed bug that briefly showed previous scene after a streaming video right before a location change.
dded57736b ZVISION: Fix bug in PanTrackNode.
52f5defa1b ZVISION: Amended previous bug fix that prevented scene redraw before changing location after video;
e068e51d22 ZVISION: Created AutomaticSubtitle class.
e826d7571b ZVISION: Fix bug that caused graphical corruption of streaming video subtitles.
32cc542bb0 ZVISION: Clearer debug message for ActionMusic().
7d46f3f29e ZVISION: Fix stuttering audio bug in ZGI room tp1e (invisible bridge guy)
e444f4b415 ZVISION: Workaround added for ZGI script bug.
8daa9f639d ZVISION: Fix bug that caused some sounds not to play upon restoring a game in certain locations.
35002be5ab ZVISION: Amend 3D sound option behaviour.
f9565f0b00 ZVISION: Lowered ZGI inventory & spell scrollbar periods.
6a135edfef GRAPHICS: Improve FrameLimiter initialization code.
3e392fd0d1 ZVISION: Fix framerate limiter functionality in non-Vsync mode.
f7f45f55e9 ZVISION: Disabled vestigial development testing code in RenderTable.
7d87521368 ZVISION: Restore functionality of "Main Menu" button in ZGI death screen.
2afa00137e ZVISION: Code cleanup to meet github workflow requirements.
b582171e05 GRAPHICS: Make FrameLimiter member variable names compliant with coding convention.
45c0e3ffe6 ZVISION: Code formatting & convention compliance.
8c47b04e54 GRAPHICS: Code formatting compliance.
f784996e93 COMMON: Code formatting compliance.
430e4f9e22 ZVISION: Code formatting & convention compliance.
f35303bd19 COMMON: Code formatting & convention adjustment to minimise diff bloat.
149089e01e GRAPHICS: Code formatting & convention adjustment to minimise diff bloat.
ef1fced74c ZVISION: Code formatting & convention adjustment to minimise diff bloat.
f71aeba972 ZVISION: Code formatting & convention compliance:
3ebd8c2b7d ZVISION: Add fix for script bug in room tl9e.
e1bdf680b2 ZVISION: Add usage documentation for FocusList and Scroller.
eff73d2b29 ZVISION: Convert FocusList to subclass of Common::Array
518cd2982d ZVISION: Append self to credits.pl
31297741b4 ZVISION: Simple formatting fixes for code review.
b475d9ed65 ZVISION: Corrected non-member variable names to meet coding convention.
822474fad4 ZVISION: Removed spurious semicolons for code review.
0aa33df124 GRAPHICS: Code formatting compliance.
5d8be17446 ZVISION: Code formatting compliance.
2cf3ddd0bc ZVISION: Bugfix & const reference suggestions from code review.
e8765be27f ZVISION: Removed unfinished rework of blitSurfaceToSurface() into local side branch.
303b7d5713 ZVISION: Code formatting compliance.
59ecad7841 ZVISION: Code formatting compliance & obsolete code removal.
36f443e77c ZVISION: Code formatting compliance.
08e9f0c533 ZVISION: Code formatting compliance.
c8dca7190b GRAPHICS: Code formatting compliance.
e0012a0651 ZVISION: Code formatting compliance.
ac6df2120f ZVISION: Code formatting compliance.
f3eb569358 GRAPHICS: Remove automatic pixelformat conversion from Screen; unnecessary.
aa2b080ba5 ZVISION: Amend RenderManager to use unmodified form of Graphics::Screen.
106b4fc0dd ZVISION: Fix segfault in hi-res video playback arising from previous commit.
a0a77c552e ZVISION: Unnecessary member variables made local to member functions.
92e5216162 ZVISION: Volume profile generator functions converted to integer maths for efficiency.
3ab20d64dc ZVISION: Pass arguments by reference instead of value.
ce745721ff ZVISION: Cleaner MT-32 detection.
dd73308c6a ZVISION: Remove obsolete code.
388d40b701 ZVISION: Code formatting compliance.
36451ff3e4 ZVISION: Fix Nemesis script bug for Monastery rumble sound effect.
0872c53a27 ZVISION: Code formatting compliance.
094eb68418 ZVISION: Code formatting compliance; all #include statements sorted.
8c196ada85 ZVISION: Code formatting compliance; remove spurious semicolons.
d123bba40c ZVISION: Code formatting compliance.
d30bab3146 ZVISION: Make appropriate methods const.
6a4c7b2631 GRAPHICS: Code formatting compliance, convert indents to tabs.
9873a40562 ZVISION: Code cleanup, reduced unnecessary indentation.
39fa339f93 ZVISION: Code formatting compliance, lower case argument names.
09cbad5471 ZVISION: Code formatting compliance, lower case member names.
85e6e05617 ZVISION: Code formatting compliance; alphabetical modules file.
902dfc9cab ZVISION: Add parse error protection to all sscanf operations.
9a7d11048c GRAPHICS: Frame limiter member initialisation moved to definition where possible.
9b80184e12 ZVISION: Reduce variable scope & make const where appropriate in RenderTable methods.
8e3434513f ZVISION: Code formatting compliance.
b3654574f4 ZVISION: Simplify ~SubtitleManager()
d0bf337d73 ZVISION: Return by reference for getMenuArea(), getWorkingArea(), getTextOffset()
26230b3147 ZVISION: Overload blitSurfaceToSurface() methods to tidy up ugly function calls.
19cc9c7f7f ZVISION: Comment out disused function.
7d5b252243 ZVISION: Respect confirm_exit option.


Commit: 68ac9870fd452aff04d12c0a4b4b86416d4a3a9d
    https://github.com/scummvm/scummvm/commit/68ac9870fd452aff04d12c0a4b4b86416d4a3a9d
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:53+02:00

Commit Message:
COMMON: Minor code comment clarification

Changed paths:
    common/rect.h


diff --git a/common/rect.h b/common/rect.h
index f5ef97b7286..d001ec69df7 100644
--- a/common/rect.h
+++ b/common/rect.h
@@ -296,7 +296,7 @@ struct Rect {
 	}
 
 	/**
-	 * Clip this rectangle with another rectangle @p r.
+	 * Clip this rectangle to within the bounds of another rectangle @p r.
 	 */
 	void clip(const Rect &r) {
 		assert(isValidRect());


Commit: 701b9ccfb1907b274e7dca79e56781da217829f0
    https://github.com/scummvm/scummvm/commit/701b9ccfb1907b274e7dca79e56781da217829f0
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:53+02:00

Commit Message:
ZVISION: Groundwork for widescreen mod.
Add launcher option.  Refine in-game menu handling code.
Add comments to clarify existing code structure.

Changed paths:
    engines/zvision/detection.h
    engines/zvision/detection_tables.h
    engines/zvision/metaengine.cpp
    engines/zvision/scripting/menu.cpp
    engines/zvision/scripting/menu.h
    engines/zvision/zvision.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/detection.h b/engines/zvision/detection.h
index fcaf5850002..43d1bde63e8 100644
--- a/engines/zvision/detection.h
+++ b/engines/zvision/detection.h
@@ -44,6 +44,7 @@ struct ZVisionGameDescription {
 #define GAMEOPTION_ENABLE_VENUS               GUIO_GAMEOPTIONS3
 #define GAMEOPTION_DISABLE_ANIM_WHILE_TURNING GUIO_GAMEOPTIONS4
 #define GAMEOPTION_USE_HIRES_MPEG_MOVIES      GUIO_GAMEOPTIONS5
+#define GAMEOPTION_ENABLE_WIDESCREEN          GUIO_GAMEOPTIONS6
 
 } // End of namespace ZVision
 
diff --git a/engines/zvision/detection_tables.h b/engines/zvision/detection_tables.h
index 26556b6d311..43e29337855 100644
--- a/engines/zvision/detection_tables.h
+++ b/engines/zvision/detection_tables.h
@@ -53,7 +53,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::EN_ANY,
 			Common::kPlatformDOS,
 			ADGF_NO_FLAGS,
-			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING)
+			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
 		},
 		GID_NEMESIS
 	},
@@ -68,7 +68,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::FR_FRA,
 			Common::kPlatformDOS,
 			ADGF_NO_FLAGS,
-			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING)
+			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
 		},
 		GID_NEMESIS
 	},
@@ -83,7 +83,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::DE_DEU,
 			Common::kPlatformDOS,
 			ADGF_NO_FLAGS,
-			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING)
+			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
 		},
 		GID_NEMESIS
 	},
@@ -98,7 +98,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::IT_ITA,
 			Common::kPlatformDOS,
 			ADGF_NO_FLAGS,
-			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING)
+			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
 		},
 		GID_NEMESIS
 	},
@@ -116,7 +116,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::KO_KOR,
 			Common::kPlatformDOS,
 			ADGF_NO_FLAGS,
-			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING)
+			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
 		},
 		GID_NEMESIS
 	},
@@ -135,7 +135,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::EN_ANY,
 			Common::kPlatformMacintosh,
 			ADGF_UNSUPPORTED,
-			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING)
+			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
 		},
 		GID_NEMESIS
 	},
@@ -149,7 +149,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::EN_ANY,
 			Common::kPlatformWindows,
 			ADGF_DEMO,
-			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING)
+			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
 		},
 		GID_NEMESIS
 	},
@@ -163,7 +163,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::EN_ANY,
 			Common::kPlatformWindows,
 			ADGF_NO_FLAGS,
-			GUIO3(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING)
+			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
 		},
 		GID_GRANDINQUISITOR
 	},
@@ -177,7 +177,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::FR_FRA,
 			Common::kPlatformWindows,
 			ADGF_NO_FLAGS,
-			GUIO3(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING)
+			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
 		},
 		GID_GRANDINQUISITOR
 	},
@@ -191,7 +191,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::DE_DEU,
 			Common::kPlatformWindows,
 			ADGF_NO_FLAGS,
-			GUIO3(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING)
+			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
 		},
 		GID_GRANDINQUISITOR
 	},
@@ -205,7 +205,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::ES_ESP,
 			Common::kPlatformWindows,
 			ADGF_NO_FLAGS,
-			GUIO3(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING)
+			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
 		},
 		GID_GRANDINQUISITOR
 	},
@@ -220,7 +220,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::EN_ANY,
 			Common::kPlatformMacintosh,
 			ADGF_NO_FLAGS,
-			GUIO3(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING)
+			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
 		},
 		GID_GRANDINQUISITOR
 	},
@@ -235,9 +235,9 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::kPlatformWindows,
 			ADGF_DVD,
 #if defined(USE_MPEG2) && defined(USE_A52)
-			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_USE_HIRES_MPEG_MOVIES)
+			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_USE_HIRES_MPEG_MOVIES, GAMEOPTION_ENABLE_WIDESCREEN)
 #else
-			GUIO3(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING)
+			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
 #endif
 		},
 		GID_GRANDINQUISITOR
@@ -252,7 +252,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::EN_ANY,
 			Common::kPlatformWindows,
 			ADGF_DEMO,
-			GUIO3(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING)
+			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
 		},
 		GID_GRANDINQUISITOR
 	},
diff --git a/engines/zvision/metaengine.cpp b/engines/zvision/metaengine.cpp
index 92167b19b43..176213b5ed8 100644
--- a/engines/zvision/metaengine.cpp
+++ b/engines/zvision/metaengine.cpp
@@ -100,6 +100,19 @@ static const ADExtraGuiOptionsMap optionsList[] = {
 		}
 	},
 
+	{
+		GAMEOPTION_ENABLE_WIDESCREEN,
+		{
+			_s("Enable widescreen support"),
+			_s("Enlarge panoramic playfield & alter game resolution to better utilise wide aspect ratio displays"),
+			"widescreen",
+			true,
+			0,
+			0
+		}
+	},
+
+
 	AD_EXTRA_GUI_OPTIONS_TERMINATOR
 };
 
diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index 7ed920fc9af..61fe7b3dcb5 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -358,12 +358,12 @@ void MenuZGI::process(uint32 deltatime) {
 		if (menuBarFlag & kMenubarItems)
 			if (!scrolled[kMenuItem]) {
 				redraw = true;
-				float scrl = 600.0 * (deltatime / 1000.0);
+				float dScrl = 600.0 * (deltatime / 1000.0);
 
-				if (scrl == 0)
-					scrl = 1.0;
+				if (dScrl == 0)
+					dScrl = 1.0;
 
-				scrollPos[kMenuItem] += (int)scrl;
+				scrollPos[kMenuItem] += (int)dScrl;
 
 				if (scrollPos[kMenuItem] >= 0) {
 					scrolled[kMenuItem] = true;
@@ -427,12 +427,12 @@ void MenuZGI::process(uint32 deltatime) {
 		if (menuBarFlag & kMenubarMagic)
 			if (!scrolled[kMenuMagic]) {
 				redraw = true;
-				float scrl = 600.0 * (deltatime / 1000.0);
+				float dScrl = 600.0 * (deltatime / 1000.0);
 
-				if (scrl == 0)
-					scrl = 1.0;
+				if (dScrl == 0)
+					dScrl = 1.0;
 
-				scrollPos[kMenuMagic] += (int)scrl;
+				scrollPos[kMenuMagic] += (int)dScrl;
 
 				if (scrollPos[kMenuMagic] >= 600) {
 					scrolled[kMenuMagic] = true;
@@ -492,12 +492,12 @@ void MenuZGI::process(uint32 deltatime) {
 	case kMenuMain:
 		if (!scrolled[kMenuMain]) {
 			redraw = true;
-			float scrl = 32.0 * 2.0 * (deltatime / 1000.0);
+			float dScrl = 32.0 * 2.0 * (deltatime / 1000.0);
 
-			if (scrl == 0)
-				scrl = 1.0;
+			if (dScrl == 0)
+				dScrl = 1.0;
 
-			scrollPos[kMenuMain] += (int)scrl;
+			scrollPos[kMenuMain] += (int)dScrl;
 
 			if (scrollPos[kMenuMain] >= 0) {
 				scrolled[kMenuMain] = true;
@@ -505,7 +505,7 @@ void MenuZGI::process(uint32 deltatime) {
 			}
 		}
 		if (redraw) {
-			_engine->getRenderManager()->blitSurfaceToMenu(menuBack[kMenuMain][0], 30, scrollPos[kMenuMain]);
+			_engine->getRenderManager()->blitSurfaceToMenu(menuBack[kMenuMain][0], 30, scrollPos[kMenuMain]); //TODO - experiment with adding colorkey here for overlaying playfield in widescreen.
 
 			if (menuBarFlag & kMenubarExit) {
 				if (mouseOnItem == kMainMenuExit)
@@ -560,6 +560,7 @@ MenuNemesis::MenuNemesis(ZVision *engine) :
 	redraw = false;
 	delay = 0;
 
+  //Buffer button images
 	char buf[24];
 	for (int i = 0; i < 4; i++)
 		for (int j = 0; j < 6; j++) {
@@ -567,6 +568,7 @@ MenuNemesis::MenuNemesis(ZVision *engine) :
 			_engine->getRenderManager()->readImageToSurface(buf, but[i][j], false);
 		}
 
+  //Buffer menubar image
 	_engine->getRenderManager()->readImageToSurface("bar.tga", menuBar, false);
 
 	frm = 0;
@@ -580,38 +582,42 @@ MenuNemesis::~MenuNemesis() {
 	menuBar.free();
 }
 
-static const int16 buts[4][2] = { {120 , 64}, {144, 184}, {128, 328}, {120, 456} };
+//Widths & X positions of buttons; {Save, Restore, Prefs, Exit}
+static const int16 wxButs[4][2] = { {120 , 64}, {144, 184}, {128, 328}, {120, 456} };
+//Height of menu bar & buttons
+static const int16 hMenu[2] = {32,40};  //{graphics height, trigger boundary height}
+static const int16 wxMenu[2] = {512,64}; //Width, X position
 
 void MenuNemesis::onMouseUp(const Common::Point &Pos) {
-	if (Pos.y < 40) {
+	if (Pos.y < hMenu[1]) {
 		// Exit
 		if (menuBarFlag & kMenubarExit)
-			if (Common::Rect(buts[3][1],
+			if (Common::Rect(wxButs[3][1],
 			                 scrollPos,
-			                 buts[3][0] + buts[3][1],
-			                 scrollPos + 32).contains(Pos)) {
+			                 wxButs[3][0] + wxButs[3][1],
+			                 scrollPos + hMenu[0]).contains(Pos)) {
 				_engine->ifQuit();
 				frm = 5;
 				redraw = true;
 			}
 
-		// Settings
+		// Prefs
 		if (menuBarFlag & kMenubarSettings)
-			if (Common::Rect(buts[2][1],
+			if (Common::Rect(wxButs[2][1],
 			                 scrollPos,
-			                 buts[2][0] + buts[2][1],
-			                 scrollPos + 32).contains(Pos)) {
+			                 wxButs[2][0] + wxButs[2][1],
+			                 scrollPos + hMenu[0]).contains(Pos)) {
 				_engine->getScriptManager()->changeLocation('g', 'j', 'p', 'e', 0);
 				frm = 5;
 				redraw = true;
 			}
 
-		// Load
+		// Restore
 		if (menuBarFlag & kMenubarRestore)
-			if (Common::Rect(buts[1][1],
+			if (Common::Rect(wxButs[1][1],
 			                 scrollPos,
-			                 buts[1][0] + buts[1][1],
-			                 scrollPos + 32).contains(Pos)) {
+			                 wxButs[1][0] + wxButs[1][1],
+			                 scrollPos + hMenu[0]).contains(Pos)) {
 				_engine->getScriptManager()->changeLocation('g', 'j', 'r', 'e', 0);
 				frm = 5;
 				redraw = true;
@@ -619,10 +625,10 @@ void MenuNemesis::onMouseUp(const Common::Point &Pos) {
 
 		// Save
 		if (menuBarFlag & kMenubarSave)
-			if (Common::Rect(buts[0][1],
+			if (Common::Rect(wxButs[0][1],
 			                 scrollPos,
-			                 buts[0][0] + buts[0][1],
-			                 scrollPos + 32).contains(Pos)) {
+			                 wxButs[0][0] + wxButs[0][1],
+			                 scrollPos + hMenu[0]).contains(Pos)) {
 				_engine->getScriptManager()->changeLocation('g', 'j', 's', 'e', 0);
 				frm = 5;
 				redraw = true;
@@ -631,7 +637,7 @@ void MenuNemesis::onMouseUp(const Common::Point &Pos) {
 }
 
 void MenuNemesis::onMouseMove(const Common::Point &Pos) {
-	if (Pos.y < 40) {
+	if (Pos.y < hMenu[1]) {
 
 		inMenu = true;
 
@@ -643,37 +649,37 @@ void MenuNemesis::onMouseMove(const Common::Point &Pos) {
 
 		// Exit
 		if (menuBarFlag & kMenubarExit)
-			if (Common::Rect(buts[3][1],
+			if (Common::Rect(wxButs[3][1],
 			                 scrollPos,
-			                 buts[3][0] + buts[3][1],
-			                 scrollPos + 32).contains(Pos)) {
+			                 wxButs[3][0] + wxButs[3][1],
+			                 scrollPos + hMenu[0]).contains(Pos)) {
 				mouseOnItem = kMainMenuExit;
 			}
 
-		// Settings
+		// Prefs
 		if (menuBarFlag & kMenubarSettings)
-			if (Common::Rect(buts[2][1],
+			if (Common::Rect(wxButs[2][1],
 			                 scrollPos,
-			                 buts[2][0] + buts[2][1],
-			                 scrollPos + 32).contains(Pos)) {
+			                 wxButs[2][0] + wxButs[2][1],
+			                 scrollPos + hMenu[0]).contains(Pos)) {
 				mouseOnItem = kMainMenuPrefs;
 			}
 
-		// Load
+		// Restore
 		if (menuBarFlag & kMenubarRestore)
-			if (Common::Rect(buts[1][1],
+			if (Common::Rect(wxButs[1][1],
 			                 scrollPos,
-			                 buts[1][0] + buts[1][1],
-			                 scrollPos + 32).contains(Pos)) {
+			                 wxButs[1][0] + wxButs[1][1],
+			                 scrollPos + hMenu[0]).contains(Pos)) {
 				mouseOnItem = kMainMenuLoad;
 			}
 
 		// Save
 		if (menuBarFlag & kMenubarSave)
-			if (Common::Rect(buts[0][1],
+			if (Common::Rect(wxButs[0][1],
 			                 scrollPos,
-			                 buts[0][0] + buts[0][1],
-			                 scrollPos + 32).contains(Pos)) {
+			                 wxButs[0][0] + wxButs[0][1],
+			                 scrollPos + hMenu[0]).contains(Pos)) {
 				mouseOnItem = kMainMenuSave;
 			}
 
@@ -693,12 +699,12 @@ void MenuNemesis::onMouseMove(const Common::Point &Pos) {
 void MenuNemesis::process(uint32 deltatime) {
 	if (inMenu) {
 		if (!scrolled) {
-			float scrl = 32.0 * 2.0 * (deltatime / 1000.0);
+			float dScrl = hMenu[0] * 2.0 * (deltatime / 1000.0);
 
-			if (scrl == 0)
-				scrl = 1.0;
+			if (dScrl == 0)
+				dScrl = 1.0;
 
-			scrollPos += (int)scrl;
+			scrollPos += (int)dScrl;
 			redraw = true;
 		}
 
@@ -717,44 +723,44 @@ void MenuNemesis::process(uint32 deltatime) {
 		}
 
 		if (redraw) {
-			_engine->getRenderManager()->blitSurfaceToMenu(menuBar, 64, scrollPos);
+			_engine->getRenderManager()->blitSurfaceToMenu(menuBar, wxMenu[1], scrollPos);
 
 			if (menuBarFlag & kMenubarExit)
 				if (mouseOnItem == kMainMenuExit)
-					_engine->getRenderManager()->blitSurfaceToMenu(but[3][frm], buts[3][1], scrollPos);
+					_engine->getRenderManager()->blitSurfaceToMenu(but[3][frm], wxButs[3][1], scrollPos);
 
 			if (menuBarFlag & kMenubarSettings)
 				if (mouseOnItem == kMainMenuPrefs)
-					_engine->getRenderManager()->blitSurfaceToMenu(but[2][frm], buts[2][1], scrollPos);
+					_engine->getRenderManager()->blitSurfaceToMenu(but[2][frm], wxButs[2][1], scrollPos);
 
 			if (menuBarFlag & kMenubarRestore)
 				if (mouseOnItem == kMainMenuLoad)
-					_engine->getRenderManager()->blitSurfaceToMenu(but[1][frm], buts[1][1], scrollPos);
+					_engine->getRenderManager()->blitSurfaceToMenu(but[1][frm], wxButs[1][1], scrollPos);
 
 			if (menuBarFlag & kMenubarSave)
 				if (mouseOnItem == kMainMenuSave)
-					_engine->getRenderManager()->blitSurfaceToMenu(but[0][frm], buts[0][1], scrollPos);
+					_engine->getRenderManager()->blitSurfaceToMenu(but[0][frm], wxButs[0][1], scrollPos);
 
 			redraw = false;
 		}
 	} else {
 		scrolled = false;
-		if (scrollPos > -32) {
-			float scrl = 32.0 * 2.0 * (deltatime / 1000.0);
+		if (scrollPos > -hMenu[0]) {
+			float dScrl = hMenu[0] * 2.0 * (deltatime / 1000.0);
 
-			if (scrl == 0)
-				scrl = 1.0;
+			if (dScrl == 0)
+				dScrl = 1.0;
 
-			Common::Rect cl(64, (int16)(32 + scrollPos - scrl), 64 + 512, 32 + scrollPos + 1);
+			Common::Rect cl(wxMenu[1], (int16)(hMenu[0] + scrollPos - dScrl), wxMenu[1] + wxMenu[0], hMenu[0] + scrollPos + 1);
 			_engine->getRenderManager()->clearMenuSurface(cl);
 
-			scrollPos -= (int)scrl;
+			scrollPos -= (int)dScrl;
 			redraw = true;
 		} else
-			scrollPos = -32;
+			scrollPos = -hMenu[0];
 
 		if (redraw) {
-			_engine->getRenderManager()->blitSurfaceToMenu(menuBar, 64, scrollPos);
+			_engine->getRenderManager()->blitSurfaceToMenu(menuBar, wxMenu[1], scrollPos);
 			redraw = false;
 		}
 	}
diff --git a/engines/zvision/scripting/menu.h b/engines/zvision/scripting/menu.h
index e979cb3d920..c70cabb4cdc 100644
--- a/engines/zvision/scripting/menu.h
+++ b/engines/zvision/scripting/menu.h
@@ -104,7 +104,7 @@ private:
 	int mouseOnItem;
 
 	bool scrolled;
-	int16 scrollPos;
+	int16 scrollPos;  //Offset of scrolling menu from its fully visible position
 
 	bool redraw;
 
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index 0dce53ff5ba..c30711594a9 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -101,6 +101,7 @@ ZVision::ZVision(OSystem *syst, const ZVisionGameDescription *gameDesc)
 	  _searchManager(nullptr),
 	  _textRenderer(nullptr),
 	  _doubleFPS(false),
+	  _widescreen(false),
 	  _audioId(0),
 	  _frameRenderDelay(2),
 	  _keyboardVelocity(0),
@@ -193,8 +194,12 @@ void ZVision::initialize() {
 		}
 	}
 
+	_widescreen = ConfMan.getBool("widescreen");
+
 	Graphics::ModeList modes;
 	modes.push_back(Graphics::Mode(WINDOW_WIDTH, WINDOW_HEIGHT));
+  if (_widescreen)
+	  modes.push_back(Graphics::Mode(WINDOW_WIDTH_WIDE, WINDOW_HEIGHT_WIDE));    
 #if defined(USE_MPEG2) && defined(USE_A52)
 	// For the DVD version of ZGI we can play high resolution videos
 	if (getGameId() == GID_GRANDINQUISITOR && (getFeatures() & ADGF_DVD))
@@ -329,9 +334,9 @@ Common::Error ZVision::run() {
 
 		// Render the backBuffer to the screen
 		_renderManager->prepareBackground();
-		_renderManager->renderMenuToScreen();
-		_renderManager->processSubs(deltaTime);
-		_renderManager->renderSceneToScreen();
+		_renderManager->renderMenuToScreen(); //TODO - disable in widescreen mode.
+		_renderManager->processSubs(deltaTime); //TODO - alter to blit subs to intermediate buffer, then handle this buffer in renderscenetoscreen()?
+		_renderManager->renderSceneToScreen();  //TODO - add code to composite menu surface into scene in this function in widescreen mode.
 
 		// Update the screen
 		if (canRender()) {
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index 186304b4225..5fa69747e8a 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -69,19 +69,27 @@ class Subtitle;
 class MidiManager;
 
 enum {
-	WINDOW_WIDTH = 640,
-	WINDOW_HEIGHT = 480,
+	WINDOW_WIDTH = 640,//640,
+	WINDOW_HEIGHT = 480,//480,
+	WINDOW_WIDTH_WIDE = 854,
+	WINDOW_HEIGHT_WIDE = 480,
 
 	HIRES_WINDOW_WIDTH = 800,
 	HIRES_WINDOW_HEIGHT = 600,
 
 	// Zork Nemesis working window sizes
-	ZNM_WORKING_WINDOW_WIDTH = 512,
-	ZNM_WORKING_WINDOW_HEIGHT = 320,
+	ZNM_WORKING_WINDOW_WIDTH = 512, //Original 512
+	ZNM_WORKING_WINDOW_HEIGHT = 320,  //Original 320
+	
+	ZNM_SUBTITLE_HEIGHT = 80, //Original 80
+	ZNM_MENU_HEIGHT = 40,  //Original 80
 
 	// ZGI working window sizes
-	ZGI_WORKING_WINDOW_WIDTH = 640,
-	ZGI_WORKING_WINDOW_HEIGHT = 344,
+	ZGI_WORKING_WINDOW_WIDTH = 640, //Original 640
+	ZGI_WORKING_WINDOW_HEIGHT = 320,  //Original 320
+	
+  ZGI_SUBTITLE_HEIGHT = 68, //Original 68
+	ZGI_MENU_HEIGHT = 34,  //Original 68
 
 	ROTATION_SCREEN_EDGE_OFFSET = 60,
 	MAX_ROTATION_SPEED = 400, // Pixels per second
@@ -160,6 +168,7 @@ private:
 	int16 _mouseVelocity;
 	int16 _keyboardVelocity;
 	bool _doubleFPS;
+	bool _widescreen;
 	bool _videoIsPlaying;
 
 	uint8 _cheatBuffer[KEYBUF_SIZE];


Commit: faad317b3fef4ec0e9e077bd6dfd7fbb0efc5e54
    https://github.com/scummvm/scummvm/commit/faad317b3fef4ec0e9e077bd6dfd7fbb0efc5e54
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:53+02:00

Commit Message:
ZVISION: Replace local blitting code with standard Osystem library functions.

Changed paths:
    engines/zvision/graphics/render_manager.cpp


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 545e3145b12..f97290c3aa1 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -36,6 +36,8 @@
 
 #include "image/tga.h"
 
+#include "graphics/blit.h"
+
 namespace ZVision {
 
 RenderManager::RenderManager(ZVision *engine, uint32 windowWidth, uint32 windowHeight, const Common::Rect &workingWindow, const Graphics::PixelFormat &pixelFormat, bool doubleFPS)
@@ -124,6 +126,8 @@ void RenderManager::renderSceneToScreen() {
 		outWndDirtyRect = _backgroundSurfaceDirtyRect;
 	}
 
+  //TODO - add widescreen menu buffer about here?
+
 	if (!outWndDirtyRect.isEmpty()) {
 		Common::Rect rect(
 			outWndDirtyRect.left + _workingWindow.left,
@@ -412,14 +416,7 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Com
 
 	byte *dstBuffer = (byte *)dst.getBasePtr(xx, yy);
 
-	int32 w = srcRect.width();
-	int32 h = srcRect.height();
-
-	for (int32 y = 0; y < h; y++) {
-		memcpy(dstBuffer, srcBuffer, w * srcAdapted->format.bytesPerPixel);
-		srcBuffer += srcAdapted->pitch;
-		dstBuffer += dst.pitch;
-	}
+	Graphics::copyBlit(dstBuffer,srcBuffer,dst.pitch,srcAdapted->pitch,srcRect.width(),srcRect.height(),srcAdapted->format.bytesPerPixel);
 
 	srcAdapted->free();
 	delete srcAdapted;
@@ -458,53 +455,7 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Com
 
 	byte *dstBuffer = (byte *)dst.getBasePtr(xx, yy);
 
-	int32 w = srcRect.width();
-	int32 h = srcRect.height();
-
-	for (int32 y = 0; y < h; y++) {
-		switch (srcAdapted->format.bytesPerPixel) {
-		case 1: {
-			const uint *srcTemp = (const uint *)srcBuffer;
-			uint *dstTemp = (uint *)dstBuffer;
-			for (int32 x = 0; x < w; x++) {
-				if (*srcTemp != keycolor)
-					*dstTemp = *srcTemp;
-				srcTemp++;
-				dstTemp++;
-			}
-		}
-		break;
-
-		case 2: {
-			const uint16 *srcTemp = (const uint16 *)srcBuffer;
-			uint16 *dstTemp = (uint16 *)dstBuffer;
-			for (int32 x = 0; x < w; x++) {
-				if (*srcTemp != keycolor)
-					*dstTemp = *srcTemp;
-				srcTemp++;
-				dstTemp++;
-			}
-		}
-		break;
-
-		case 4: {
-			const uint32 *srcTemp = (const uint32 *)srcBuffer;
-			uint32 *dstTemp = (uint32 *)dstBuffer;
-			for (int32 x = 0; x < w; x++) {
-				if (*srcTemp != keycolor)
-					*dstTemp = *srcTemp;
-				srcTemp++;
-				dstTemp++;
-			}
-		}
-		break;
-
-		default:
-			break;
-		}
-		srcBuffer += srcAdapted->pitch;
-		dstBuffer += dst.pitch;
-	}
+  Graphics::keyBlit(dstBuffer,srcBuffer,dst.pitch,srcAdapted->pitch,srcRect.width(),srcRect.height(),srcAdapted->format.bytesPerPixel,keycolor);
 
 	srcAdapted->free();
 	delete srcAdapted;
@@ -539,10 +490,13 @@ void RenderManager::blitSurfaceToBkgScaled(const Graphics::Surface &src, const C
 
 void RenderManager::blitSurfaceToMenu(const Graphics::Surface &src, int x, int y, int32 colorkey) {
 	Common::Rect empt;
+  Graphics::Surface *dstSurface = &_menuSurface;  //Add code to change this to background in widescreen mode if test works.
 	if (colorkey >= 0)
-		blitSurfaceToSurface(src, empt, _menuSurface, x, y, colorkey);
+		//blitSurfaceToSurface(src, empt, _menuSurface, x, y, colorkey);
+    blitSurfaceToSurface(src, empt, *dstSurface, x, y, colorkey);
 	else
-		blitSurfaceToSurface(src, empt, _menuSurface, x, y);
+		//blitSurfaceToSurface(src, empt, _menuSurface, x, y);
+		blitSurfaceToSurface(src, empt, *dstSurface, x, y);
 	Common::Rect dirty(src.w, src.h);
 	dirty.translate(x, y);
 	if (_menuSurfaceDirtyRect.isEmpty())


Commit: 185a1f7878bef87424bc78cb364e013ff980b700
    https://github.com/scummvm/scummvm/commit/185a1f7878bef87424bc78cb364e013ff980b700
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:53+02:00

Commit Message:
COMMON: Add detail to usage & functionality comment.

Changed paths:
    common/rect.h


diff --git a/common/rect.h b/common/rect.h
index d001ec69df7..d0cf597a521 100644
--- a/common/rect.h
+++ b/common/rect.h
@@ -389,7 +389,8 @@ struct Rect {
 
 	/**
 	 * Given target surface with size clip, this function ensures that
-	 * blit arguments @p dst and @p rect are within the @p clip rectangle.
+	 * blit arguments @p dst and @p rect are within the @p clip rectangle,
+	 * shrinking them as necessary.
 	 * @param dst  Blit destination coordinates.
 	 * @param rect Blit source rectangle.
 	 * @param clip Clip rectangle (size of destination surface).


Commit: fda0e8ac890cc40b3340a1bdb7b3d3e726ef2903
    https://github.com/scummvm/scummvm/commit/fda0e8ac890cc40b3340a1bdb7b3d3e726ef2903
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:53+02:00

Commit Message:
GRAPHICS: Add efficient dirty rectangle PixelFormat conversion to Screen::update().
Allow derived ManagedSurface to use different PixelFormat to parent Screen.
Function as before when pixelFormat matches g_system->getScreenFormat().

Changed paths:
    graphics/screen.cpp


diff --git a/graphics/screen.cpp b/graphics/screen.cpp
index be81655b064..b3e5cb68e71 100644
--- a/graphics/screen.cpp
+++ b/graphics/screen.cpp
@@ -43,13 +43,29 @@ void Screen::update() {
 	mergeDirtyRects();
 
 	// Loop through copying dirty areas to the physical screen
+	PixelFormat outputFormat = g_system->getScreenFormat();
 	Common::List<Common::Rect>::iterator i;
-	for (i = _dirtyRects.begin(); i != _dirtyRects.end(); ++i) {
-		const Common::Rect &r = *i;
-		const byte *srcP = (const byte *)getBasePtr(r.left, r.top);
-		g_system->copyRectToScreen(srcP, pitch, r.left, r.top,
-			r.width(), r.height());
-	}
+	if(outputFormat == format) {
+	  for (i = _dirtyRects.begin(); i != _dirtyRects.end(); ++i) {
+		  const Common::Rect &r = *i;
+		  const byte *srcP = (const byte *)getBasePtr(r.left, r.top);
+		  g_system->copyRectToScreen(srcP, pitch, r.left, r.top,
+			  r.width(), r.height());
+	  }
+  }
+  else {
+  	Graphics::Surface outSurface;
+    for (i = _dirtyRects.begin(); i != _dirtyRects.end(); ++i) {
+	    const Common::Rect &r = *i;
+		  const byte *srcP = (const byte *)getBasePtr(r.left, r.top);
+      outSurface.create(r.width(), r.height(), format);
+      outSurface.copyRectToSurface(srcP, pitch, 0, 0, r.width(), r.height());
+      outSurface.convertToInPlace(outputFormat);
+	    g_system->copyRectToScreen(outSurface.getBasePtr(0,0), outSurface.pitch, r.left, r.top,
+		    r.width(), r.height());
+    }
+    outSurface.free();
+  }
 
 	// Signal the physical screen to update
 	updateScreen();


Commit: 50f489bcecaa98f74291dafe5313430d62d9d48a
    https://github.com/scummvm/scummvm/commit/50f489bcecaa98f74291dafe5313430d62d9d48a
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:53+02:00

Commit Message:
GRAPHICS: Additional documentation & comments.

Changed paths:
    graphics/blit.h
    graphics/blit/blit.cpp


diff --git a/graphics/blit.h b/graphics/blit.h
index ef539694e72..49fd1f65dc6 100644
--- a/graphics/blit.h
+++ b/graphics/blit.h
@@ -54,6 +54,9 @@ inline static void convertPaletteToMap(uint32 *dst, const byte *src, uint colors
 
 /**
  * Blits a rectangle.
+ * Cautions: 
+ *  source & destination buffers must have same bpp
+ *  blit function has no protection against buffer overruns; w.bpp & h must not exceed respective byte dimensions (pitch & height) of either buffer
  *
  * @param dst			the buffer which will receive the converted graphics data
  * @param src			the buffer containing the original graphics data
diff --git a/graphics/blit/blit.cpp b/graphics/blit/blit.cpp
index af4e53d3d5c..4940e656d69 100644
--- a/graphics/blit/blit.cpp
+++ b/graphics/blit/blit.cpp
@@ -36,10 +36,15 @@ void copyBlit(byte *dst, const byte *src,
 		return;
 
 	if (dstPitch == srcPitch && ((w * bytesPerPixel) == dstPitch)) {
+	  //Buffers have equal line pitch AND total number of bytes per line matches that pitch
+	  //Therefore we may copy a whole subset of h full-width raster lines in one go.
 		memcpy(dst, src, dstPitch * h);
 	} else {
+	  //Not transferring whole width of either source or destination buffer, therefore must copy line-by-line
 		for (uint i = 0; i < h; ++i) {
+		  //Copy sublength w of one full buffer raster line
 			memcpy(dst, src, w * bytesPerPixel);
+			//iterate both buffer pointers by respective pitch to horizontally align starting point of next raster line with that of the one just copied
 			dst += dstPitch;
 			src += srcPitch;
 		}


Commit: ac0a7884dea5eacd5a472598f7163da8b258f587
    https://github.com/scummvm/scummvm/commit/ac0a7884dea5eacd5a472598f7163da8b258f587
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:53+02:00

Commit Message:
ZVISION: Adapt RenderManager structure for experimental widescreen support.
Add basic transparency to menu renderer to allow playfield overlay.
Add Scroller class to simplify menu code.
Refinements to Nemesis menu code.
Make greater use of standard G-system library functions.
Add widescreen tickbox to Nemesis game options.
ZGI-specific code not touched as yet.

Changed paths:
  A engines/zvision/scripting/scroller.cpp
  A engines/zvision/scripting/scroller.h
    engines/zvision/core/events.cpp
    engines/zvision/graphics/graphics_effect.h
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/module.mk
    engines/zvision/scripting/menu.cpp
    engines/zvision/scripting/menu.h
    engines/zvision/zvision.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/core/events.cpp b/engines/zvision/core/events.cpp
index 50b56d0e335..2a0b5095e1f 100644
--- a/engines/zvision/core/events.cpp
+++ b/engines/zvision/core/events.cpp
@@ -167,29 +167,37 @@ void ZVision::processEvents() {
 		switch (_event.type) {
 		case Common::EVENT_LBUTTONDOWN:
 			_cursorManager->cursorDown(true);
-			_scriptManager->setStateValue(StateKey_LMouse, 1);
 			_menu->onMouseDown(_event.mouse);
-			_scriptManager->addEvent(_event);
+			if(!_menu->isInMenu() || !_widescreen) {
+			  _scriptManager->setStateValue(StateKey_LMouse, 1);
+			  _scriptManager->addEvent(_event);
+		  }
 			break;
 
 		case Common::EVENT_LBUTTONUP:
 			_cursorManager->cursorDown(false);
-			_scriptManager->setStateValue(StateKey_LMouse, 0);
 			_menu->onMouseUp(_event.mouse);
-			_scriptManager->addEvent(_event);
+			if(!_menu->isInMenu() || !_widescreen) {
+			  _scriptManager->setStateValue(StateKey_LMouse, 0);
+			  _scriptManager->addEvent(_event);
+      }
 			break;
 
 		case Common::EVENT_RBUTTONDOWN:
 			_cursorManager->cursorDown(true);
-			_scriptManager->setStateValue(StateKey_RMouse, 1);
+			if(!_menu->isInMenu() || !_widescreen) {
+			  _scriptManager->setStateValue(StateKey_RMouse, 1);
 
-			if (getGameId() == GID_NEMESIS)
-				_scriptManager->inventoryCycle();
+			  if (getGameId() == GID_NEMESIS)
+				  _scriptManager->inventoryCycle();
+			}
 			break;
 
 		case Common::EVENT_RBUTTONUP:
 			_cursorManager->cursorDown(false);
-			_scriptManager->setStateValue(StateKey_RMouse, 0);
+			if(!_menu->isInMenu() || !_widescreen) {
+  			_scriptManager->setStateValue(StateKey_RMouse, 0);
+			}
 			break;
 
 		case Common::EVENT_MOUSEMOVE:
@@ -319,7 +327,7 @@ void ZVision::onMouseMove(const Common::Point &pos) {
 	Common::Point clippedPos = pos;
 	clippedPos.x = CLIP<int16>(pos.x, _workingWindow.left + 1, _workingWindow.right - 1);
 
-	if (_workingWindow.contains(clippedPos)) {
+	if (_workingWindow.contains(clippedPos) && !_menu->isInMenu()) {
 		cursorWasChanged = _scriptManager->onMouseMove(clippedPos, imageCoord);
 
 		RenderTable::RenderState renderState = _renderManager->getRenderTable()->getRenderState();
diff --git a/engines/zvision/graphics/graphics_effect.h b/engines/zvision/graphics/graphics_effect.h
index 38508569bc2..3493ed0a24e 100644
--- a/engines/zvision/graphics/graphics_effect.h
+++ b/engines/zvision/graphics/graphics_effect.h
@@ -48,10 +48,13 @@ public:
 		return _region;
 	}
 
+  //If true, effect is applied to the current background image prior to panoramic warping
+  //If false, effect is applied to the effects buffer, which corresponds directly to the working window
 	bool isPort() {
 		return _ported;
 	}
 
+  //Make a copy of supplied surface, draw effect on it, then return that altered surface
 	virtual const Graphics::Surface *draw(const Graphics::Surface &srcSubRect) {
 		return &_surface;
 	}
diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index f97290c3aa1..c3c3f2756e2 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -38,9 +38,12 @@
 
 #include "graphics/blit.h"
 
+//FOR BUG TEST ONLY
+#include "common/debug.h"
+
 namespace ZVision {
 
-RenderManager::RenderManager(ZVision *engine, uint32 windowWidth, uint32 windowHeight, const Common::Rect &workingWindow, const Graphics::PixelFormat &pixelFormat, bool doubleFPS)
+RenderManager::RenderManager(ZVision *engine, uint32 windowWidth, uint32 windowHeight, const Common::Rect workingWindow, const Common::Rect menuArea, const Graphics::PixelFormat pixelFormat, bool doubleFPS)
 	: _engine(engine),
 	  _system(engine->_system),
 	  _screenCenterX(_workingWindow.width() / 2),
@@ -52,14 +55,21 @@ RenderManager::RenderManager(ZVision *engine, uint32 windowWidth, uint32 windowH
 	  _backgroundOffset(0),
 	  _renderTable(_workingWindow.width(), _workingWindow.height()),
 	  _doubleFPS(doubleFPS),
-	  _subid(0) {
-
+	  _subid(0),
+	  _menuArea(menuArea) {
+	  
+  _screenSurface.create(WINDOW_WIDTH, WINDOW_HEIGHT, _pixelFormat);
+	_screenSurface.setTransparentColor(-1);
+	_screenSurface.clear();
+  
 	_backgroundSurface.create(_workingWindow.width(), _workingWindow.height(), _pixelFormat);
+	_backgroundManagedSurface.create(_screenSurface, _workingWindow);
+
 	_effectSurface.create(_workingWindow.width(), _workingWindow.height(), _pixelFormat);
 	_warpedSceneSurface.create(_workingWindow.width(), _workingWindow.height(), _pixelFormat);
-	_menuSurface.create(windowWidth, workingWindow.top, _pixelFormat);
 
-	_menuArea = Common::Rect(0, 0, windowWidth, workingWindow.top);
+	_menuSurface.create(_menuArea.width(), _menuArea.height(), _pixelFormat);
+	_menuManagedSurface.create(_screenSurface, _menuArea);
 
 	initSubArea(windowWidth, windowHeight, workingWindow);
 }
@@ -67,10 +77,13 @@ RenderManager::RenderManager(ZVision *engine, uint32 windowWidth, uint32 windowH
 RenderManager::~RenderManager() {
 	_currentBackgroundImage.free();
 	_backgroundSurface.free();
+	_backgroundManagedSurface.free();
 	_effectSurface.free();
 	_warpedSceneSurface.free();
 	_menuSurface.free();
+	_menuManagedSurface.free();
 	_subtitleSurface.free();
+	_screenSurface.free();
 }
 
 void RenderManager::renderSceneToScreen() {
@@ -78,7 +91,7 @@ void RenderManager::renderSceneToScreen() {
 	Graphics::Surface *in = &_backgroundSurface;
 	Common::Rect outWndDirtyRect;
 
-	// If we have graphical effects, we apply them using a temporary buffer
+	//Apply graphical effects to temporary effects buffer and/or directly to current background image, as appropriate
 	if (!_effects.empty()) {
 		bool copied = false;
 		Common::Rect windowRect(_workingWindow.width(), _workingWindow.height());
@@ -114,6 +127,7 @@ void RenderManager::renderSceneToScreen() {
 		}
 	}
 
+  //Apply panorama/tilt warp to background image
 	RenderTable::RenderState state = _renderTable.getRenderState();
 	if (state == RenderTable::PANORAMA || state == RenderTable::TILT) {
 		if (!_backgroundSurfaceDirtyRect.isEmpty()) {
@@ -125,18 +139,23 @@ void RenderManager::renderSceneToScreen() {
 		out = in;
 		outWndDirtyRect = _backgroundSurfaceDirtyRect;
 	}
-
-  //TODO - add widescreen menu buffer about here?
-
+	
+	
+	_backgroundManagedSurface.simpleBlitFrom(*out); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
+	//_menuManagedSurface.simpleBlitFrom(_menuSurface);
+	_menuManagedSurface.transBlitFrom(_menuSurface, -1);
+	_screenSurface.update();
+
+  /*
 	if (!outWndDirtyRect.isEmpty()) {
-		Common::Rect rect(
-			outWndDirtyRect.left + _workingWindow.left,
-			outWndDirtyRect.top + _workingWindow.top,
-			outWndDirtyRect.left + _workingWindow.left + outWndDirtyRect.width(),
-			outWndDirtyRect.top + _workingWindow.top + outWndDirtyRect.height()
-		);
-		copyToScreen(*out, rect, outWndDirtyRect.left, outWndDirtyRect.top);
+		Common::Rect rect = outWndDirtyRect;
+		rect.translate(_workingWindow.left,_workingWindow.top); //NB - feels like this should really be moveTo(), but that causes an offset bug when rendering doorknocker.  Suspect this is an irregularity elsewhere that will eventually need to be found & fixed, but can be tolerated for now.
+		
+  //Update dirty rectangle of screen
+		//copyToScreen(*out, rect, outWndDirtyRect.left, outWndDirtyRect.top);
+    copyToScreen(_backgroundManagedSurface, rect, outWndDirtyRect.left, outWndDirtyRect.top);
 	}
+	//*/
 }
 
 void RenderManager::copyToScreen(const Graphics::Surface &surface, Common::Rect &rect, int16 srcLeft, int16 srcTop) {
@@ -384,43 +403,116 @@ void RenderManager::scaleBuffer(const void *src, void *dst, uint32 srcWidth, uin
 	}
 }
 
+
+//ORIGINAL FUNCTION
+//*
 void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect , Graphics::Surface &dst, int _x, int _y) {
 	Common::Rect srcRect = _srcRect;
+	Common::Point dstPos = Common::Point(_x,_y);
+	//Default to using whole source surface
 	if (srcRect.isEmpty())
 		srcRect = Common::Rect(src.w, src.h);
-	srcRect.clip(src.w, src.h);
-	Common::Rect dstRect = Common::Rect(-_x + srcRect.left , -_y + srcRect.top, -_x + srcRect.left + dst.w, -_y + srcRect.top + dst.h);
+  //Clip source rectangle to within bounds of source buffer
+	srcRect.clip(src.w, src.h); 
+	
+	//CODE IDENTICAL TO HERE
+	
+	//BUG TEST CODE
+	Common::Point dstPos2 = dstPos;
+	Common::Rect srcRect2 = srcRect;
+	Common::Rect::getBlitRect(dstPos2, srcRect2, Common::Rect(dst.w,dst.h));
+	
+	//Generate destination rectangle
+	Common::Rect dstRect = Common::Rect(dst.w, dst.h);
+	//Translate destination rectangle to its position relative to source rectangle
+	dstRect.translate(srcRect.left-_x,srcRect.top-_y);
+	//clip source rectangle to within bounds of offset destination rectangle
 	srcRect.clip(dstRect);
-
-	if (srcRect.isEmpty() || !srcRect.isValidRect())
-		return;
-
-	Graphics::Surface *srcAdapted = src.convertTo(dst.format);
-
-	// Copy srcRect from src surface to dst surface
-	const byte *srcBuffer = (const byte *)srcAdapted->getBasePtr(srcRect.left, srcRect.top);
-
-	int xx = _x;
-	int yy = _y;
-
-	if (xx < 0)
-		xx = 0;
-	if (yy < 0)
-		yy = 0;
-
-	if (_x >= dst.w || _y >= dst.h) {
-		srcAdapted->free();
-		delete srcAdapted;
-		return;
+	
+	//BUG TEST
+	/*
+	if(srcRect.left != srcRect2.left) {
+	   debug("srcRect.left = %i, srcRect2.left = %i", srcRect.left, srcRect2.left);	   	   
 	}
+	if(srcRect.top != srcRect2.top) {
+	   debug("srcRect.top = %i, srcRect2.top = %i", srcRect.top, srcRect2.top);
+  } 
+	if(srcRect.right != srcRect2.right) {
+	   debug("srcRect.right = %i, srcRect2.right = %i", srcRect.right, srcRect2.right);
+  }
+	if(srcRect.bottom != srcRect2.bottom) {
+	   debug("srcRect.bottom = %i, srcRect2.bottom = %i", srcRect.bottom, srcRect2.bottom);	   
+  }
+*/
+
+  //CODE IDENTICAL FROM HERE  
+
+  //Abort if nothing to blit
+	if (!srcRect.isEmpty()) {
+    //Convert pixel format of source to match destination
+	  Graphics::Surface *srcAdapted = src.convertTo(dst.format);
+	  //Get pointer for source buffer blit rectangle origin
+	  const byte *srcBuffer = (const byte *)srcAdapted->getBasePtr(srcRect.left, srcRect.top);
+
+    //Default to blitting into origin of target surface if negative valued
+	  if (dstPos.x < 0)
+		  dstPos.x = 0;
+	  if (dstPos.y < 0)
+		  dstPos.y = 0;
+		  
+	  //BUG TEST
+	  assert(dstPos == dstPos2);
+    
+    //If _x & _y lie within destination surface
+    if (dstPos.x < dst.w && dstPos.y < dst.h) {
+      //Get pointer for destination buffer blit rectangle origin
+	    byte *dstBuffer = (byte *)dst.getBasePtr(dstPos.x, dstPos.y);
+	    Graphics::copyBlit(dstBuffer,srcBuffer,dst.pitch,srcAdapted->pitch,srcRect.width(),srcRect.height(),srcAdapted->format.bytesPerPixel);
+    }
+    srcAdapted->free();
+    delete srcAdapted;
+  }
 
-	byte *dstBuffer = (byte *)dst.getBasePtr(xx, yy);
+}
+/*/
 
-	Graphics::copyBlit(dstBuffer,srcBuffer,dst.pitch,srcAdapted->pitch,srcRect.width(),srcRect.height(),srcAdapted->format.bytesPerPixel);
+//SIMPLIFIED FUNCTION
+//TODO - find bug that breaks panorama rotation.  Suspect problem with negative arguments of some sort.
+//*
+void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect , Graphics::Surface &dst, int _x, int _y) {
+	Common::Rect srcRect = _srcRect;
+	Common::Point dstPos = Common::Point(_x,_y);
+	//Default to using whole source surface
+	if (srcRect.isEmpty())
+		srcRect = Common::Rect(src.w, src.h);
+  //Ensure source rectangle does not read beyond bounds of source surface
+	srcRect.clip(src.w, src.h);
 
-	srcAdapted->free();
-	delete srcAdapted;
+	//CODE IDENTICAL TO HERE
+	
+	//Ensure source rectangle does not write beyond bounds of destination surface & is valid
+	  //NB alters dstPos & srcRect!
+	Common::Rect::getBlitRect(dstPos, srcRect, Common::Rect(dst.w,dst.h));
+
+  //CODE IDENTICAL FROM HERE
+  
+	//Abort if nothing to blit
+	if(!srcRect.isEmpty()) {
+    //Convert pixel format of source to match destination
+	  Graphics::Surface *srcAdapted = src.convertTo(dst.format);
+	  //Get pointer for source buffer blit rectangle origin
+	  const byte *srcBuffer = (const byte *)srcAdapted->getBasePtr(srcRect.left, srcRect.top); 
+    //If _x & _y lie within destination surface
+    if (dstPos.x < dst.w && dstPos.y < dst.h) {
+      //Get pointer for destination buffer blit rectangle origin
+	    byte *dstBuffer = (byte *)dst.getBasePtr(dstPos.x, dstPos.y);
+	    Graphics::copyBlit(dstBuffer,srcBuffer,dst.pitch,srcAdapted->pitch,srcRect.width(),srcRect.height(),srcAdapted->format.bytesPerPixel);
+    }
+	  srcAdapted->free();
+	  delete srcAdapted;
+  }
 }
+//*/
 
 void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect , Graphics::Surface &dst, int _x, int _y, uint32 colorkey) {
 	Common::Rect srcRect = _srcRect;
@@ -430,6 +522,7 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Com
 	Common::Rect dstRect = Common::Rect(-_x + srcRect.left , -_y + srcRect.top, -_x + srcRect.left + dst.w, -_y + srcRect.top + dst.h);
 	srcRect.clip(dstRect);
 
+  //Abort if nothing to blit
 	if (srcRect.isEmpty() || !srcRect.isValidRect())
 		return;
 
@@ -447,16 +540,11 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Com
 	if (yy < 0)
 		yy = 0;
 
-	if (_x >= dst.w || _y >= dst.h) {
-		srcAdapted->free();
-		delete srcAdapted;
-		return;
-	}
-
+	if (_x < dst.w && _y < dst.h) {
 	byte *dstBuffer = (byte *)dst.getBasePtr(xx, yy);
-
   Graphics::keyBlit(dstBuffer,srcBuffer,dst.pitch,srcAdapted->pitch,srcRect.width(),srcRect.height(),srcAdapted->format.bytesPerPixel,keycolor);
-
+  }
+  
 	srcAdapted->free();
 	delete srcAdapted;
 }
@@ -488,21 +576,28 @@ void RenderManager::blitSurfaceToBkgScaled(const Graphics::Surface &src, const C
 	}
 }
 
-void RenderManager::blitSurfaceToMenu(const Graphics::Surface &src, int x, int y, int32 colorkey) {
+void RenderManager::blitSurfaceToMenu(const Graphics::Surface &src, int16 x, int16 y, int32 colorkey) {
 	Common::Rect empt;
-  Graphics::Surface *dstSurface = &_menuSurface;  //Add code to change this to background in widescreen mode if test works.
-	if (colorkey >= 0)
+	Common::Point destPos{x,y};
+  Graphics::Surface *dstSurface = &_menuSurface;
+	if (colorkey >= 0) {
 		//blitSurfaceToSurface(src, empt, _menuSurface, x, y, colorkey);
     blitSurfaceToSurface(src, empt, *dstSurface, x, y, colorkey);
-	else
+    //_menuManagedSurface.transBlitFrom(src,destPos,colorkey);
+  }
+	else {
 		//blitSurfaceToSurface(src, empt, _menuSurface, x, y);
 		blitSurfaceToSurface(src, empt, *dstSurface, x, y);
+    //_menuManagedSurface.blitFrom(src,destPos);
+  }
+  //*/
 	Common::Rect dirty(src.w, src.h);
-	dirty.translate(x, y);
+	dirty.moveTo(x, y);
 	if (_menuSurfaceDirtyRect.isEmpty())
 		_menuSurfaceDirtyRect = dirty;
 	else
 		_menuSurfaceDirtyRect.extend(dirty);
+	//*/
 }
 
 Graphics::Surface *RenderManager::getBkgRect(Common::Rect &rect) {
@@ -606,33 +701,17 @@ void RenderManager::prepareBackground() {
 	_backgroundSurfaceDirtyRect.clip(_workingWindow.width(), _workingWindow.height());
 }
 
-void RenderManager::clearMenuSurface() {
+void RenderManager::clearMenuSurface(int32 colorkey) {
 	_menuSurfaceDirtyRect = Common::Rect(0, 0, _menuSurface.w, _menuSurface.h);
-	_menuSurface.fillRect(_menuSurfaceDirtyRect, 0);
+	_menuSurface.fillRect(_menuSurfaceDirtyRect, colorkey);
 }
 
-void RenderManager::clearMenuSurface(const Common::Rect &r) {
+void RenderManager::clearMenuSurface(const Common::Rect &r, int32 colorkey) {
 	if (_menuSurfaceDirtyRect.isEmpty())
 		_menuSurfaceDirtyRect = r;
 	else
 		_menuSurfaceDirtyRect.extend(r);
-	_menuSurface.fillRect(r, 0);
-}
-
-void RenderManager::renderMenuToScreen() {
-	if (!_menuSurfaceDirtyRect.isEmpty()) {
-		_menuSurfaceDirtyRect.clip(Common::Rect(_menuSurface.w, _menuSurface.h));
-		if (!_menuSurfaceDirtyRect.isEmpty()) {
-			Common::Rect rect(
-				_menuSurfaceDirtyRect.left + _menuArea.left,
-				_menuSurfaceDirtyRect.top + _menuArea.top,
-				_menuSurfaceDirtyRect.left + _menuArea.left + _menuSurfaceDirtyRect.width(),
-				_menuSurfaceDirtyRect.top + _menuArea.top + _menuSurfaceDirtyRect.height()
-			);
-			copyToScreen(_menuSurface, rect, _menuSurfaceDirtyRect.left, _menuSurfaceDirtyRect.top);
-		}
-		_menuSurfaceDirtyRect = Common::Rect();
-	}
+	_menuSurface.fillRect(r, colorkey);
 }
 
 void RenderManager::initSubArea(uint32 windowWidth, uint32 windowHeight, const Common::Rect &workingWindow) {
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index 9c39ebf38e6..a069a970b4e 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -30,6 +30,9 @@
 
 #include "graphics/surface.h"
 
+#include "graphics/managed_surface.h"
+#include "graphics/screen.h"
+
 #include "zvision/graphics/graphics_effect.h"
 
 class OSystem;
@@ -47,7 +50,7 @@ namespace ZVision {
 
 class RenderManager {
 public:
-	RenderManager(ZVision *engine, uint32 windowWidth, uint32 windowHeight, const Common::Rect &workingWindow, const Graphics::PixelFormat &pixelFormat, bool doubleFPS);
+	RenderManager(ZVision *engine, uint32 windowWidth, uint32 windowHeight, const Common::Rect workingWindow, const Common::Rect menuArea, const Graphics::PixelFormat pixelFormat, bool doubleFPS);
 	~RenderManager();
 
 private:
@@ -78,6 +81,12 @@ private:
 	const int _screenCenterX;
 	// Center of the screen in the y direction
 	const int _screenCenterY;
+	
+	
+	/**
+	Managed surface representing physical screen; dirty rectangles will be handled automatically by this from now on
+    */
+	Graphics::Screen _screenSurface;
 
 	/** A buffer for background image that's being used to create the background */
 	Graphics::Surface _currentBackgroundImage;
@@ -97,6 +106,7 @@ private:
 	// If it's a normal scene, the pixels will be blitted directly to the screen
 	// If it's a panorma / tilt scene, the pixels will be first warped to _warpedSceneSurface
 	Graphics::Surface _backgroundSurface;
+	Graphics::ManagedSurface _backgroundManagedSurface;
 	Common::Rect _backgroundSurfaceDirtyRect;
 
 	// A buffer for subtitles
@@ -107,6 +117,7 @@ private:
 
 	// A buffer for menu drawing
 	Graphics::Surface _menuSurface;
+	Graphics::ManagedSurface _menuManagedSurface;
 	Common::Rect _menuSurfaceDirtyRect;
 
 	// Rectangle for menu area
@@ -118,7 +129,6 @@ private:
 	// A buffer to store the result of the panorama / tilt warps
 	Graphics::Surface _warpedSceneSurface;
 
-
 	/** Used to warp the background image */
 	RenderTable _renderTable;
 
@@ -221,8 +231,17 @@ public:
 	// Scale buffer (nearest)
 	void scaleBuffer(const void *src, void *dst, uint32 srcWidth, uint32 srcHeight, byte bytesPerPixel, uint32 dstWidth, uint32 dstHeight);
 
-	// Blitting surface-to-surface methods
-	void blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect , Graphics::Surface &dst, int x, int y);
+	/**
+	 * Blit from one surface to another surface
+	 *
+	 * @param src       Source surface
+	 * @param _srcRect  Rectangle defining area of source surface to blit; if this rectangle is empty, entire source surface is blitted
+	 * @param dst       Destination surface
+ 	 * @param x         Destination surface x coordinate
+	 * @param y         Destination surface y coordinate
+	 */	
+
+	void blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect , Graphics::Surface &dst, int _x, int _y);
 	void blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect , Graphics::Surface &dst, int _x, int _y, uint32 colorkey);
 
 	// Blitting surface-to-background methods
@@ -232,7 +251,7 @@ public:
 	void blitSurfaceToBkgScaled(const Graphics::Surface &src, const Common::Rect &_dstRect, int32 colorkey = -1);
 
 	// Blitting surface-to-menu methods
-	void blitSurfaceToMenu(const Graphics::Surface &src, int x, int y, int32 colorkey = -1);
+	void blitSurfaceToMenu(const Graphics::Surface &src, int16 x, int16 y, int32 colorkey = -1);
 
 	// Subtitles methods
 
@@ -263,11 +282,8 @@ public:
 	Graphics::Surface *loadImage(const Common::Path &file, bool transposed);
 
 	// Clear whole/area of menu surface
-	void clearMenuSurface();
-	void clearMenuSurface(const Common::Rect &r);
-
-	// Copy menu buffer to screen
-	void renderMenuToScreen();
+	void clearMenuSurface(int32 colorkey = 0);
+	void clearMenuSurface(const Common::Rect &r, int32 colorkey = 0);
 
 	// Copy needed portion of background surface to workingWindow surface
 	void prepareBackground();
diff --git a/engines/zvision/module.mk b/engines/zvision/module.mk
index 70728e39dc4..6562501f84c 100644
--- a/engines/zvision/module.mk
+++ b/engines/zvision/module.mk
@@ -30,6 +30,7 @@ MODULE_OBJS := \
 	scripting/controls/titler_control.o \
 	scripting/inventory.o \
 	scripting/menu.o \
+	scripting/scroller.o \
 	scripting/scr_file_handling.o \
 	scripting/script_manager.o \
 	scripting/effects/animation_effect.o \
diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index 61fe7b3dcb5..6c544259d4a 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -37,15 +37,17 @@ enum {
 	kMenuMain = 2
 };
 
-MenuHandler::MenuHandler(ZVision *engine) {
+MenuHandler::MenuHandler(ZVision *engine, const Common::Rect menuArea) {
 	_engine = engine;
 	menuBarFlag = 0xFFFF;
+	_menuArea = menuArea; //Area in which menu is drawn
+	_menuTriggerArea = menuArea;  //Area in which mouse triggers menu scrolldown
 }
 
-MenuZGI::MenuZGI(ZVision *engine) :
-	MenuHandler(engine) {
+MenuZGI::MenuZGI(ZVision *engine, const Common::Rect menuArea) :
+	MenuHandler(engine, menuArea) {
 	menuMouseFocus = -1;
-	inMenu = false;
+	menuActive = false;
 	scrolled[0] = false;
 	scrolled[1] = false;
 	scrolled[2] = false;
@@ -210,9 +212,9 @@ void MenuZGI::onMouseUp(const Common::Point &Pos) {
 void MenuZGI::onMouseMove(const Common::Point &Pos) {
 	if (Pos.y < 40) {
 
-		if (!inMenu)
+		if (!menuActive)
 			redraw = true;
-		inMenu = true;
+		menuActive = true;
 		switch (menuMouseFocus) {
 		case kMenuItem:
 			if (menuBarFlag & kMenubarItems) {
@@ -339,9 +341,9 @@ void MenuZGI::onMouseMove(const Common::Point &Pos) {
 			break;
 		}
 	} else {
-		if (inMenu)
+		if (menuActive)
 			clean = true;
-		inMenu = false;
+		menuActive = false;
 		if (_engine->getScriptManager()->getStateValue(StateKey_MenuState) != 0)
 			_engine->getScriptManager()->setStateValue(StateKey_MenuState, 0);
 		menuMouseFocus = -1;
@@ -505,7 +507,7 @@ void MenuZGI::process(uint32 deltatime) {
 			}
 		}
 		if (redraw) {
-			_engine->getRenderManager()->blitSurfaceToMenu(menuBack[kMenuMain][0], 30, scrollPos[kMenuMain]); //TODO - experiment with adding colorkey here for overlaying playfield in widescreen.
+			_engine->getRenderManager()->blitSurfaceToMenu(menuBack[kMenuMain][0], 30, scrollPos[kMenuMain]);
 
 			if (menuBarFlag & kMenubarExit) {
 				if (mouseOnItem == kMainMenuExit)
@@ -536,7 +538,7 @@ void MenuZGI::process(uint32 deltatime) {
 		break;
 	default:
 		if (redraw) {
-			if (inMenu) {
+			if (menuActive) {
 				_engine->getRenderManager()->blitSurfaceToMenu(menuBack[kMenuMain][1], 30, 0);
 
 				if (menuBarFlag & kMenubarItems)
@@ -551,22 +553,23 @@ void MenuZGI::process(uint32 deltatime) {
 	}
 }
 
-MenuNemesis::MenuNemesis(ZVision *engine) :
-	MenuHandler(engine) {
-	inMenu = false;
-	scrolled = false;
-	scrollPos = 0;
+MenuNemesis::MenuNemesis(ZVision *engine, const Common::Rect menuArea) :
+	MenuHandler(engine, menuArea),
+	menuScroller(Common::Point(0,0), Common::Point(0,-32)) {
 	mouseOnItem = -1;
 	redraw = false;
 	delay = 0;
 
-  //Buffer button images
 	char buf[24];
-	for (int i = 0; i < 4; i++)
+	for (int i = 0; i < 4; i++) {
+    //Buffer button images
 		for (int j = 0; j < 6; j++) {
 			Common::sprintf_s(buf, "butfrm%d%d.tga", i + 1, j);
 			_engine->getRenderManager()->readImageToSurface(buf, but[i][j], false);
 		}
+		//Generate button hotspot areas
+		hotspots[i] = Common::Rect(wxButs[i][1], _menuArea.top, wxButs[i][1]+wxButs[i][0], _menuArea.bottom);
+	}
 
   //Buffer menubar image
 	_engine->getRenderManager()->readImageToSurface("bar.tga", menuBar, false);
@@ -582,53 +585,34 @@ MenuNemesis::~MenuNemesis() {
 	menuBar.free();
 }
 
-//Widths & X positions of buttons; {Save, Restore, Prefs, Exit}
-static const int16 wxButs[4][2] = { {120 , 64}, {144, 184}, {128, 328}, {120, 456} };
-//Height of menu bar & buttons
-static const int16 hMenu[2] = {32,40};  //{graphics height, trigger boundary height}
-static const int16 wxMenu[2] = {512,64}; //Width, X position
-
 void MenuNemesis::onMouseUp(const Common::Point &Pos) {
-	if (Pos.y < hMenu[1]) {
+  inMenu = _menuArea.contains(Pos);
+
+	if (_menuTriggerArea.contains(Pos)) {
 		// Exit
 		if (menuBarFlag & kMenubarExit)
-			if (Common::Rect(wxButs[3][1],
-			                 scrollPos,
-			                 wxButs[3][0] + wxButs[3][1],
-			                 scrollPos + hMenu[0]).contains(Pos)) {
+		  if (hotspots[3].contains(Pos)) {
 				_engine->ifQuit();
 				frm = 5;
 				redraw = true;
 			}
-
 		// Prefs
 		if (menuBarFlag & kMenubarSettings)
-			if (Common::Rect(wxButs[2][1],
-			                 scrollPos,
-			                 wxButs[2][0] + wxButs[2][1],
-			                 scrollPos + hMenu[0]).contains(Pos)) {
+		  if (hotspots[2].contains(Pos)) {
 				_engine->getScriptManager()->changeLocation('g', 'j', 'p', 'e', 0);
 				frm = 5;
 				redraw = true;
 			}
-
 		// Restore
 		if (menuBarFlag & kMenubarRestore)
-			if (Common::Rect(wxButs[1][1],
-			                 scrollPos,
-			                 wxButs[1][0] + wxButs[1][1],
-			                 scrollPos + hMenu[0]).contains(Pos)) {
+		  if (hotspots[1].contains(Pos)) {
 				_engine->getScriptManager()->changeLocation('g', 'j', 'r', 'e', 0);
 				frm = 5;
 				redraw = true;
 			}
-
 		// Save
 		if (menuBarFlag & kMenubarSave)
-			if (Common::Rect(wxButs[0][1],
-			                 scrollPos,
-			                 wxButs[0][0] + wxButs[0][1],
-			                 scrollPos + hMenu[0]).contains(Pos)) {
+		  if (hotspots[0].contains(Pos)) {
 				_engine->getScriptManager()->changeLocation('g', 'j', 's', 'e', 0);
 				frm = 5;
 				redraw = true;
@@ -637,9 +621,10 @@ void MenuNemesis::onMouseUp(const Common::Point &Pos) {
 }
 
 void MenuNemesis::onMouseMove(const Common::Point &Pos) {
-	if (Pos.y < hMenu[1]) {
+  inMenu = _menuArea.contains(Pos);
 
-		inMenu = true;
+	if (_menuTriggerArea.contains(Pos)) {
+		menuScroller.active = true;
 
 		if (_engine->getScriptManager()->getStateValue(StateKey_MenuState) != 2)
 			_engine->getScriptManager()->setStateValue(StateKey_MenuState, 2);
@@ -647,41 +632,25 @@ void MenuNemesis::onMouseMove(const Common::Point &Pos) {
 		int lastItem = mouseOnItem;
 		mouseOnItem = -1;
 
-		// Exit
-		if (menuBarFlag & kMenubarExit)
-			if (Common::Rect(wxButs[3][1],
-			                 scrollPos,
-			                 wxButs[3][0] + wxButs[3][1],
-			                 scrollPos + hMenu[0]).contains(Pos)) {
-				mouseOnItem = kMainMenuExit;
-			}
-
-		// Prefs
-		if (menuBarFlag & kMenubarSettings)
-			if (Common::Rect(wxButs[2][1],
-			                 scrollPos,
-			                 wxButs[2][0] + wxButs[2][1],
-			                 scrollPos + hMenu[0]).contains(Pos)) {
-				mouseOnItem = kMainMenuPrefs;
-			}
-
-		// Restore
-		if (menuBarFlag & kMenubarRestore)
-			if (Common::Rect(wxButs[1][1],
-			                 scrollPos,
-			                 wxButs[1][0] + wxButs[1][1],
-			                 scrollPos + hMenu[0]).contains(Pos)) {
-				mouseOnItem = kMainMenuLoad;
-			}
-
-		// Save
-		if (menuBarFlag & kMenubarSave)
-			if (Common::Rect(wxButs[0][1],
-			                 scrollPos,
-			                 wxButs[0][0] + wxButs[0][1],
-			                 scrollPos + hMenu[0]).contains(Pos)) {
-				mouseOnItem = kMainMenuSave;
-			}
+    //Check mouse position against menu area
+	  if(inMenu) {
+	    // Exit
+		  if (menuBarFlag & kMenubarExit)
+			  if (hotspots[3].contains(Pos))
+				  mouseOnItem = kMainMenuExit;
+		  // Prefs
+		  if (menuBarFlag & kMenubarSettings)
+			  if (hotspots[2].contains(Pos))
+				  mouseOnItem = kMainMenuPrefs;
+		  // Restore
+		  if (menuBarFlag & kMenubarRestore)
+			  if (hotspots[1].contains(Pos))
+				  mouseOnItem = kMainMenuLoad;
+		  // Save
+		  if (menuBarFlag & kMenubarSave)
+			  if (hotspots[0].contains(Pos))
+				  mouseOnItem = kMainMenuSave;
+		}
 
 		if (lastItem != mouseOnItem) {
 			redraw = true;
@@ -689,7 +658,7 @@ void MenuNemesis::onMouseMove(const Common::Point &Pos) {
 			delay = 200;
 		}
 	} else {
-		inMenu = false;
+		menuScroller.active = false;
 		if (_engine->getScriptManager()->getStateValue(StateKey_MenuState) != 0)
 			_engine->getScriptManager()->setStateValue(StateKey_MenuState, 0);
 		mouseOnItem = -1;
@@ -697,73 +666,44 @@ void MenuNemesis::onMouseMove(const Common::Point &Pos) {
 }
 
 void MenuNemesis::process(uint32 deltatime) {
-	if (inMenu) {
-		if (!scrolled) {
-			float dScrl = hMenu[0] * 2.0 * (deltatime / 1000.0);
-
-			if (dScrl == 0)
-				dScrl = 1.0;
-
-			scrollPos += (int)dScrl;
-			redraw = true;
+  
+	if(menuScroller.update(deltatime)) {
+		redraw = true;
+    for (int i = 0; i < 4; i++)
+      hotspots[i].moveTo(_menuArea.left + wxButs[i][1], _menuArea.top + menuScroller.Pos.y);
 		}
 
-		if (scrollPos >= 0) {
-			scrolled = true;
-			scrollPos = 0;
-		}
-
-		if (mouseOnItem != -1) {
-			delay -= deltatime;
-			if (delay <= 0 && frm < 4) {
-				delay = 200;
-				frm++;
-				redraw = true;
-			}
+	if (mouseOnItem != -1) {
+		delay -= deltatime;
+		if (delay <= 0 && frm < 4) {
+			delay = 200;
+			frm++;
+			redraw = true;
 		}
+	}
+		
+	if (redraw) {
+		_engine->getRenderManager()->clearMenuSurface(colorkey);
+		_engine->getRenderManager()->blitSurfaceToMenu(menuBar, 0, menuScroller.Pos.y);
 
-		if (redraw) {
-			_engine->getRenderManager()->blitSurfaceToMenu(menuBar, wxMenu[1], scrollPos);
-
-			if (menuBarFlag & kMenubarExit)
-				if (mouseOnItem == kMainMenuExit)
-					_engine->getRenderManager()->blitSurfaceToMenu(but[3][frm], wxButs[3][1], scrollPos);
-
-			if (menuBarFlag & kMenubarSettings)
-				if (mouseOnItem == kMainMenuPrefs)
-					_engine->getRenderManager()->blitSurfaceToMenu(but[2][frm], wxButs[2][1], scrollPos);
-
-			if (menuBarFlag & kMenubarRestore)
-				if (mouseOnItem == kMainMenuLoad)
-					_engine->getRenderManager()->blitSurfaceToMenu(but[1][frm], wxButs[1][1], scrollPos);
-
-			if (menuBarFlag & kMenubarSave)
-				if (mouseOnItem == kMainMenuSave)
-					_engine->getRenderManager()->blitSurfaceToMenu(but[0][frm], wxButs[0][1], scrollPos);
-
-			redraw = false;
-		}
-	} else {
-		scrolled = false;
-		if (scrollPos > -hMenu[0]) {
-			float dScrl = hMenu[0] * 2.0 * (deltatime / 1000.0);
+		if (menuBarFlag & kMenubarExit)
+			if (mouseOnItem == kMainMenuExit)
+				_engine->getRenderManager()->blitSurfaceToMenu(but[3][frm], wxButs[3][1], menuScroller.Pos.y);
 
-			if (dScrl == 0)
-				dScrl = 1.0;
+		if (menuBarFlag & kMenubarSettings)
+			if (mouseOnItem == kMainMenuPrefs)
+				_engine->getRenderManager()->blitSurfaceToMenu(but[2][frm], wxButs[2][1], menuScroller.Pos.y);
 
-			Common::Rect cl(wxMenu[1], (int16)(hMenu[0] + scrollPos - dScrl), wxMenu[1] + wxMenu[0], hMenu[0] + scrollPos + 1);
-			_engine->getRenderManager()->clearMenuSurface(cl);
+		if (menuBarFlag & kMenubarRestore)
+			if (mouseOnItem == kMainMenuLoad)
+				_engine->getRenderManager()->blitSurfaceToMenu(but[1][frm], wxButs[1][1], menuScroller.Pos.y);
 
-			scrollPos -= (int)dScrl;
-			redraw = true;
-		} else
-			scrollPos = -hMenu[0];
+		if (menuBarFlag & kMenubarSave)
+			if (mouseOnItem == kMainMenuSave)
+				_engine->getRenderManager()->blitSurfaceToMenu(but[0][frm], wxButs[0][1], menuScroller.Pos.y);
 
-		if (redraw) {
-			_engine->getRenderManager()->blitSurfaceToMenu(menuBar, wxMenu[1], scrollPos);
-			redraw = false;
-		}
-	}
+		redraw = false;
+	}	
 }
-
+  
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/menu.h b/engines/zvision/scripting/menu.h
index c70cabb4cdc..60f26cafe7b 100644
--- a/engines/zvision/scripting/menu.h
+++ b/engines/zvision/scripting/menu.h
@@ -27,6 +27,7 @@
 
 #include "zvision/zvision.h"
 #include "zvision/scripting/script_manager.h"
+#include "zvision/scripting/scroller.h"
 
 namespace ZVision {
 
@@ -41,12 +42,14 @@ enum menuBar {
 
 class MenuHandler {
 public:
-	MenuHandler(ZVision *engine);
+	MenuHandler(ZVision *engine, Common::Rect menuArea);
 	virtual ~MenuHandler() {};
 	virtual void onMouseMove(const Common::Point &Pos) {};
 	virtual void onMouseDown(const Common::Point &Pos) {};
 	virtual void onMouseUp(const Common::Point &Pos) {};
 	virtual void process(uint32 deltaTimeInMillis) {};
+  bool isInMenu() {return inMenu;}; //For widescreen mod; used to suspend panning, tilting & scripting triggers when the mouse is within the working window but also in the menu.
+  //NB former boolean flag inMenu has been renamed to menuActive.
 
 	void setEnable(uint16 flags) {
 		menuBarFlag = flags;
@@ -57,11 +60,18 @@ public:
 protected:
 	uint16 menuBarFlag;
 	ZVision *_engine;
+  Common::Rect _menuArea;	
+  Common::Rect _menuTriggerArea;
+	bool menuActive;  //True if mouse is in menu area
+	bool inMenu = false;  //True if mouse is over scrolled menu graphics, regardless of menuActive
+	bool redraw = true;
+	int mouseOnItem;
+	int32 colorkey = -1;  //Transparency color for compositing menu over playfield
 };
 
 class MenuZGI: public MenuHandler {
 public:
-	MenuZGI(ZVision *engine);
+	MenuZGI(ZVision *engine, Common::Rect menuArea);
 	~MenuZGI() override;
 	void onMouseMove(const Common::Point &Pos) override;
 	void onMouseUp(const Common::Point &Pos) override;
@@ -76,21 +86,16 @@ private:
 	uint magicId[12];
 
 	int menuMouseFocus;
-	bool inMenu;
-
-	int mouseOnItem;
 
 	bool scrolled[3];
 	int16 scrollPos[3];
 
 	bool clean;
-	bool redraw;
-
 };
 
 class MenuNemesis: public MenuHandler {
 public:
-	MenuNemesis(ZVision *engine);
+	MenuNemesis(ZVision *engine, Common::Rect menuArea);
 	~MenuNemesis() override;
 	void onMouseMove(const Common::Point &Pos) override;
 	void onMouseUp(const Common::Point &Pos) override;
@@ -98,19 +103,17 @@ public:
 private:
 	Graphics::Surface but[4][6];
 	Graphics::Surface menuBar;
-
-	bool inMenu;
-
-	int mouseOnItem;
-
-	bool scrolled;
-	int16 scrollPos;  //Offset of scrolling menu from its fully visible position
-
-	bool redraw;
+	Common::Rect hotspots[4];
+	
+  //Widths & X positions of buttons; {Save, Restore, Prefs, Exit}
+  //X positions relative to left of menu area
+  //const int16 wxButs[4][2] = { {120 , 64}, {144, 184}, {128, 328}, {120, 456} };  //Originals
+  const int16 wxButs[4][2] = { {120 , 0}, {144, 120}, {128, 264}, {120, 392} };
+	
+  Scroller menuScroller;
 
 	int frm;
 	int16 delay;
-
 };
 
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/scroller.cpp b/engines/zvision/scripting/scroller.cpp
new file mode 100644
index 00000000000..ad2540186b8
--- /dev/null
+++ b/engines/zvision/scripting/scroller.cpp
@@ -0,0 +1,79 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "zvision/scripting/scroller.h"
+
+namespace ZVision {
+
+Scroller::Scroller(const Common::Point &activePos, const Common::Point &idlePos, int16 period) :
+  _activePos(activePos), 
+  _idlePos(idlePos),
+  _period(period) {
+  deltaPos = _activePos - _idlePos;
+	Pos = _idlePos;
+	prevPos = Pos;
+}
+
+Scroller::~Scroller() {
+}
+
+bool Scroller::update(uint32 deltatime) {
+  prevPos = Pos;
+
+  Common::Point targetPos;
+	float dx=0;
+	float dy=0;
+	
+	if (active)
+	  targetPos = _activePos;
+  else
+  	targetPos = _idlePos;
+
+  if (Pos.x != targetPos.x) {
+    dx = (deltaPos.x * deltatime) / _period;
+    if(dx == 0)
+      dx = 1;
+  }
+  if (Pos.y != targetPos.y) {
+    dy = (deltaPos.y * deltatime) / _period;
+    if(dy == 0)
+      dy = 1;
+  }
+  
+  if(!active) {
+    dx = -dx;
+    dy = -dy;
+  }
+  
+  Pos.x += (int)dx;
+  if( (dx == 0) || ( (dx > 0) && (Pos.x > targetPos.x) ) || ( (dx < 0) && (Pos.x < targetPos.x) ) )
+    Pos.x = targetPos.x;
+    
+  Pos.y += (int)dy;
+  if( (dy == 0) || ( (dy > 0) && (Pos.y > targetPos.y) ) || ( (dy < 0) && (Pos.y < targetPos.y) ) )
+    Pos.y = targetPos.y;
+	
+	scrolled = (Pos == _activePos);
+
+	return (Pos != prevPos);  //True if redraw necessary
+}
+
+} // End of namespace ZVision
diff --git a/engines/zvision/scripting/scroller.h b/engines/zvision/scripting/scroller.h
new file mode 100644
index 00000000000..c6f40b22e3b
--- /dev/null
+++ b/engines/zvision/scripting/scroller.h
@@ -0,0 +1,50 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef ZVISION_SCROLLER_H
+#define ZVISION_SCROLLER_H
+
+#include "common/rect.h"
+#include "zvision/zvision.h"
+
+namespace ZVision {
+
+class Scroller {
+public:
+  Scroller(const Common::Point &activePos, const Common::Point &idlePos, const int16 period = 500);
+  ~Scroller();
+  bool update(uint32 deltatime);  //Calculate updated position of scrolled graphics; return true if redraw is necessary.
+
+	Common::Point Pos;
+	Common::Point prevPos;
+
+  bool active = false;
+	bool scrolled = false;  //True when menu is in full active position
+private:
+  const Common::Point _activePos;
+  const Common::Point _idlePos;
+	Common::Point deltaPos;
+  const int16 _period;
+};
+
+} // End of namespace ZVision
+
+#endif
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index c30711594a9..a2a436f87f5 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -220,7 +220,7 @@ void ZVision::initialize() {
 
 	// Create managers
 	_scriptManager = new ScriptManager(this);
-	_renderManager = new RenderManager(this, WINDOW_WIDTH, WINDOW_HEIGHT, _workingWindow, _resourcePixelFormat, _doubleFPS);
+	_renderManager = new RenderManager(this, WINDOW_WIDTH, WINDOW_HEIGHT, _workingWindow, _menuArea, _resourcePixelFormat, _doubleFPS);
 	_saveManager = new SaveManager(this);
 	_stringManager = new StringManager(this);
 	_cursorManager = new CursorManager(this, _resourcePixelFormat);
@@ -228,9 +228,9 @@ void ZVision::initialize() {
 	_midiManager = new MidiManager();
 
 	if (getGameId() == GID_GRANDINQUISITOR)
-		_menu = new MenuZGI(this);
+		_menu = new MenuZGI(this, _menuArea);
 	else
-		_menu = new MenuNemesis(this);
+		_menu = new MenuNemesis(this, _menuArea);
 
 	// Initialize the managers
 	_cursorManager->initialize();
@@ -334,9 +334,8 @@ Common::Error ZVision::run() {
 
 		// Render the backBuffer to the screen
 		_renderManager->prepareBackground();
-		_renderManager->renderMenuToScreen(); //TODO - disable in widescreen mode.
-		_renderManager->processSubs(deltaTime); //TODO - alter to blit subs to intermediate buffer, then handle this buffer in renderscenetoscreen()?
-		_renderManager->renderSceneToScreen();  //TODO - add code to composite menu surface into scene in this function in widescreen mode.
+		_renderManager->processSubs(deltaTime); //TODO - alter to blit subs to intermediate buffer, then handle this buffer in renderscenetoscreen, in same manner as menu
+		_renderManager->renderSceneToScreen();
 
 		// Update the screen
 		if (canRender()) {
@@ -404,6 +403,17 @@ void ZVision::initScreen() {
 						((WINDOW_HEIGHT - workingWindowHeight) / 2) + workingWindowHeight
 					 );
 
+	uint16 menuAreaHeight = (getGameId() == GID_NEMESIS) ? ZNM_MENU_HEIGHT : ZGI_MENU_HEIGHT;
+  _menuArea = Common::Rect(
+						 (WINDOW_WIDTH  -  workingWindowWidth) / 2,
+						 0,
+						((WINDOW_WIDTH  -  workingWindowWidth) / 2) + workingWindowWidth,
+						menuAreaHeight
+					 );
+
+  if(_widescreen)
+    _menuArea.moveTo(_workingWindow.left, _workingWindow.top);
+
 	initGraphics(WINDOW_WIDTH, WINDOW_HEIGHT, &_screenPixelFormat);
 }
 
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index 5fa69747e8a..3cecdbe7232 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -77,14 +77,14 @@ enum {
 	HIRES_WINDOW_WIDTH = 800,
 	HIRES_WINDOW_HEIGHT = 600,
 
-	// Zork Nemesis working window sizes
+	// Zork Nemesis working window sizes (original aspect ratio 8:5)
 	ZNM_WORKING_WINDOW_WIDTH = 512, //Original 512
 	ZNM_WORKING_WINDOW_HEIGHT = 320,  //Original 320
 	
 	ZNM_SUBTITLE_HEIGHT = 80, //Original 80
 	ZNM_MENU_HEIGHT = 40,  //Original 80
 
-	// ZGI working window sizes
+	// ZGI working window sizes (original aspect ratio 2:1)
 	ZGI_WORKING_WINDOW_WIDTH = 640, //Original 640
 	ZGI_WORKING_WINDOW_HEIGHT = 320,  //Original 320
 	
@@ -129,6 +129,14 @@ public:
 	 * edges of this Rectangle
 	 */
 	Common::Rect _workingWindow;
+	/**
+	 * A Rectangle in which the menu will be rendered.  
+	 * In the original game, this is always separate from the working window,
+	 * and thus may be rendered completely independently.
+	 * In the widescreen mod, this window may intersect the working window,
+	 * and thus must be composited and rendered within renderSceneToScreen().
+	 */
+	Common::Rect _menuArea;
 	const Graphics::PixelFormat _resourcePixelFormat;
 	const Graphics::PixelFormat _screenPixelFormat;
 


Commit: 1db616d58d2238ca2adcfdd77efcbb1e3c74417a
    https://github.com/scummvm/scummvm/commit/1db616d58d2238ca2adcfdd77efcbb1e3c74417a
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:53+02:00

Commit Message:
ZVISION: Improve scroller code.
Add LinearScroller class.

Changed paths:
    engines/zvision/scripting/scroller.cpp
    engines/zvision/scripting/scroller.h


diff --git a/engines/zvision/scripting/scroller.cpp b/engines/zvision/scripting/scroller.cpp
index ad2540186b8..fca33a2de1e 100644
--- a/engines/zvision/scripting/scroller.cpp
+++ b/engines/zvision/scripting/scroller.cpp
@@ -23,57 +23,106 @@
 
 namespace ZVision {
 
-Scroller::Scroller(const Common::Point &activePos, const Common::Point &idlePos, int16 period) :
-  _activePos(activePos), 
+LinearScroller::LinearScroller(const int16 activePos, const int16 idlePos, const int16 period) :
+  Pos(idlePos),
+  prevPos(idlePos),
+  _activePos(activePos),
   _idlePos(idlePos),
+  deltaPos((int16)(activePos-idlePos)),
   _period(period) {
-  deltaPos = _activePos - _idlePos;
-	Pos = _idlePos;
-	prevPos = Pos;
 }
 
-Scroller::~Scroller() {
+LinearScroller::~LinearScroller() {
 }
 
-bool Scroller::update(uint32 deltatime) {
+bool LinearScroller::update(uint32 deltatime) {
   prevPos = Pos;
+  if(_period != 0)
+    {
+    int16 targetPos;
+	  float dPos=0;
+	  
+	  if (_active)
+	    targetPos = _activePos;
+    else
+    	targetPos = _idlePos;
 
-  Common::Point targetPos;
-	float dx=0;
-	float dy=0;
-	
-	if (active)
-	  targetPos = _activePos;
-  else
-  	targetPos = _idlePos;
-
-  if (Pos.x != targetPos.x) {
-    dx = (deltaPos.x * deltatime) / _period;
-    if(dx == 0)
-      dx = 1;
-  }
-  if (Pos.y != targetPos.y) {
-    dy = (deltaPos.y * deltatime) / _period;
-    if(dy == 0)
-      dy = 1;
-  }
-  
-  if(!active) {
-    dx = -dx;
-    dy = -dy;
-  }
-  
-  Pos.x += (int)dx;
-  if( (dx == 0) || ( (dx > 0) && (Pos.x > targetPos.x) ) || ( (dx < 0) && (Pos.x < targetPos.x) ) )
-    Pos.x = targetPos.x;
+    if (Pos != targetPos) {
+      dPos = (float)((int32)deltatime * (int32)deltaPos) / _period;
+      if((int16)dPos == 0) {
+        if(deltaPos > 0)
+          dPos = 1;
+        else
+          dPos = -1;
+      }
+    }
     
-  Pos.y += (int)dy;
-  if( (dy == 0) || ( (dy > 0) && (Pos.y > targetPos.y) ) || ( (dy < 0) && (Pos.y < targetPos.y) ) )
-    Pos.y = targetPos.y;
-	
-	scrolled = (Pos == _activePos);
-
+    if(!_active)
+      dPos = -dPos;
+    
+    Pos += (int16)dPos;
+    if( (dPos == 0) || ( (dPos > 0) && (Pos > targetPos) ) || ( (dPos < 0) && (Pos < targetPos) ) )
+      Pos = targetPos;
+    moving = (Pos != targetPos);
+  }
+  else {
+    if(_active)
+      Pos = _activePos;
+    else
+      Pos = _idlePos;
+    moving = false;
+  } 
 	return (Pos != prevPos);  //True if redraw necessary
 }
 
+void LinearScroller::reset() {
+  setActive(false);
+  Pos = _idlePos;
+}
+
+void LinearScroller::setActive(bool active) {
+  _active = active;
+}
+
+bool LinearScroller::isMoving() {
+  return moving;
+}
+
+
+Scroller::Scroller(const Common::Point &activePos, const Common::Point &idlePos, int16 period) :
+  Xscroller(activePos.x,idlePos.x,period), 
+  Yscroller(activePos.y,idlePos.y,period) {
+  Pos.x = Xscroller.Pos;
+  Pos.y = Yscroller.Pos;
+}
+
+Scroller::~Scroller() {
+}
+
+void Scroller::reset() {
+  Xscroller.reset();
+  Yscroller.reset();
+};
+
+
+void Scroller::setActive(bool active) {
+  Xscroller.setActive(active);
+  Yscroller.setActive(active);
+}
+
+bool Scroller::isMoving() {
+  return Xscroller.isMoving() | Yscroller.isMoving();
+}
+
+bool Scroller::update(uint32 deltatime) {
+  bool redraw = false;
+  if(Xscroller.update(deltatime))
+    redraw = true; 
+  if(Yscroller.update(deltatime))
+    redraw = true;
+  Pos.x = Xscroller.Pos;
+  Pos.y = Yscroller.Pos;
+	return (redraw);
+}
+
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/scroller.h b/engines/zvision/scripting/scroller.h
index c6f40b22e3b..d1ba89bab00 100644
--- a/engines/zvision/scripting/scroller.h
+++ b/engines/zvision/scripting/scroller.h
@@ -27,22 +27,40 @@
 
 namespace ZVision {
 
+class LinearScroller {
+public:
+  LinearScroller(const int16 activePos, const int16 idlePos, const int16 period = 500);
+  ~LinearScroller();
+  void reset();
+  bool update(uint32 deltatime);  //Calculate updated position of scrolled graphics; return true if redraw is necessary.
+  void setActive(bool active);
+  bool isMoving();
+  int16 getPos();
+
+	int16 Pos;
+	int16 prevPos;
+
+private:
+  bool _active = false;
+  bool moving = false;
+  const int16 _activePos;
+  const int16 _idlePos;
+	const int16 deltaPos;
+  const int16 _period;
+};
+
 class Scroller {
 public:
   Scroller(const Common::Point &activePos, const Common::Point &idlePos, const int16 period = 500);
   ~Scroller();
+  void reset();
   bool update(uint32 deltatime);  //Calculate updated position of scrolled graphics; return true if redraw is necessary.
-
+  void setActive(bool active);
+  bool isMoving();
 	Common::Point Pos;
-	Common::Point prevPos;
 
-  bool active = false;
-	bool scrolled = false;  //True when menu is in full active position
 private:
-  const Common::Point _activePos;
-  const Common::Point _idlePos;
-	Common::Point deltaPos;
-  const int16 _period;
+  LinearScroller Xscroller, Yscroller;
 };
 
 } // End of namespace ZVision


Commit: 422b72dc78bdcbdd1d344d7d64075375ad269ea8
    https://github.com/scummvm/scummvm/commit/422b72dc78bdcbdd1d344d7d64075375ad269ea8
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:54+02:00

Commit Message:
ZVISION: Amend erroneous ZGI working window height.

Changed paths:
    engines/zvision/zvision.h


diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index 3cecdbe7232..06df44aa623 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -82,14 +82,14 @@ enum {
 	ZNM_WORKING_WINDOW_HEIGHT = 320,  //Original 320
 	
 	ZNM_SUBTITLE_HEIGHT = 80, //Original 80
-	ZNM_MENU_HEIGHT = 40,  //Original 80
+	ZNM_MENU_HEIGHT = 32,  //Original 80
 
 	// ZGI working window sizes (original aspect ratio 2:1)
 	ZGI_WORKING_WINDOW_WIDTH = 640, //Original 640
-	ZGI_WORKING_WINDOW_HEIGHT = 320,  //Original 320
+	ZGI_WORKING_WINDOW_HEIGHT = 344,  //Original 344
 	
   ZGI_SUBTITLE_HEIGHT = 68, //Original 68
-	ZGI_MENU_HEIGHT = 34,  //Original 68
+	ZGI_MENU_HEIGHT = 32,  //Original 68
 
 	ROTATION_SCREEN_EDGE_OFFSET = 60,
 	MAX_ROTATION_SPEED = 400, // Pixels per second


Commit: dcbb155f8b61c8259eadb5c2bff12450a6866e35
    https://github.com/scummvm/scummvm/commit/dcbb155f8b61c8259eadb5c2bff12450a6866e35
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:54+02:00

Commit Message:
ZVISION: Menu code rework to minimise code duplication & support widescreen.
Widescreen support functionality added to ZGI menu code.
Menus may now overlap each other and the playfield in both ZGI and Nemesis.
Possible bug introduced: when entering inventory screen, noticeable delay before items render.
Panning is automatically paused whilst mouse is in menu area.

Changed paths:
    engines/zvision/core/events.cpp
    engines/zvision/scripting/menu.cpp
    engines/zvision/scripting/menu.h


diff --git a/engines/zvision/core/events.cpp b/engines/zvision/core/events.cpp
index 2a0b5095e1f..1dfb97f717b 100644
--- a/engines/zvision/core/events.cpp
+++ b/engines/zvision/core/events.cpp
@@ -168,7 +168,7 @@ void ZVision::processEvents() {
 		case Common::EVENT_LBUTTONDOWN:
 			_cursorManager->cursorDown(true);
 			_menu->onMouseDown(_event.mouse);
-			if(!_menu->isInMenu() || !_widescreen) {
+			if(!_menu->inMenu() || !_widescreen) {
 			  _scriptManager->setStateValue(StateKey_LMouse, 1);
 			  _scriptManager->addEvent(_event);
 		  }
@@ -177,7 +177,7 @@ void ZVision::processEvents() {
 		case Common::EVENT_LBUTTONUP:
 			_cursorManager->cursorDown(false);
 			_menu->onMouseUp(_event.mouse);
-			if(!_menu->isInMenu() || !_widescreen) {
+			if(!_menu->inMenu() || !_widescreen) {
 			  _scriptManager->setStateValue(StateKey_LMouse, 0);
 			  _scriptManager->addEvent(_event);
       }
@@ -185,7 +185,7 @@ void ZVision::processEvents() {
 
 		case Common::EVENT_RBUTTONDOWN:
 			_cursorManager->cursorDown(true);
-			if(!_menu->isInMenu() || !_widescreen) {
+			if(!_menu->inMenu() || !_widescreen) {
 			  _scriptManager->setStateValue(StateKey_RMouse, 1);
 
 			  if (getGameId() == GID_NEMESIS)
@@ -195,7 +195,7 @@ void ZVision::processEvents() {
 
 		case Common::EVENT_RBUTTONUP:
 			_cursorManager->cursorDown(false);
-			if(!_menu->isInMenu() || !_widescreen) {
+			if(!_menu->inMenu() || !_widescreen) {
   			_scriptManager->setStateValue(StateKey_RMouse, 0);
 			}
 			break;
@@ -223,22 +223,26 @@ void ZVision::processEvents() {
 				break;
 
 			case kZVisionActionSave:
-				if (_menu->getEnable() & kMenubarSave)
+				//if (_menu->getEnable() & kMenubarSave)
+				if (_menu->getEnable(kMainMenuSave))		
 					_scriptManager->changeLocation('g', 'j', 's', 'e', 0);
 				break;
 
 			case kZVisionActionRestore:
-				if (_menu->getEnable() & kMenubarRestore)
+				//if (_menu->getEnable() & kMenubarRestore)
+				if (_menu->getEnable(kMainMenuLoad))		
 					_scriptManager->changeLocation('g', 'j', 'r', 'e', 0);
 				break;
 
 			case kZVisionActionPreferences:
-				if (_menu->getEnable() & kMenubarSettings)
+				//if (_menu->getEnable() & kMenubarSettings)
+				if (_menu->getEnable(kMainMenuPrefs))		
 					_scriptManager->changeLocation('g', 'j', 'p', 'e', 0);
 				break;
 
 			case kZVisionActionQuit:
-				if (_menu->getEnable() & kMenubarExit)
+				//if (_menu->getEnable() & kMenubarExit)
+				if (_menu->getEnable(kMainMenuExit))				
 					ifQuit();
 				break;
 
@@ -327,7 +331,7 @@ void ZVision::onMouseMove(const Common::Point &pos) {
 	Common::Point clippedPos = pos;
 	clippedPos.x = CLIP<int16>(pos.x, _workingWindow.left + 1, _workingWindow.right - 1);
 
-	if (_workingWindow.contains(clippedPos) && !_menu->isInMenu()) {
+	if (_workingWindow.contains(clippedPos) && !_menu->inMenu()) {
 		cursorWasChanged = _scriptManager->onMouseMove(clippedPos, imageCoord);
 
 		RenderTable::RenderState renderState = _renderManager->getRenderTable()->getRenderState();
diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index 6c544259d4a..dd1aae34958 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -22,688 +22,578 @@
 #include "zvision/graphics/render_manager.h"
 #include "zvision/scripting/menu.h"
 
+//FOR BUG TEST ONLY
+//#include "common/debug.h"
+
 namespace ZVision {
 
 enum {
-	kMainMenuSave = 0,
-	kMainMenuLoad = 1,
-	kMainMenuPrefs = 2,
-	kMainMenuExit = 3
+  kFocusNone = -1,
+	kFocusItems = 0,
+	kFocusMagic = 1,
+	kFocusMain = 2
 };
 
-enum {
-	kMenuItem = 0,
-	kMenuMagic = 1,
-	kMenuMain = 2
+MenuHandler::MenuHandler(ZVision *engine, const Common::Rect menuArea, const MenuParams params) :
+	_engine{engine},
+  _params{params},
+	menuBarFlag{0xFFFF},
+	_menuArea{menuArea},
+  menuOrigin{menuArea.left,menuArea.top},
+  menuTriggerArea{menuOrigin,_menuArea.width(),_params.triggerHeight},
+  mainScroller{params.activePos, params.idlePos, params.period} {
+	
+	enableFlags.set_size(6);
+  for(int8 i = 0; i < 4; i++) {
+	  //Generate button hotspot areas
+	  menuHotspots[i] = Common::Rect(_params.wxButs[i][1], _menuArea.top, _params.wxButs[i][1]+_params.wxButs[i][0], _menuArea.bottom);
+    //Initialise button animation frames
+    mainFrames[i] = _params.idleFrame;
+	}
+	for (int i = 0; i < 4; i++)
+    buttonAnim[i] = new LinearScroller(_params.activeFrame,_params.idleFrame,_params.buttonPeriod);
+	menuFocus.push_back(kFocusNone);
+	mainArea = Common::Rect(_params.wMain,hMainMenu);
+	mainArea.moveTo(menuOrigin+mainScroller.Pos);
+}
+
+MenuHandler::~MenuHandler() {
+	for (int i = 0; i < 4; i++)
+	  delete buttonAnim[i];
+	mainBack.free();
+}
+
+void MenuHandler::setEnable(uint16 flags) {
+	  static const uint16 flagMasks[6] = {0x8,0x4,0x2,0x1,0x100,0x200};  //Enum order: save,restore,prefs,quit,items,magic
+		menuBarFlag = flags;
+		for(uint i=0; i<=5; i++) {
+      if(menuBarFlag & flagMasks[i])
+        enableFlags.set(i);
+      else
+        enableFlags.unset(i);
+    }		  
+	}
+
+void MenuHandler::onMouseUp(const Common::Point &Pos) {
+  if(menuFocus.front() == kFocusMain) {
+    mouseOnItem = mouseOverMain(Pos);
+    if(mouseOnItem == mainClicked)
+      //Activate clicked action from main menu
+      switch(mouseOnItem) {
+        case kMainMenuSave:
+		      _engine->getScriptManager()->changeLocation('g', 'j', 's', 'e', 0);
+		      setFocus(kFocusNone);
+		      mainScroller.reset();
+		      redraw = true;
+		      break;
+	      case kMainMenuLoad:
+		      _engine->getScriptManager()->changeLocation('g', 'j', 'r', 'e', 0);
+		      setFocus(kFocusNone);
+		      mainScroller.reset();
+		      redraw = true;
+		      break;
+        case kMainMenuPrefs:
+		      _engine->getScriptManager()->changeLocation('g', 'j', 'p', 'e', 0);
+		      setFocus(kFocusNone);
+		      mainScroller.reset();
+		      redraw = true;
+	        break;
+        case kMainMenuExit:
+		      _engine->ifQuit();
+		      break;
+	      default:
+	        break;
+      }
+  }
+  mainClicked = -1;
+}
+
+void MenuHandler::onMouseDown(const Common::Point &Pos) {
+  if(menuFocus.front() == kFocusMain) {
+    mouseOnItem = mouseOverMain(Pos);
+    //Show clicked graphic
+    if((mouseOnItem>=0) && (mouseOnItem<4))
+      if(enableFlags.get(mouseOnItem)) {
+        mainClicked = mouseOnItem;
+        redraw = true;
+      }
+  }
+  debug("mouse position %d %d", Pos.x, Pos.y);
+}
+
+void MenuHandler::onMouseMove(const Common::Point &Pos) {
+  bool nowInMenu = inMenu(Pos);
+  if(nowInMenu != prevInMenu)
+    redraw = true;
+  prevInMenu = nowInMenu;
+    
+	int lastItem = mouseOnItem;
+  
+  switch(menuFocus.front()) {
+    case kFocusMain:
+      //Inform game scripting engine that mouse is in main menu
+	    if(_engine->getScriptManager()->getStateValue(StateKey_MenuState) != 2)
+		    _engine->getScriptManager()->setStateValue(StateKey_MenuState, 2);
+      mouseOnItem = mouseOverMain(Pos);
+	    break;
+	  case kFocusNone:
+		  //Inform game scripting engine that mouse is not in any menu
+		  if(_engine->getScriptManager()->getStateValue(StateKey_MenuState) != 0)
+			  _engine->getScriptManager()->setStateValue(StateKey_MenuState, 0);
+		  mouseOnItem = -1;
+		  break;
+	}
+  mainScroller.setActive(menuFocus.front()==kFocusMain);
+  //Update button animation status
+  for (int i = 0; i < 4; i++)
+    if(menuFocus[0] == kFocusMain && mouseOnItem == i)
+      buttonAnim[i]->setActive(true);
+    else
+ 	    buttonAnim[i]->setActive(false);
+  if(lastItem != mouseOnItem)
+    redraw = true;
+}
+
+int MenuHandler::mouseOverMain(const Common::Point &Pos) {
+  //Common::Rect mainHotspot(28,hSideMenu);
+  //mainHotspot.moveTo(mainOrigin + mainScroller.Pos);
+  for(int8 i = 0; i < 4; i++) {
+    if(enableFlags.get(i) && menuHotspots[i].contains(Pos))
+      return i;
+  }
+  return -1;
+}
+
+void MenuHandler::process(uint32 deltatime) {
+	if(mainScroller.update(deltatime)) {
+	  mainArea.moveTo(menuOrigin+mainScroller.Pos);
+    for (int i = 0; i < 4; i++)
+      menuHotspots[i].moveTo(_menuArea.left + _params.wxButs[i][1], _menuArea.top + mainScroller.Pos.y);
+		redraw = true;
+	}
+  //Update button highlight animation frame
+  for(int i = 0; i < 4; i++)
+    if(buttonAnim[i]->update(deltatime)) {
+      mainFrames[i] = buttonAnim[i]->Pos;
+      redraw = true;
+    }
+	if(redraw) {
+	  _engine->getRenderManager()->clearMenuSurface(colorkey);
+  	redrawAll();
+  	redraw = false;
+  }
+};
+
+void MenuNemesis::redrawAll() {
+  redrawMain();
 };
 
-MenuHandler::MenuHandler(ZVision *engine, const Common::Rect menuArea) {
-	_engine = engine;
-	menuBarFlag = 0xFFFF;
-	_menuArea = menuArea; //Area in which menu is drawn
-	_menuTriggerArea = menuArea;  //Area in which mouse triggers menu scrolldown
+void MenuHandler::redrawMain() {
+  //Draw menu background
+  _engine->getRenderManager()->blitSurfaceToMenu(mainBack, mainScroller.Pos.x, mainScroller.Pos.y, 0);
+  //Draw buttons
+  if(menuFocus.front() == kFocusMain)
+    for(int8 i = 0; i < 4; i++) {
+      if(enableFlags.get(i) && (mainFrames[i]>=0)) {
+        if(mainClicked == i)
+	        _engine->getRenderManager()->blitSurfaceToMenu(mainButtons[i][_params.clickedFrame], _params.wxButs[i][1], mainScroller.Pos.y, 0);        
+        else
+	        _engine->getRenderManager()->blitSurfaceToMenu(mainButtons[i][mainFrames[i]], _params.wxButs[i][1], mainScroller.Pos.y, 0);
+      }
+    }
+  clean = false;
 }
 
-MenuZGI::MenuZGI(ZVision *engine, const Common::Rect menuArea) :
-	MenuHandler(engine, menuArea) {
-	menuMouseFocus = -1;
-	menuActive = false;
-	scrolled[0] = false;
-	scrolled[1] = false;
-	scrolled[2] = false;
-	scrollPos[0] = 0;
-	scrollPos[1] = 0;
-	scrollPos[2] = 0;
-	mouseOnItem = -1;
-	redraw = false;
-	clean = false;
+void MenuHandler::setFocus(int8 currentFocus) {
+  if(menuFocus.front() != currentFocus) {
+    Common::Array<int8> _menuFocus;
+    while(menuFocus.size() > 0) {
+      if(menuFocus.back() != currentFocus)
+        _menuFocus.push_back(menuFocus.back());
+      menuFocus.pop_back();
+    }
+    menuFocus.push_back(currentFocus);
+    while(_menuFocus.size() > 0) {
+      menuFocus.push_back(_menuFocus.back());
+      _menuFocus.pop_back();
+    }
+  }
+  assert(menuFocus.size() <= 4);
+}
 
+MenuZGI::MenuZGI(ZVision *engine, const Common::Rect menuArea) :
+	MenuHandler(engine, menuArea, zgiParams),
+	itemsScroller{Common::Point(0,0), Common::Point(wSideMenuTab-wSideMenu,0), 1000},
+	magicScroller{Common::Point(-wSideMenu,0), Common::Point(-wSideMenuTab,0), 1000},
+	itemsOrigin{menuArea.left, menuArea.top},
+	magicOrigin{menuArea.right, menuArea.top} {
+
+  magicArea = Common::Rect(magicOrigin + magicScroller.Pos, wSideMenu, hSideMenu);
+  itemsArea = Common::Rect(itemsOrigin + itemsScroller.Pos, wSideMenu, hSideMenu);
+	
+  //Buffer main menu background
+	_engine->getRenderManager()->readImageToSurface("gmzau031.tga", mainBack, false);
+	
 	char buf[24];
-	for (int i = 1; i < 4; i++) {
-		Common::sprintf_s(buf, "gmzau%2.2x1.tga", i);
-		_engine->getRenderManager()->readImageToSurface(buf, menuBack[i - 1][0], false);
-		Common::sprintf_s(buf, "gmzau%2.2x1.tga", i + 0x10);
-		_engine->getRenderManager()->readImageToSurface(buf, menuBack[i - 1][1], false);
-	}
 	for (int i = 0; i < 4; i++) {
+	  //Buffer menu buttons
 		Common::sprintf_s(buf, "gmzmu%2.2x1.tga", i);
-		_engine->getRenderManager()->readImageToSurface(buf, menuBar[i][0], false);
+		_engine->getRenderManager()->readImageToSurface(buf, mainButtons[i][0], false);
 		Common::sprintf_s(buf, "gmznu%2.2x1.tga", i);
-		_engine->getRenderManager()->readImageToSurface(buf, menuBar[i][1], false);
+		_engine->getRenderManager()->readImageToSurface(buf, mainButtons[i][1], false);
+	}
+	for (int i = 1; i < 4; i++) {
+	  //Buffer full menu backgrounds
+		Common::sprintf_s(buf, "gmzau%2.2x1.tga", i);
+		_engine->getRenderManager()->readImageToSurface(buf, menuBack[i - 1], false);
 	}
-
 	for (int i = 0; i < 50; i++) {
 		items[i][0] = NULL;
 		items[i][1] = NULL;
 		itemId[i] = 0;
 	}
-
 	for (int i = 0; i < 12; i++) {
 		magic[i][0] = NULL;
 		magic[i][1] = NULL;
 		magicId[i] = 0;
 	}
+	//Initialise focus sequence
+  setFocus(kFocusMain);
+  setFocus(kFocusMagic);
+  setFocus(kFocusItems);
+  setFocus(kFocusNone);
 }
 
 MenuZGI::~MenuZGI() {
-	for (int i = 0; i < 3; i++) {
-		menuBack[i][0].free();
-		menuBack[i][1].free();
-	}
-	for (int i = 0; i < 4; i++) {
-		menuBar[i][0].free();
-		menuBar[i][1].free();
-	}
+	for (int i = 0; i < 3; i++)
+		menuBack[i].free();
+		
+	for (int i = 0; i < 4; i++)
+    for(int j = 0; j < 2; j++)
+		  mainButtons[i][j].free();
+		  
 	for (int i = 0; i < 50; i++) {
-		if (items[i][0]) {
+		if(items[i][0]) {
 			items[i][0]->free();
 			delete items[i][0];
 		}
-		if (items[i][1]) {
+		if(items[i][1]) {
 			items[i][1]->free();
 			delete items[i][1];
 		}
 	}
 	for (int i = 0; i < 12; i++) {
-		if (magic[i][0]) {
+		if(magic[i][0]) {
 			magic[i][0]->free();
 			delete magic[i][0];
 		}
-		if (magic[i][1]) {
+		if(magic[i][1]) {
 			magic[i][1]->free();
 			delete magic[i][1];
 		}
 	}
 }
 
+bool MenuZGI::inMenu(const Common::Point &Pos) {
+  return menuTriggerArea.contains(Pos) || (menuFocus.front() != kFocusNone);
+}
+
 void MenuZGI::onMouseUp(const Common::Point &Pos) {
-	if (Pos.y < 40) {
-		switch (menuMouseFocus) {
-		case kMenuItem:
-			if (menuBarFlag & kMenubarItems) {
-				int itemCount = _engine->getScriptManager()->getStateValue(StateKey_Inv_TotalSlots);
-				if (itemCount == 0)
-					itemCount = 20;
-
-				for (int i = 0; i < itemCount; i++) {
-					int itemspace = (600 - 28) / itemCount;
-
-					if (Common::Rect(scrollPos[kMenuItem] + itemspace * i, 0,
-					                 scrollPos[kMenuItem] + itemspace * i + 28, 32).contains(Pos)) {
-						int32 mouseItem = _engine->getScriptManager()->getStateValue(StateKey_InventoryItem);
-						if (mouseItem >= 0  && mouseItem < 0xE0) {
-							_engine->getScriptManager()->inventoryDrop(mouseItem);
-							_engine->getScriptManager()->inventoryAdd(_engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + i));
-							_engine->getScriptManager()->setStateValue(StateKey_Inv_StartSlot + i, mouseItem);
-
-							redraw = true;
-						}
-					}
-				}
-			}
-			break;
-
-		case kMenuMagic:
-			if (menuBarFlag & kMenubarMagic) {
-				for (int i = 0; i < 12; i++) {
-
-					uint itemnum = _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + i);
-					if (itemnum != 0) {
-						if (_engine->getScriptManager()->getStateValue(StateKey_Reversed_Spellbooc) == 1)
-							itemnum = 0xEE + i;
-						else
-							itemnum = 0xE0 + i;
-					}
-					if (itemnum)
-						if (_engine->getScriptManager()->getStateValue(StateKey_InventoryItem) == 0 || _engine->getScriptManager()->getStateValue(StateKey_InventoryItem) >= 0xE0)
-							if (Common::Rect(668 + 47 * i - scrollPos[kMenuMagic], 0,
-							                 668 + 47 * i - scrollPos[kMenuMagic] + 28, 32).contains(Pos))
-								_engine->getScriptManager()->setStateValue(StateKey_Active_Spell, itemnum);
-				}
-
-			}
-			break;
-
-		case kMenuMain:
-
-			// Exit
-			if (menuBarFlag & kMenubarExit)
-				if (Common::Rect(320 + 135,
-				                 scrollPos[kMenuMain],
-				                 320 + 135 + 135,
-				                 scrollPos[kMenuMain] + 32).contains(Pos)) {
-					_engine->ifQuit();
-				}
-
-			// Settings
-			if (menuBarFlag & kMenubarSettings)
-				if (Common::Rect(320 ,
-				                 scrollPos[kMenuMain],
-				                 320 + 135,
-				                 scrollPos[kMenuMain] + 32).contains(Pos)) {
-					_engine->getScriptManager()->changeLocation('g', 'j', 'p', 'e', 0);
-				}
-
-			// Load
-			if (menuBarFlag & kMenubarRestore)
-				if (Common::Rect(320 - 135,
-				                 scrollPos[kMenuMain],
-				                 320,
-				                 scrollPos[kMenuMain] + 32).contains(Pos)) {
-					_engine->getScriptManager()->changeLocation('g', 'j', 'r', 'e', 0);
-				}
-
-			// Save
-			if (menuBarFlag & kMenubarSave)
-				if (Common::Rect(320 - 135 * 2,
-				                 scrollPos[kMenuMain],
-				                 320 - 135,
-				                 scrollPos[kMenuMain] + 32).contains(Pos)) {
-					_engine->getScriptManager()->changeLocation('g', 'j', 's', 'e', 0);
-				}
-			break;
-
-		default:
-			break;
-		}
-	}
+	if(inMenu(Pos))
+	  //redraw = true;
+		switch (menuFocus.front()) {
+		  case kFocusItems:
+			  if(enableFlags.get(kItemsMenu)) {
+				  int itemCount = _engine->getScriptManager()->getStateValue(StateKey_Inv_TotalSlots);
+				  if(itemCount == 0)
+					  itemCount = 20;
+          int i = mouseOverItem(Pos,itemCount);
+          if(i != -1) {
+				    int32 mouseItem = _engine->getScriptManager()->getStateValue(StateKey_InventoryItem);
+				    if(mouseItem >= 0  && mouseItem < 0xE0) {
+					    _engine->getScriptManager()->inventoryDrop(mouseItem);
+					    _engine->getScriptManager()->inventoryAdd(_engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + i));
+					    _engine->getScriptManager()->setStateValue(StateKey_Inv_StartSlot + i, mouseItem);
+					    redraw = true;         
+            }
+          }
+		    }
+			  break;
+		  case kFocusMagic:
+			  if(enableFlags.get(kMagicMenu)) {
+			    int i = mouseOverMagic(Pos);
+			    if(i != -1) {
+				    uint itemnum = _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + i);
+				    if(itemnum != 0) {
+					    if(_engine->getScriptManager()->getStateValue(StateKey_Reversed_Spellbooc) == 1)
+						    itemnum = 0xEE + i;
+					    else
+						    itemnum = 0xE0 + i;
+					    }
+				    if(itemnum)
+					    if(_engine->getScriptManager()->getStateValue(StateKey_InventoryItem) == 0 || _engine->getScriptManager()->getStateValue(StateKey_InventoryItem) >= 0xE0)
+					      _engine->getScriptManager()->setStateValue(StateKey_Active_Spell, itemnum);
+			    }
+			  }
+			  break;
+		  case kFocusMain:
+        MenuHandler::onMouseUp(Pos);
+			  break;
+		  default:
+			  break;
+		  }
 }
 
 void MenuZGI::onMouseMove(const Common::Point &Pos) {
-	if (Pos.y < 40) {
-
-		if (!menuActive)
-			redraw = true;
-		menuActive = true;
-		switch (menuMouseFocus) {
-		case kMenuItem:
-			if (menuBarFlag & kMenubarItems) {
-				int itemCount = _engine->getScriptManager()->getStateValue(StateKey_Inv_TotalSlots);
-				if (itemCount == 0)
-					itemCount = 20;
-				else if (itemCount > 50)
-					itemCount = 50;
-
-				int lastItem = mouseOnItem;
-
-				mouseOnItem = -1;
-
-				for (int i = 0; i < itemCount; i++) {
-					int itemspace = (600 - 28) / itemCount;
-
-					if (Common::Rect(scrollPos[kMenuItem] + itemspace * i, 0,
-					                 scrollPos[kMenuItem] + itemspace * i + 28, 32).contains(Pos)) {
-						mouseOnItem = i;
-						break;
-					}
-				}
-
-				if (lastItem != mouseOnItem)
-					if (_engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + mouseOnItem) ||
-					        _engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + lastItem))
-						redraw = true;
-			}
-			break;
-
-		case kMenuMagic:
-			if (menuBarFlag & kMenubarMagic) {
-				int lastItem = mouseOnItem;
-				mouseOnItem = -1;
-				for (int i = 0; i < 12; i++) {
-					if (Common::Rect(668 + 47 * i - scrollPos[kMenuMagic], 0,
-					                 668 + 47 * i - scrollPos[kMenuMagic] + 28, 32).contains(Pos)) {
-						mouseOnItem = i;
-						break;
-					}
-				}
-
-				if (lastItem != mouseOnItem)
-					if (_engine->getScriptManager()->getStateValue(StateKey_Spell_1 + mouseOnItem) ||
-					        _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + lastItem))
-						redraw = true;
-
-			}
-			break;
-
-		case kMenuMain: {
-			int lastItem = mouseOnItem;
-			mouseOnItem = -1;
-
-			// Exit
-			if (menuBarFlag & kMenubarExit)
-				if (Common::Rect(320 + 135,
-				                 scrollPos[kMenuMain],
-				                 320 + 135 + 135,
-				                 scrollPos[kMenuMain] + 32).contains(Pos)) {
-					mouseOnItem = kMainMenuExit;
-				}
-
-			// Settings
-			if (menuBarFlag & kMenubarSettings)
-				if (Common::Rect(320 ,
-				                 scrollPos[kMenuMain],
-				                 320 + 135,
-				                 scrollPos[kMenuMain] + 32).contains(Pos)) {
-					mouseOnItem = kMainMenuPrefs;
-				}
-
-			// Load
-			if (menuBarFlag & kMenubarRestore)
-				if (Common::Rect(320 - 135,
-				                 scrollPos[kMenuMain],
-				                 320,
-				                 scrollPos[kMenuMain] + 32).contains(Pos)) {
-					mouseOnItem = kMainMenuLoad;
-				}
-
-			// Save
-			if (menuBarFlag & kMenubarSave)
-				if (Common::Rect(320 - 135 * 2,
-				                 scrollPos[kMenuMain],
-				                 320 - 135,
-				                 scrollPos[kMenuMain] + 32).contains(Pos)) {
-					mouseOnItem = kMainMenuSave;
-				}
-
-			if (lastItem != mouseOnItem)
-				redraw = true;
-		}
-		break;
-
-		default:
-			int cur_menu = menuMouseFocus;
-			if (Common::Rect(64, 0, 64 + 512, 8).contains(Pos)) { // Main
-				menuMouseFocus = kMenuMain;
-				scrolled[kMenuMain]  = false;
-				scrollPos[kMenuMain] = menuBack[kMenuMain][1].h - menuBack[kMenuMain][0].h;
-				_engine->getScriptManager()->setStateValue(StateKey_MenuState, 2);
-			}
-
-			if (menuBarFlag & kMenubarMagic)
-				if (Common::Rect(640 - 28, 0, 640, 32).contains(Pos)) { // Magic
-					menuMouseFocus = kMenuMagic;
-					scrolled[kMenuMagic]  = false;
-					scrollPos[kMenuMagic] = 28;
-					_engine->getScriptManager()->setStateValue(StateKey_MenuState, 3);
-				}
-
-			if (menuBarFlag & kMenubarItems)
-				if (Common::Rect(0, 0, 28, 32).contains(Pos)) { // Items
-					menuMouseFocus = kMenuItem;
-					scrolled[kMenuItem]  = false;
-					scrollPos[kMenuItem] = 28 - 600;
-					_engine->getScriptManager()->setStateValue(StateKey_MenuState, 1);
-				}
-
-			if (cur_menu != menuMouseFocus)
-				clean = true;
-
-			break;
-		}
-	} else {
-		if (menuActive)
-			clean = true;
-		menuActive = false;
-		if (_engine->getScriptManager()->getStateValue(StateKey_MenuState) != 0)
-			_engine->getScriptManager()->setStateValue(StateKey_MenuState, 0);
-		menuMouseFocus = -1;
-	}
+  if(!inMenu(Pos) && prevInMenu) {
+    mainScroller.reset();
+    magicScroller.reset();
+    itemsScroller.reset();
+  }
+
+  //Set focus to topmost layer of menus that mouse is currently over
+  for(uint8 i=0; i<menuFocus.size(); i++) {
+    switch(menuFocus[i]) {
+      case kFocusItems:
+        if(itemsArea.contains(Pos)) {
+          setFocus(kFocusItems);
+          i = menuFocus.size()+1;
+        }
+        break;
+      case kFocusMagic:
+        if(magicArea.contains(Pos)) {
+          setFocus(kFocusMagic);
+          i = menuFocus.size()+1;
+        }
+        break;
+      case kFocusMain:
+        if(mainArea.contains(Pos)) {
+          setFocus(kFocusMain);
+          i = menuFocus.size()+1;
+        }
+        break;
+      default:
+        setFocus(kFocusNone);
+        break;
+    }
+  }    
+  itemsScroller.setActive(menuFocus.front()==kFocusItems);
+  magicScroller.setActive(menuFocus.front()==kFocusMagic);  
+	if(menuFocus.front() != kFocusNone) {
+		switch (menuFocus.front()) {
+		  case kFocusItems:
+			  if(enableFlags.get(kItemsMenu)) {
+				  int itemCount = _engine->getScriptManager()->getStateValue(StateKey_Inv_TotalSlots);
+				  if(itemCount == 0)
+					  itemCount = 20;
+				  else if(itemCount > 50)
+					  itemCount = 50;					  
+				  int lastItem = mouseOnItem;
+			    mouseOnItem = mouseOverItem(Pos, itemCount);
+				  if(lastItem != mouseOnItem)
+					  if(_engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + mouseOnItem) || _engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + lastItem))
+						  redraw = true;
+			  }
+			  break;
+		  case kFocusMagic:
+			  if(enableFlags.get(kMagicMenu)) {
+				  int lastItem = mouseOnItem;
+			    mouseOnItem = mouseOverMagic(Pos);
+				  if(lastItem != mouseOnItem)
+					  if(_engine->getScriptManager()->getStateValue(StateKey_Spell_1 + mouseOnItem) || _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + lastItem))
+						  redraw = true;
+			  }
+			  break;
+		  case kFocusMain:
+		    break;
+    }
+	} 
+  MenuHandler::onMouseMove(Pos);
 }
 
-void MenuZGI::process(uint32 deltatime) {
-	if (clean) {
-		_engine->getRenderManager()->clearMenuSurface();
-		clean = false;
-	}
-	switch (menuMouseFocus) {
-	case kMenuItem:
-		if (menuBarFlag & kMenubarItems)
-			if (!scrolled[kMenuItem]) {
-				redraw = true;
-				float dScrl = 600.0 * (deltatime / 1000.0);
-
-				if (dScrl == 0)
-					dScrl = 1.0;
-
-				scrollPos[kMenuItem] += (int)dScrl;
-
-				if (scrollPos[kMenuItem] >= 0) {
-					scrolled[kMenuItem] = true;
-					scrollPos[kMenuItem] = 0;
-				}
-			}
-		if (redraw) {
-			_engine->getRenderManager()->blitSurfaceToMenu(menuBack[kMenuItem][0], scrollPos[kMenuItem], 0);
-
-			int itemCount = _engine->getScriptManager()->getStateValue(StateKey_Inv_TotalSlots);
-			if (itemCount == 0)
-				itemCount = 20;
-			else if (itemCount > 50)
-				itemCount = 50;
-
-			for (int i = 0; i < itemCount; i++) {
-				int itemspace = (600 - 28) / itemCount;
-
-				bool inrect = false;
-
-				if (mouseOnItem == i)
-					inrect = true;
-
-				uint curItemId = _engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + i);
-
-				if (curItemId != 0) {
-					if (itemId[i] != curItemId) {
-						char buf[16];
-						Common::sprintf_s(buf, "gmzwu%2.2x1.tga", curItemId);
-						items[i][0] = _engine->getRenderManager()->loadImage(buf, false);
-						Common::sprintf_s(buf, "gmzxu%2.2x1.tga", curItemId);
-						items[i][1] = _engine->getRenderManager()->loadImage(buf, false);
-						itemId[i] = curItemId;
-					}
-
-					if (inrect)
-						_engine->getRenderManager()->blitSurfaceToMenu(*items[i][1], scrollPos[kMenuItem] + itemspace * i, 0, 0);
-					else
-						_engine->getRenderManager()->blitSurfaceToMenu(*items[i][0], scrollPos[kMenuItem] + itemspace * i, 0, 0);
-
-				} else {
-					if (items[i][0]) {
-						items[i][0]->free();
-						delete items[i][0];
-						items[i][0] = NULL;
-					}
-					if (items[i][1]) {
-						items[i][1]->free();
-						delete items[i][1];
-						items[i][1] = NULL;
-					}
-					itemId[i] = 0;
-				}
-			}
-
-			redraw = false;
-		}
-		break;
-
-	case kMenuMagic:
-		if (menuBarFlag & kMenubarMagic)
-			if (!scrolled[kMenuMagic]) {
-				redraw = true;
-				float dScrl = 600.0 * (deltatime / 1000.0);
-
-				if (dScrl == 0)
-					dScrl = 1.0;
-
-				scrollPos[kMenuMagic] += (int)dScrl;
-
-				if (scrollPos[kMenuMagic] >= 600) {
-					scrolled[kMenuMagic] = true;
-					scrollPos[kMenuMagic] = 600;
-				}
-			}
-		if (redraw) {
-			_engine->getRenderManager()->blitSurfaceToMenu(menuBack[kMenuMagic][0], 640 - scrollPos[kMenuMagic], 0);
-
-			for (int i = 0; i < 12; i++) {
-				bool inrect = false;
-
-				if (mouseOnItem == i)
-					inrect = true;
-
-				uint curItemId = _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + i);
-				if (curItemId) {
-					if (_engine->getScriptManager()->getStateValue(StateKey_Reversed_Spellbooc) == 1)
-						curItemId = 0xEE + i;
-					else
-						curItemId = 0xE0 + i;
-				}
-
-				if (curItemId != 0) {
-					if (itemId[i] != curItemId) {
-						char buf[16];
-						Common::sprintf_s(buf, "gmzwu%2.2x1.tga", curItemId);
-						magic[i][0] = _engine->getRenderManager()->loadImage(buf, false);
-						Common::sprintf_s(buf, "gmzxu%2.2x1.tga", curItemId);
-						magic[i][1] = _engine->getRenderManager()->loadImage(buf, false);
-						magicId[i] = curItemId;
-					}
-
-					if (inrect)
-						_engine->getRenderManager()->blitSurfaceToMenu(*magic[i][1], 668 + 47 * i - scrollPos[kMenuMagic], 0, 0);
-					else
-						_engine->getRenderManager()->blitSurfaceToMenu(*magic[i][0], 668 + 47 * i - scrollPos[kMenuMagic], 0, 0);
-
-				} else {
-					if (magic[i][0]) {
-						magic[i][0]->free();
-						delete magic[i][0];
-						magic[i][0] = NULL;
-					}
-					if (magic[i][1]) {
-						magic[i][1]->free();
-						delete magic[i][1];
-						magic[i][1] = NULL;
-					}
-					magicId[i] = 0;
-				}
-			}
-			redraw = false;
-		}
-		break;
+int MenuZGI::mouseOverItem(const Common::Point &Pos, int itemCount) {
+  int itemWidth = (wSideMenu - 28) / itemCount;
+  Common::Rect itemHotspot = Common::Rect(28,hSideMenu);
+  itemHotspot.moveTo(itemsOrigin + itemsScroller.Pos);
+  for (int i = 0; i < itemCount; i++) {
+	  if(itemHotspot.contains(Pos))
+      return i;
+	  itemHotspot.translate(itemWidth,0);
+  }
+  return -1;
+};
+
+int MenuZGI::mouseOverMagic(const Common::Point &Pos) {
+  Common::Rect magicHotspot(28,hSideMenu);
+  magicHotspot.moveTo(magicOrigin + magicScroller.Pos);
+  magicHotspot.translate(28,0); //Offset from end of menu
+  for (int i = 0; i < 12; i++) {
+    if(magicHotspot.contains(Pos))
+      return i;
+  magicHotspot.translate(magicWidth,0);
+  }
+  return -1;
+};
 
-	case kMenuMain:
-		if (!scrolled[kMenuMain]) {
-			redraw = true;
-			float dScrl = 32.0 * 2.0 * (deltatime / 1000.0);
+void MenuZGI::process(uint32 deltatime) {
+	if(itemsScroller.update(deltatime)) {
+	  itemsArea.moveTo(itemsOrigin+itemsScroller.Pos);
+	  redraw = true;
+  }
+  if(magicScroller.update(deltatime)) {
+	  magicArea.moveTo(magicOrigin+magicScroller.Pos);
+	  redraw = true;
+  }
+  MenuHandler::process(deltatime);
+}
 
-			if (dScrl == 0)
-				dScrl = 1.0;
+void MenuZGI::redrawAll() {
+  if(MenuHandler::inMenu())
+    for(int8 i=menuFocus.size()-1; i>=0; i--)
+      switch (menuFocus[i]) {
+        case kFocusItems:
+          if(enableFlags.get(kItemsMenu)) {
+            redrawItems();
+          }
+    	    break;
+        case kFocusMagic:
+          if(enableFlags.get(kMagicMenu)) {
+            redrawMagic();
+          }
+	        break;
+        case kFocusMain:
+          redrawMain(); 
+	        break;
+        default:
+	        break;
+      }
+};
 
-			scrollPos[kMenuMain] += (int)dScrl;
+void MenuZGI::redrawMagic() {
+  const int16 yOrigin = _menuArea.width();
+  _engine->getRenderManager()->blitSurfaceToMenu(menuBack[kFocusMagic], yOrigin+magicScroller.Pos.x, 0, 0);
+  for (int i = 0; i < 12; i++) {
+    bool inrect = false;
+    if(mouseOnItem == i)
+	    inrect = true;
+    uint curItemId = _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + i);
+    if(curItemId) {
+	    if(_engine->getScriptManager()->getStateValue(StateKey_Reversed_Spellbooc) == 1)
+		    curItemId = 0xEE + i;
+	    else
+		    curItemId = 0xE0 + i;
+    }
+    if(curItemId != 0) {
+	    if(itemId[i] != curItemId) {
+		    char buf[16];
+		    Common::sprintf_s(buf, "gmzwu%2.2x1.tga", curItemId);
+		    magic[i][0] = _engine->getRenderManager()->loadImage(buf, false);
+		    Common::sprintf_s(buf, "gmzxu%2.2x1.tga", curItemId);
+		    magic[i][1] = _engine->getRenderManager()->loadImage(buf, false);
+		    magicId[i] = curItemId;
+	    }
+	    if(inrect)
+		    _engine->getRenderManager()->blitSurfaceToMenu(*magic[i][1], yOrigin + magicScroller.Pos.x + 28 + magicWidth*i, 0, 0);
+	    else
+		    _engine->getRenderManager()->blitSurfaceToMenu(*magic[i][0], yOrigin + magicScroller.Pos.x + 28 + magicWidth*i, 0, 0);
+    } 
+    else {
+	    if(magic[i][0]) {
+		    magic[i][0]->free();
+		    delete magic[i][0];
+		    magic[i][0] = NULL;
+	    }
+	    if(magic[i][1]) {
+		    magic[i][1]->free();
+		    delete magic[i][1];
+		    magic[i][1] = NULL;
+	    }
+	    magicId[i] = 0;
+    }
+  }
+  clean = false;
+}
 
-			if (scrollPos[kMenuMain] >= 0) {
-				scrolled[kMenuMain] = true;
-				scrollPos[kMenuMain] = 0;
-			}
-		}
-		if (redraw) {
-			_engine->getRenderManager()->blitSurfaceToMenu(menuBack[kMenuMain][0], 30, scrollPos[kMenuMain]);
-
-			if (menuBarFlag & kMenubarExit) {
-				if (mouseOnItem == kMainMenuExit)
-					_engine->getRenderManager()->blitSurfaceToMenu(menuBar[kMainMenuExit][1], 320 + 135, scrollPos[kMenuMain]);
-				else
-					_engine->getRenderManager()->blitSurfaceToMenu(menuBar[kMainMenuExit][0], 320 + 135, scrollPos[kMenuMain]);
-			}
-			if (menuBarFlag & kMenubarSettings) {
-				if (mouseOnItem == kMainMenuPrefs)
-					_engine->getRenderManager()->blitSurfaceToMenu(menuBar[kMainMenuPrefs][1], 320, scrollPos[kMenuMain]);
-				else
-					_engine->getRenderManager()->blitSurfaceToMenu(menuBar[kMainMenuPrefs][0], 320, scrollPos[kMenuMain]);
-			}
-			if (menuBarFlag & kMenubarRestore) {
-				if (mouseOnItem == kMainMenuLoad)
-					_engine->getRenderManager()->blitSurfaceToMenu(menuBar[kMainMenuLoad][1], 320 - 135, scrollPos[kMenuMain]);
-				else
-					_engine->getRenderManager()->blitSurfaceToMenu(menuBar[kMainMenuLoad][0], 320 - 135, scrollPos[kMenuMain]);
-			}
-			if (menuBarFlag & kMenubarSave) {
-				if (mouseOnItem == kMainMenuSave)
-					_engine->getRenderManager()->blitSurfaceToMenu(menuBar[kMainMenuSave][1], 320 - 135 * 2, scrollPos[kMenuMain]);
-				else
-					_engine->getRenderManager()->blitSurfaceToMenu(menuBar[kMainMenuSave][0], 320 - 135 * 2, scrollPos[kMenuMain]);
-			}
-			redraw = false;
-		}
-		break;
-	default:
-		if (redraw) {
-			if (menuActive) {
-				_engine->getRenderManager()->blitSurfaceToMenu(menuBack[kMenuMain][1], 30, 0);
-
-				if (menuBarFlag & kMenubarItems)
-					_engine->getRenderManager()->blitSurfaceToMenu(menuBack[kMenuItem][1], 0, 0);
-
-				if (menuBarFlag & kMenubarMagic)
-					_engine->getRenderManager()->blitSurfaceToMenu(menuBack[kMenuMagic][1], 640 - 28, 0);
-			}
-			redraw = false;
-		}
-		break;
-	}
+void MenuZGI::redrawItems() {
+  _engine->getRenderManager()->blitSurfaceToMenu(menuBack[kFocusItems], itemsScroller.Pos.x, 0, 0);
+  int itemCount = _engine->getScriptManager()->getStateValue(StateKey_Inv_TotalSlots);
+  if(itemCount == 0)
+    itemCount = 20;
+  else if(itemCount > 50)
+    itemCount = 50;
+  int itemWidth = (wSideMenu - 28) / itemCount;
+
+  for (int i = 0; i < itemCount; i++) {
+    bool inrect = false;
+    if(mouseOnItem == i)
+	    inrect = true;
+    uint curItemId = _engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + i);
+
+    if(curItemId != 0) {
+	    if(itemId[i] != curItemId) {
+		    char buf[16];
+		    Common::sprintf_s(buf, "gmzwu%2.2x1.tga", curItemId);
+		    items[i][0] = _engine->getRenderManager()->loadImage(buf, false);
+		    Common::sprintf_s(buf, "gmzxu%2.2x1.tga", curItemId);
+		    items[i][1] = _engine->getRenderManager()->loadImage(buf, false);
+		    itemId[i] = curItemId;
+	    }
+	    if(inrect)
+		    _engine->getRenderManager()->blitSurfaceToMenu(*items[i][1], itemsScroller.Pos.x + itemWidth*i, 0, 0);
+	    else
+		    _engine->getRenderManager()->blitSurfaceToMenu(*items[i][0], itemsScroller.Pos.x + itemWidth*i, 0, 0);
+    } else {
+	    if(items[i][0]) {
+		    items[i][0]->free();
+		    delete items[i][0];
+		    items[i][0] = NULL;
+	    }
+	    if(items[i][1]) {
+		    items[i][1]->free();
+		    delete items[i][1];
+		    items[i][1] = NULL;
+	    }
+	    itemId[i] = 0;
+    }
+  }
+  clean = false;
 }
 
 MenuNemesis::MenuNemesis(ZVision *engine, const Common::Rect menuArea) :
-	MenuHandler(engine, menuArea),
-	menuScroller(Common::Point(0,0), Common::Point(0,-32)) {
-	mouseOnItem = -1;
-	redraw = false;
-	delay = 0;
+	MenuHandler(engine, menuArea, nemesisParams) {
 
+  //Buffer menu background image
+	_engine->getRenderManager()->readImageToSurface("bar.tga", mainBack, false);
+	
 	char buf[24];
 	for (int i = 0; i < 4; i++) {
-    //Buffer button images
+    //Buffer menu buttons
 		for (int j = 0; j < 6; j++) {
 			Common::sprintf_s(buf, "butfrm%d%d.tga", i + 1, j);
-			_engine->getRenderManager()->readImageToSurface(buf, but[i][j], false);
+			_engine->getRenderManager()->readImageToSurface(buf, mainButtons[i][j], false);
 		}
-		//Generate button hotspot areas
-		hotspots[i] = Common::Rect(wxButs[i][1], _menuArea.top, wxButs[i][1]+wxButs[i][0], _menuArea.bottom);
 	}
-
-  //Buffer menubar image
-	_engine->getRenderManager()->readImageToSurface("bar.tga", menuBar, false);
-
-	frm = 0;
 }
 
 MenuNemesis::~MenuNemesis() {
-	for (int i = 0; i < 4; i++)
+	for (int i = 0; i < 4; i++) {
 		for (int j = 0; j < 6; j++)
-			but[i][j].free();
-
-	menuBar.free();
+			mainButtons[i][j].free();
+	};
 }
 
-void MenuNemesis::onMouseUp(const Common::Point &Pos) {
-  inMenu = _menuArea.contains(Pos);
-
-	if (_menuTriggerArea.contains(Pos)) {
-		// Exit
-		if (menuBarFlag & kMenubarExit)
-		  if (hotspots[3].contains(Pos)) {
-				_engine->ifQuit();
-				frm = 5;
-				redraw = true;
-			}
-		// Prefs
-		if (menuBarFlag & kMenubarSettings)
-		  if (hotspots[2].contains(Pos)) {
-				_engine->getScriptManager()->changeLocation('g', 'j', 'p', 'e', 0);
-				frm = 5;
-				redraw = true;
-			}
-		// Restore
-		if (menuBarFlag & kMenubarRestore)
-		  if (hotspots[1].contains(Pos)) {
-				_engine->getScriptManager()->changeLocation('g', 'j', 'r', 'e', 0);
-				frm = 5;
-				redraw = true;
-			}
-		// Save
-		if (menuBarFlag & kMenubarSave)
-		  if (hotspots[0].contains(Pos)) {
-				_engine->getScriptManager()->changeLocation('g', 'j', 's', 'e', 0);
-				frm = 5;
-				redraw = true;
-			}
-	}
+bool MenuNemesis::inMenu(const Common::Point &Pos) {
+  return menuTriggerArea.contains(Pos) || (menuFocus.front() != kFocusNone);
 }
 
 void MenuNemesis::onMouseMove(const Common::Point &Pos) {
-  inMenu = _menuArea.contains(Pos);
-
-	if (_menuTriggerArea.contains(Pos)) {
-		menuScroller.active = true;
-
-		if (_engine->getScriptManager()->getStateValue(StateKey_MenuState) != 2)
-			_engine->getScriptManager()->setStateValue(StateKey_MenuState, 2);
-
-		int lastItem = mouseOnItem;
-		mouseOnItem = -1;
-
-    //Check mouse position against menu area
-	  if(inMenu) {
-	    // Exit
-		  if (menuBarFlag & kMenubarExit)
-			  if (hotspots[3].contains(Pos))
-				  mouseOnItem = kMainMenuExit;
-		  // Prefs
-		  if (menuBarFlag & kMenubarSettings)
-			  if (hotspots[2].contains(Pos))
-				  mouseOnItem = kMainMenuPrefs;
-		  // Restore
-		  if (menuBarFlag & kMenubarRestore)
-			  if (hotspots[1].contains(Pos))
-				  mouseOnItem = kMainMenuLoad;
-		  // Save
-		  if (menuBarFlag & kMenubarSave)
-			  if (hotspots[0].contains(Pos))
-				  mouseOnItem = kMainMenuSave;
-		}
-
-		if (lastItem != mouseOnItem) {
-			redraw = true;
-			frm = 0;
-			delay = 200;
-		}
-	} else {
-		menuScroller.active = false;
-		if (_engine->getScriptManager()->getStateValue(StateKey_MenuState) != 0)
-			_engine->getScriptManager()->setStateValue(StateKey_MenuState, 0);
-		mouseOnItem = -1;
-	}
+  //Trigger main menu scrolldown to get mouse over main trigger area
+  //Set focus to topmost layer of menus that mouse is currently over
+  if(mainArea.contains(Pos) || menuTriggerArea.contains(Pos))
+    setFocus(kFocusMain);
+  else
+    setFocus(kFocusNone);
+  MenuHandler::onMouseMove(Pos);
 }
 
-void MenuNemesis::process(uint32 deltatime) {
-  
-	if(menuScroller.update(deltatime)) {
-		redraw = true;
-    for (int i = 0; i < 4; i++)
-      hotspots[i].moveTo(_menuArea.left + wxButs[i][1], _menuArea.top + menuScroller.Pos.y);
-		}
-
-	if (mouseOnItem != -1) {
-		delay -= deltatime;
-		if (delay <= 0 && frm < 4) {
-			delay = 200;
-			frm++;
-			redraw = true;
-		}
-	}
-		
-	if (redraw) {
-		_engine->getRenderManager()->clearMenuSurface(colorkey);
-		_engine->getRenderManager()->blitSurfaceToMenu(menuBar, 0, menuScroller.Pos.y);
-
-		if (menuBarFlag & kMenubarExit)
-			if (mouseOnItem == kMainMenuExit)
-				_engine->getRenderManager()->blitSurfaceToMenu(but[3][frm], wxButs[3][1], menuScroller.Pos.y);
-
-		if (menuBarFlag & kMenubarSettings)
-			if (mouseOnItem == kMainMenuPrefs)
-				_engine->getRenderManager()->blitSurfaceToMenu(but[2][frm], wxButs[2][1], menuScroller.Pos.y);
-
-		if (menuBarFlag & kMenubarRestore)
-			if (mouseOnItem == kMainMenuLoad)
-				_engine->getRenderManager()->blitSurfaceToMenu(but[1][frm], wxButs[1][1], menuScroller.Pos.y);
-
-		if (menuBarFlag & kMenubarSave)
-			if (mouseOnItem == kMainMenuSave)
-				_engine->getRenderManager()->blitSurfaceToMenu(but[0][frm], wxButs[0][1], menuScroller.Pos.y);
-
-		redraw = false;
-	}	
-}
-  
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/menu.h b/engines/zvision/scripting/menu.h
index 60f26cafe7b..785e49cc43a 100644
--- a/engines/zvision/scripting/menu.h
+++ b/engines/zvision/scripting/menu.h
@@ -24,6 +24,8 @@
 
 #include "graphics/surface.h"
 #include "common/rect.h"
+#include "common/array.h"
+#include "common/bitarray.h"
 
 #include "zvision/zvision.h"
 #include "zvision/scripting/script_manager.h"
@@ -31,44 +33,110 @@
 
 namespace ZVision {
 
-enum menuBar {
-	kMenubarExit = 0x1,
-	kMenubarSettings = 0x2,
-	kMenubarRestore = 0x4,
-	kMenubarSave = 0x8,
-	kMenubarItems = 0x100,
-	kMenubarMagic = 0x200
+enum {
+	kMainMenuSave = 0,
+	kMainMenuLoad = 1,
+	kMainMenuPrefs = 2,
+	kMainMenuExit = 3,
+	kItemsMenu = 4,
+	kMagicMenu = 5
+};
+
+struct MenuParams {
+  int16 wxButs[4][2];   //Widths & X positions of main menu buttons; {Save, Restore, Prefs, Quit}
+  int16 wMain;  //Widths & X position of main menu background
+  int8 idleFrame; //Frame to display of unselected main menu button
+  int8 activeFrame; //Frame to display of selected main menu button when mouse is down
+  int8 clickedFrame; //Frame to display of selected main menu button when mouse is down
+  Common::Point activePos;  //Fully scrolled main menu position, relative to origin of menu area
+  Common::Point idlePos;  //Fully retracted main menu position, relative to origin of menu area
+  int16 period; //Duration of main menu scrolldown
+  int16 triggerHeight;  //Height of menu trigger area when inactive
+  int16 buttonPeriod; //Duration of main menu button animation
+};
+
+//NB - menu area is same width as working window.
+
+static const MenuParams nemesisParams {
+  { {120 , -1}, {144, 120}, {128, 264}, {120, 392} },
+  512,
+  -1,
+  4,
+  5,
+  Common::Point(0,0),
+  Common::Point(0,-32),
+  500,
+  2,
+  500
+};
+
+static const MenuParams zgiParams {
+  { {135 , 50}, {135, 185}, {135, 320}, {135, 455} },
+  580,
+  0,
+  1,
+  1,
+  Common::Point(30,0),
+  Common::Point(30,-20),
+  250,
+  32,
+  0
 };
 
 class MenuHandler {
 public:
-	MenuHandler(ZVision *engine, Common::Rect menuArea);
-	virtual ~MenuHandler() {};
-	virtual void onMouseMove(const Common::Point &Pos) {};
-	virtual void onMouseDown(const Common::Point &Pos) {};
-	virtual void onMouseUp(const Common::Point &Pos) {};
-	virtual void process(uint32 deltaTimeInMillis) {};
-  bool isInMenu() {return inMenu;}; //For widescreen mod; used to suspend panning, tilting & scripting triggers when the mouse is within the working window but also in the menu.
-  //NB former boolean flag inMenu has been renamed to menuActive.
-
-	void setEnable(uint16 flags) {
-		menuBarFlag = flags;
-	}
+	MenuHandler(ZVision *engine, const Common::Rect menuArea, const MenuParams params);
+	virtual ~MenuHandler();
+	virtual void onMouseMove(const Common::Point &Pos);
+	virtual void onMouseDown(const Common::Point &Pos);
+	virtual void onMouseUp(const Common::Point &Pos);
+	virtual void process(uint32 deltaTimeInMillis);
+  bool inMenu() {return prevInMenu;};
+  virtual bool inMenu(const Common::Point &Pos) {return false;}; //For widescreen mod; used to suspend panning, tilting & scripting triggers when the mouse is within the working window but also in the menu.
+
+	void mainMouseDown(const Common::Point &Pos); //Show clicked graphic under selected button
+	bool mainMouseMove(const Common::Point &Pos); //return true if selected button has changed
+
+	void setEnable(uint16 flags);
 	uint16 getEnable() {
 		return menuBarFlag;
 	}
+	bool getEnable(uint8 flag) {
+	  return enableFlags.get(flag);
+	}
+	
 protected:
-	uint16 menuBarFlag;
-	ZVision *_engine;
-  Common::Rect _menuArea;	
-  Common::Rect _menuTriggerArea;
-	bool menuActive;  //True if mouse is in menu area
-	bool inMenu = false;  //True if mouse is over scrolled menu graphics, regardless of menuActive
+  virtual void redrawAll() {};
+  void redrawMain();
+	int mouseOverMain(const Common::Point &Pos);
+	void setFocus(int8 currentFocus);
+	
+//	bool inMenu = false;  //True if menus are currently visible
+	bool prevInMenu = false;
 	bool redraw = true;
-	int mouseOnItem;
-	int32 colorkey = -1;  //Transparency color for compositing menu over playfield
-};
+	int mouseOnItem = -1;
+	static const int32 colorkey = -1;  //Transparency color for compositing menu over playfield
+	static const uint8 hMainMenu = 32;
+  int8 mainClicked = -1;
 
+	ZVision *_engine;
+  const MenuParams _params;
+	uint16 menuBarFlag;
+  const Common::Rect _menuArea;
+	const Common::Point menuOrigin;
+  const Common::Rect menuTriggerArea;
+	Graphics::Surface mainBack;
+	Graphics::Surface mainButtons[4][6];
+	Common::BitArray enableFlags;
+  Common::Rect mainArea;
+	Common::Rect menuHotspots[4];
+  int8 mainFrames[4]; //Frame to display of each main menu button; first row is currently displayed, 2nd row is backbuffer for idle animations
+  Scroller mainScroller;
+	Common::Array<int8> menuFocus; //Order in which menus have most recently had focus; determines current mouse focus & order in which to redraw them.
+	bool clean = false; //Whether or not to blank
+  LinearScroller* buttonAnim[4];
+};
+ 
 class MenuZGI: public MenuHandler {
 public:
 	MenuZGI(ZVision *engine, Common::Rect menuArea);
@@ -76,21 +144,33 @@ public:
 	void onMouseMove(const Common::Point &Pos) override;
 	void onMouseUp(const Common::Point &Pos) override;
 	void process(uint32 deltaTimeInMillis) override;
+  bool inMenu(const Common::Point &Pos) override;
 private:
-	Graphics::Surface menuBack[3][2];
-	Graphics::Surface menuBar[4][2];
+  void redrawAll() override;
+	Graphics::Surface menuBack[3];
 	Graphics::Surface *items[50][2];
 	uint itemId[50];
 
 	Graphics::Surface *magic[12][2];
 	uint magicId[12];
+//  void redrawMain(bool hasFocus) override;
+	void redrawItems();
+	void redrawMagic();
+	int mouseOverItem(const Common::Point &Pos, int itemCount);
+	int mouseOverMagic(const Common::Point &Pos);
+	
+	static const uint16 hSideMenu = 32;
+	static const uint16 wSideMenu = 600;
+	static const uint16 wSideMenuTab = 20;
+  static const int16 magicWidth = 47;
 
-	int menuMouseFocus;
+  Scroller itemsScroller, magicScroller;
 
-	bool scrolled[3];
-	int16 scrollPos[3];
+  const Common::Point magicOrigin;
+  const Common::Point itemsOrigin;
 
-	bool clean;
+  Common::Rect magicArea;
+  Common::Rect itemsArea;
 };
 
 class MenuNemesis: public MenuHandler {
@@ -98,22 +178,9 @@ public:
 	MenuNemesis(ZVision *engine, Common::Rect menuArea);
 	~MenuNemesis() override;
 	void onMouseMove(const Common::Point &Pos) override;
-	void onMouseUp(const Common::Point &Pos) override;
-	void process(uint32 deltaTimeInMillis) override;
+  bool inMenu(const Common::Point &Pos) override;
 private:
-	Graphics::Surface but[4][6];
-	Graphics::Surface menuBar;
-	Common::Rect hotspots[4];
-	
-  //Widths & X positions of buttons; {Save, Restore, Prefs, Exit}
-  //X positions relative to left of menu area
-  //const int16 wxButs[4][2] = { {120 , 64}, {144, 184}, {128, 328}, {120, 456} };  //Originals
-  const int16 wxButs[4][2] = { {120 , 0}, {144, 120}, {128, 264}, {120, 392} };
-	
-  Scroller menuScroller;
-
-	int frm;
-	int16 delay;
+  void redrawAll() override;
 };
 
 } // End of namespace ZVision


Commit: c61cefee8938dcb07030eb09b27e6848633ef68d
    https://github.com/scummvm/scummvm/commit/c61cefee8938dcb07030eb09b27e6848633ef68d
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:54+02:00

Commit Message:
ZVISION: Replace simpleBlit with transBlit.
Enable menus to overlay working window.

Changed paths:
    engines/zvision/graphics/render_manager.cpp


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index c3c3f2756e2..3f770ac6d81 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -142,7 +142,6 @@ void RenderManager::renderSceneToScreen() {
 	
 	
 	_backgroundManagedSurface.simpleBlitFrom(*out); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
-	//_menuManagedSurface.simpleBlitFrom(_menuSurface);
 	_menuManagedSurface.transBlitFrom(_menuSurface, -1);
 	_screenSurface.update();
 


Commit: 1255ef328805b12408bedd0fdd06d3279c24f75b
    https://github.com/scummvm/scummvm/commit/1255ef328805b12408bedd0fdd06d3279c24f75b
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:54+02:00

Commit Message:
ZVISION: Improve widescreen descriptive text in options.

Changed paths:
    engines/zvision/metaengine.cpp


diff --git a/engines/zvision/metaengine.cpp b/engines/zvision/metaengine.cpp
index 176213b5ed8..5a9cb7891d2 100644
--- a/engines/zvision/metaengine.cpp
+++ b/engines/zvision/metaengine.cpp
@@ -104,7 +104,7 @@ static const ADExtraGuiOptionsMap optionsList[] = {
 		GAMEOPTION_ENABLE_WIDESCREEN,
 		{
 			_s("Enable widescreen support"),
-			_s("Enlarge panoramic playfield & alter game resolution to better utilise wide aspect ratio displays"),
+			_s("Rearrange placement of menus & subtitles so as to make better use of modern wide aspect ratio displays."),
 			"widescreen",
 			true,
 			0,


Commit: e442d4fab5338c2c03c3f352bb1f689d3079f3a3
    https://github.com/scummvm/scummvm/commit/e442d4fab5338c2c03c3f352bb1f689d3079f3a3
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:54+02:00

Commit Message:
ZVISION: Code cleanup

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 3f770ac6d81..d8a413f0b1d 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -94,15 +94,14 @@ void RenderManager::renderSceneToScreen() {
 	//Apply graphical effects to temporary effects buffer and/or directly to current background image, as appropriate
 	if (!_effects.empty()) {
 		bool copied = false;
-		Common::Rect windowRect(_workingWindow.width(), _workingWindow.height());
+		const Common::Rect windowRect(_workingWindow.width(), _workingWindow.height());
 
 		for (EffectsList::iterator it = _effects.begin(); it != _effects.end(); it++) {
 			Common::Rect rect = (*it)->getRegion();
 			Common::Rect screenSpaceLocation = rect;
 
-			if ((*it)->isPort()) {
+			if ((*it)->isPort())
 				screenSpaceLocation = transformBackgroundSpaceRectToScreenSpace(screenSpaceLocation);
-			}
 
 			if (windowRect.intersects(screenSpaceLocation)) {
 				if (!copied) {
@@ -135,7 +134,8 @@ void RenderManager::renderSceneToScreen() {
 			out = &_warpedSceneSurface;
 			outWndDirtyRect = Common::Rect(_workingWindow.width(), _workingWindow.height());
 		}
-	} else {
+	} 
+	else {
 		out = in;
 		outWndDirtyRect = _backgroundSurfaceDirtyRect;
 	}
@@ -417,9 +417,9 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Com
 	//CODE IDENTICAL TO HERE
 	
 	//BUG TEST CODE
-	Common::Point dstPos2 = dstPos;
-	Common::Rect srcRect2 = srcRect;
-	Common::Rect::getBlitRect(dstPos2, srcRect2, Common::Rect(dst.w,dst.h));
+	//Common::Point dstPos2 = dstPos;
+	//Common::Rect srcRect2 = srcRect;
+	//Common::Rect::getBlitRect(dstPos2, srcRect2, Common::Rect(dst.w,dst.h));
 	
 	//Generate destination rectangle
 	Common::Rect dstRect = Common::Rect(dst.w, dst.h);
@@ -460,7 +460,7 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Com
 		  dstPos.y = 0;
 		  
 	  //BUG TEST
-	  assert(dstPos == dstPos2);
+	  //assert(dstPos == dstPos2);
     
     //If _x & _y lie within destination surface
     if (dstPos.x < dst.w && dstPos.y < dst.h) {
@@ -705,14 +705,6 @@ void RenderManager::clearMenuSurface(int32 colorkey) {
 	_menuSurface.fillRect(_menuSurfaceDirtyRect, colorkey);
 }
 
-void RenderManager::clearMenuSurface(const Common::Rect &r, int32 colorkey) {
-	if (_menuSurfaceDirtyRect.isEmpty())
-		_menuSurfaceDirtyRect = r;
-	else
-		_menuSurfaceDirtyRect.extend(r);
-	_menuSurface.fillRect(r, colorkey);
-}
-
 void RenderManager::initSubArea(uint32 windowWidth, uint32 windowHeight, const Common::Rect &workingWindow) {
 	_workingWindow = workingWindow;
 
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index a069a970b4e..0b8408a5572 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -283,7 +283,6 @@ public:
 
 	// Clear whole/area of menu surface
 	void clearMenuSurface(int32 colorkey = 0);
-	void clearMenuSurface(const Common::Rect &r, int32 colorkey = 0);
 
 	// Copy needed portion of background surface to workingWindow surface
 	void prepareBackground();


Commit: 6cd9acf642720bf541a92f7ad55d40f660cc6a73
    https://github.com/scummvm/scummvm/commit/6cd9acf642720bf541a92f7ad55d40f660cc6a73
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:54+02:00

Commit Message:
ZVISION: Fix bug in renderSceneToScreen() that delays inventory item display.

Changed paths:
    engines/zvision/graphics/render_manager.cpp


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index d8a413f0b1d..74d2c731c6a 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -143,7 +143,8 @@ void RenderManager::renderSceneToScreen() {
 	
 	_backgroundManagedSurface.simpleBlitFrom(*out); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
 	_menuManagedSurface.transBlitFrom(_menuSurface, -1);
-	_screenSurface.update();
+	if(_engine->canRender())
+	  _screenSurface.update();
 
   /*
 	if (!outWndDirtyRect.isEmpty()) {


Commit: ea13219757127ac865de9783c80b323579aec7d1
    https://github.com/scummvm/scummvm/commit/ea13219757127ac865de9783c80b323579aec7d1
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:54+02:00

Commit Message:
ZVISION: Improve menu scrolling behaviour.

Changed paths:
    engines/zvision/scripting/menu.cpp


diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index dd1aae34958..b5c76b46eb4 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -345,7 +345,7 @@ void MenuZGI::onMouseUp(const Common::Point &Pos) {
 }
 
 void MenuZGI::onMouseMove(const Common::Point &Pos) {
-  if(!inMenu(Pos) && prevInMenu) {
+  if(!inMenu(Pos)) {
     mainScroller.reset();
     magicScroller.reset();
     itemsScroller.reset();


Commit: bddf8495d1b224568b20d10f73a11d41ff1bb3d3
    https://github.com/scummvm/scummvm/commit/bddf8495d1b224568b20d10f73a11d41ff1bb3d3
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:54+02:00

Commit Message:
ZVISION: Rename MenuHandler to MenuManager for consistency.

Changed paths:
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/menu.cpp
    engines/zvision/scripting/menu.h
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index da35678cfa8..ae4a8829fca 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -447,7 +447,7 @@ ActionMenuBarEnable::ActionMenuBarEnable(ZVision *engine, int32 slotKey, const C
 }
 
 bool ActionMenuBarEnable::execute() {
-	_engine->getMenuHandler()->setEnable(_menus);
+	_engine->getMenuManager()->setEnable(_menus);
 	return true;
 }
 
diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index b5c76b46eb4..6bc4b547893 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -34,7 +34,7 @@ enum {
 	kFocusMain = 2
 };
 
-MenuHandler::MenuHandler(ZVision *engine, const Common::Rect menuArea, const MenuParams params) :
+MenuManager::MenuManager(ZVision *engine, const Common::Rect menuArea, const MenuParams params) :
 	_engine{engine},
   _params{params},
 	menuBarFlag{0xFFFF},
@@ -57,13 +57,13 @@ MenuHandler::MenuHandler(ZVision *engine, const Common::Rect menuArea, const Men
 	mainArea.moveTo(menuOrigin+mainScroller.Pos);
 }
 
-MenuHandler::~MenuHandler() {
+MenuManager::~MenuManager() {
 	for (int i = 0; i < 4; i++)
 	  delete buttonAnim[i];
 	mainBack.free();
 }
 
-void MenuHandler::setEnable(uint16 flags) {
+void MenuManager::setEnable(uint16 flags) {
 	  static const uint16 flagMasks[6] = {0x8,0x4,0x2,0x1,0x100,0x200};  //Enum order: save,restore,prefs,quit,items,magic
 		menuBarFlag = flags;
 		for(uint i=0; i<=5; i++) {
@@ -74,7 +74,7 @@ void MenuHandler::setEnable(uint16 flags) {
     }		  
 	}
 
-void MenuHandler::onMouseUp(const Common::Point &Pos) {
+void MenuManager::onMouseUp(const Common::Point &Pos) {
   if(menuFocus.front() == kFocusMain) {
     mouseOnItem = mouseOverMain(Pos);
     if(mouseOnItem == mainClicked)
@@ -108,7 +108,7 @@ void MenuHandler::onMouseUp(const Common::Point &Pos) {
   mainClicked = -1;
 }
 
-void MenuHandler::onMouseDown(const Common::Point &Pos) {
+void MenuManager::onMouseDown(const Common::Point &Pos) {
   if(menuFocus.front() == kFocusMain) {
     mouseOnItem = mouseOverMain(Pos);
     //Show clicked graphic
@@ -121,7 +121,7 @@ void MenuHandler::onMouseDown(const Common::Point &Pos) {
   debug("mouse position %d %d", Pos.x, Pos.y);
 }
 
-void MenuHandler::onMouseMove(const Common::Point &Pos) {
+void MenuManager::onMouseMove(const Common::Point &Pos) {
   bool nowInMenu = inMenu(Pos);
   if(nowInMenu != prevInMenu)
     redraw = true;
@@ -154,7 +154,7 @@ void MenuHandler::onMouseMove(const Common::Point &Pos) {
     redraw = true;
 }
 
-int MenuHandler::mouseOverMain(const Common::Point &Pos) {
+int MenuManager::mouseOverMain(const Common::Point &Pos) {
   //Common::Rect mainHotspot(28,hSideMenu);
   //mainHotspot.moveTo(mainOrigin + mainScroller.Pos);
   for(int8 i = 0; i < 4; i++) {
@@ -164,7 +164,7 @@ int MenuHandler::mouseOverMain(const Common::Point &Pos) {
   return -1;
 }
 
-void MenuHandler::process(uint32 deltatime) {
+void MenuManager::process(uint32 deltatime) {
 	if(mainScroller.update(deltatime)) {
 	  mainArea.moveTo(menuOrigin+mainScroller.Pos);
     for (int i = 0; i < 4; i++)
@@ -188,7 +188,7 @@ void MenuNemesis::redrawAll() {
   redrawMain();
 };
 
-void MenuHandler::redrawMain() {
+void MenuManager::redrawMain() {
   //Draw menu background
   _engine->getRenderManager()->blitSurfaceToMenu(mainBack, mainScroller.Pos.x, mainScroller.Pos.y, 0);
   //Draw buttons
@@ -204,7 +204,7 @@ void MenuHandler::redrawMain() {
   clean = false;
 }
 
-void MenuHandler::setFocus(int8 currentFocus) {
+void MenuManager::setFocus(int8 currentFocus) {
   if(menuFocus.front() != currentFocus) {
     Common::Array<int8> _menuFocus;
     while(menuFocus.size() > 0) {
@@ -222,7 +222,7 @@ void MenuHandler::setFocus(int8 currentFocus) {
 }
 
 MenuZGI::MenuZGI(ZVision *engine, const Common::Rect menuArea) :
-	MenuHandler(engine, menuArea, zgiParams),
+	MenuManager(engine, menuArea, zgiParams),
 	itemsScroller{Common::Point(0,0), Common::Point(wSideMenuTab-wSideMenu,0), 1000},
 	magicScroller{Common::Point(-wSideMenu,0), Common::Point(-wSideMenuTab,0), 1000},
 	itemsOrigin{menuArea.left, menuArea.top},
@@ -337,7 +337,7 @@ void MenuZGI::onMouseUp(const Common::Point &Pos) {
 			  }
 			  break;
 		  case kFocusMain:
-        MenuHandler::onMouseUp(Pos);
+        MenuManager::onMouseUp(Pos);
 			  break;
 		  default:
 			  break;
@@ -408,7 +408,7 @@ void MenuZGI::onMouseMove(const Common::Point &Pos) {
 		    break;
     }
 	} 
-  MenuHandler::onMouseMove(Pos);
+  MenuManager::onMouseMove(Pos);
 }
 
 int MenuZGI::mouseOverItem(const Common::Point &Pos, int itemCount) {
@@ -444,11 +444,11 @@ void MenuZGI::process(uint32 deltatime) {
 	  magicArea.moveTo(magicOrigin+magicScroller.Pos);
 	  redraw = true;
   }
-  MenuHandler::process(deltatime);
+  MenuManager::process(deltatime);
 }
 
 void MenuZGI::redrawAll() {
-  if(MenuHandler::inMenu())
+  if(MenuManager::inMenu())
     for(int8 i=menuFocus.size()-1; i>=0; i--)
       switch (menuFocus[i]) {
         case kFocusItems:
@@ -560,7 +560,7 @@ void MenuZGI::redrawItems() {
 }
 
 MenuNemesis::MenuNemesis(ZVision *engine, const Common::Rect menuArea) :
-	MenuHandler(engine, menuArea, nemesisParams) {
+	MenuManager(engine, menuArea, nemesisParams) {
 
   //Buffer menu background image
 	_engine->getRenderManager()->readImageToSurface("bar.tga", mainBack, false);
@@ -593,7 +593,7 @@ void MenuNemesis::onMouseMove(const Common::Point &Pos) {
     setFocus(kFocusMain);
   else
     setFocus(kFocusNone);
-  MenuHandler::onMouseMove(Pos);
+  MenuManager::onMouseMove(Pos);
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/menu.h b/engines/zvision/scripting/menu.h
index 785e49cc43a..8f9b1dafcd8 100644
--- a/engines/zvision/scripting/menu.h
+++ b/engines/zvision/scripting/menu.h
@@ -83,10 +83,10 @@ static const MenuParams zgiParams {
   0
 };
 
-class MenuHandler {
+class MenuManager {
 public:
-	MenuHandler(ZVision *engine, const Common::Rect menuArea, const MenuParams params);
-	virtual ~MenuHandler();
+	MenuManager(ZVision *engine, const Common::Rect menuArea, const MenuParams params);
+	virtual ~MenuManager();
 	virtual void onMouseMove(const Common::Point &Pos);
 	virtual void onMouseDown(const Common::Point &Pos);
 	virtual void onMouseUp(const Common::Point &Pos);
@@ -137,7 +137,7 @@ protected:
   LinearScroller* buttonAnim[4];
 };
  
-class MenuZGI: public MenuHandler {
+class MenuZGI: public MenuManager {
 public:
 	MenuZGI(ZVision *engine, Common::Rect menuArea);
 	~MenuZGI() override;
@@ -173,7 +173,7 @@ private:
   Common::Rect itemsArea;
 };
 
-class MenuNemesis: public MenuHandler {
+class MenuNemesis: public MenuManager {
 public:
 	MenuNemesis(ZVision *engine, Common::Rect menuArea);
 	~MenuNemesis() override;
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index a87f5af9142..64896929300 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -82,6 +82,7 @@ void ScriptManager::update(uint deltaTimeMillis) {
 		// Another idea would be to change if there are pending scripts
 		// in the exec queues, but that could cause this to hang
 		// indefinitely.
+		// TODO - this causes noticeable pauses on location change; see if these can be reduced by improving this functionality.
 		if (_changeLocationDelayCycles-- <= 0) {
 			ChangeLocationReal(false);
 		}
@@ -643,7 +644,7 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 	_referenceTable.clear();
 	addPuzzlesToReferenceTable(universe);
 
-	_engine->getMenuHandler()->setEnable(0xFFFF);
+	_engine->getMenuManager()->setEnable(0xFFFF);
 
 	if (_nextLocation.world != _currentLocation.world) {
 		cleanScriptScope(nodeview);
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index 06df44aa623..5151c6c1d08 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -63,7 +63,7 @@ class CursorManager;
 class StringManager;
 class SaveManager;
 class RLFDecoder;
-class MenuHandler;
+class MenuManager;
 class TextRenderer;
 class Subtitle;
 class MidiManager;
@@ -137,6 +137,7 @@ public:
 	 * and thus must be composited and rendered within renderSceneToScreen().
 	 */
 	Common::Rect _menuArea;
+	Common::Rect _subArea;
 	const Graphics::PixelFormat _resourcePixelFormat;
 	const Graphics::PixelFormat _screenPixelFormat;
 
@@ -157,7 +158,7 @@ private:
 	TextRenderer *_textRenderer;
 	MidiManager *_midiManager;
 	SaveManager *_saveManager;
-	MenuHandler *_menu;
+	MenuManager *_menu;
 
 	// Clock
 	Clock _clock;
@@ -213,7 +214,7 @@ public:
 	MidiManager *getMidiManager() const {
 		return _midiManager;
 	}
-	MenuHandler *getMenuHandler() const {
+	MenuManager *getMenuManager() const {
 		return _menu;
 	}
 


Commit: 23871b541bde6b06246664cf275d19771786ba50
    https://github.com/scummvm/scummvm/commit/23871b541bde6b06246664cf275d19771786ba50
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:54+02:00

Commit Message:
ZVISION: Alter puzzle debug message level.

Changed paths:
    engines/zvision/scripting/script_manager.cpp


diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index 64896929300..a0312b8e49b 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -275,7 +275,7 @@ bool ScriptManager::checkPuzzleCriteria(Puzzle *puzzle, uint counter) {
 
 	// criteriaList can be empty. Aka, the puzzle should be executed immediately
 	if (puzzle->criteriaList.empty() || criteriaMet) {
-		debug(1, "Puzzle %u criteria passed. Executing its ResultActions", puzzle->key);
+		debug(2, "Puzzle %u criteria passed. Executing its ResultActions", puzzle->key);
 
 		// Set the puzzle as completed
 		setStateValue(puzzle->key, 1);


Commit: 9c0d5a874794aad3210c97a2bc79cd6b11f556b8
    https://github.com/scummvm/scummvm/commit/9c0d5a874794aad3210c97a2bc79cd6b11f556b8
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:54+02:00

Commit Message:
ZVISION: Unify video playback rendering & scene rendering.
Simplify screen updates & enable subtitles to overlay video playback.

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/video/video.cpp


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 74d2c731c6a..c452b89d272 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -46,9 +46,8 @@ namespace ZVision {
 RenderManager::RenderManager(ZVision *engine, uint32 windowWidth, uint32 windowHeight, const Common::Rect workingWindow, const Common::Rect menuArea, const Graphics::PixelFormat pixelFormat, bool doubleFPS)
 	: _engine(engine),
 	  _system(engine->_system),
-	  _screenCenterX(_workingWindow.width() / 2),
-	  _screenCenterY(_workingWindow.height() / 2),
 	  _workingWindow(workingWindow),
+	  _screenCentre(windowWidth / 2, windowHeight / 2),
 	  _pixelFormat(pixelFormat),
 	  _backgroundWidth(0),
 	  _backgroundHeight(0),
@@ -70,6 +69,7 @@ RenderManager::RenderManager(ZVision *engine, uint32 windowWidth, uint32 windowH
 
 	_menuSurface.create(_menuArea.width(), _menuArea.height(), _pixelFormat);
 	_menuManagedSurface.create(_screenSurface, _menuArea);
+	_subManagedSurface.create(_screenSurface, _subArea);
 
 	initSubArea(windowWidth, windowHeight, workingWindow);
 }
@@ -82,66 +82,70 @@ RenderManager::~RenderManager() {
 	_warpedSceneSurface.free();
 	_menuSurface.free();
 	_menuManagedSurface.free();
-	_subtitleSurface.free();
+	_subSurface.free();
+	_subManagedSurface.free();
 	_screenSurface.free();
 }
 
-void RenderManager::renderSceneToScreen() {
-	Graphics::Surface *out = &_warpedSceneSurface;
-	Graphics::Surface *in = &_backgroundSurface;
-	Common::Rect outWndDirtyRect;
-
-	//Apply graphical effects to temporary effects buffer and/or directly to current background image, as appropriate
-	if (!_effects.empty()) {
-		bool copied = false;
-		const Common::Rect windowRect(_workingWindow.width(), _workingWindow.height());
-
-		for (EffectsList::iterator it = _effects.begin(); it != _effects.end(); it++) {
-			Common::Rect rect = (*it)->getRegion();
-			Common::Rect screenSpaceLocation = rect;
-
-			if ((*it)->isPort())
-				screenSpaceLocation = transformBackgroundSpaceRectToScreenSpace(screenSpaceLocation);
-
-			if (windowRect.intersects(screenSpaceLocation)) {
-				if (!copied) {
-					copied = true;
-					_effectSurface.copyFrom(_backgroundSurface);
-					in = &_effectSurface;
-				}
-				const Graphics::Surface *post;
-				if ((*it)->isPort())
-					post = (*it)->draw(_currentBackgroundImage.getSubArea(rect));
-				else
-					post = (*it)->draw(_effectSurface.getSubArea(rect));
-				Common::Rect empty;
-				blitSurfaceToSurface(*post, empty, _effectSurface, screenSpaceLocation.left, screenSpaceLocation.top);
-				screenSpaceLocation.clip(windowRect);
-				if (_backgroundSurfaceDirtyRect .isEmpty()) {
-					_backgroundSurfaceDirtyRect = screenSpaceLocation;
-				} else {
-					_backgroundSurfaceDirtyRect.extend(screenSpaceLocation);
-				}
-			}
-		}
-	}
-
-  //Apply panorama/tilt warp to background image
-	RenderTable::RenderState state = _renderTable.getRenderState();
-	if (state == RenderTable::PANORAMA || state == RenderTable::TILT) {
-		if (!_backgroundSurfaceDirtyRect.isEmpty()) {
-			_renderTable.mutateImage(&_warpedSceneSurface, in);
-			out = &_warpedSceneSurface;
-			outWndDirtyRect = Common::Rect(_workingWindow.width(), _workingWindow.height());
-		}
-	} 
-	else {
-		out = in;
-		outWndDirtyRect = _backgroundSurfaceDirtyRect;
+void RenderManager::renderSceneToScreen(bool videoPlaying) {
+  if(!videoPlaying) {
+	  Graphics::Surface *out = &_warpedSceneSurface;
+	  Graphics::Surface *in = &_backgroundSurface;
+	  Common::Rect outWndDirtyRect;
+
+	  //Apply graphical effects to temporary effects buffer and/or directly to current background image, as appropriate
+	  if (!_effects.empty()) {
+		  bool copied = false;
+		  const Common::Rect windowRect(_workingWindow.width(), _workingWindow.height());
+
+		  for (EffectsList::iterator it = _effects.begin(); it != _effects.end(); it++) {
+			  Common::Rect rect = (*it)->getRegion();
+			  Common::Rect screenSpaceLocation = rect;
+
+			  if ((*it)->isPort())
+				  screenSpaceLocation = transformBackgroundSpaceRectToScreenSpace(screenSpaceLocation);
+
+			  if (windowRect.intersects(screenSpaceLocation)) {
+				  if (!copied) {
+					  copied = true;
+					  _effectSurface.copyFrom(_backgroundSurface);
+					  in = &_effectSurface;
+				  }
+				  const Graphics::Surface *post;
+				  if ((*it)->isPort())
+					  post = (*it)->draw(_currentBackgroundImage.getSubArea(rect));
+				  else
+					  post = (*it)->draw(_effectSurface.getSubArea(rect));
+				  Common::Rect empty;
+				  blitSurfaceToSurface(*post, empty, _effectSurface, screenSpaceLocation.left, screenSpaceLocation.top);
+				  screenSpaceLocation.clip(windowRect);
+				  if (_backgroundSurfaceDirtyRect .isEmpty()) {
+					  _backgroundSurfaceDirtyRect = screenSpaceLocation;
+				  } else {
+					  _backgroundSurfaceDirtyRect.extend(screenSpaceLocation);
+				  }
+			  }
+		  }
+	  }
+
+    //Apply panorama/tilt warp to background image
+	  RenderTable::RenderState state = _renderTable.getRenderState();
+	  if (state == RenderTable::PANORAMA || state == RenderTable::TILT) {
+		  if (!_backgroundSurfaceDirtyRect.isEmpty()) {
+			  _renderTable.mutateImage(&_warpedSceneSurface, in);
+			  out = &_warpedSceneSurface;
+			  outWndDirtyRect = Common::Rect(_workingWindow.width(), _workingWindow.height());
+		  }
+	  } 
+	  else {
+		  out = in;
+		  outWndDirtyRect = _backgroundSurfaceDirtyRect;
+	  }
+	  
+	  
+	  _backgroundManagedSurface.simpleBlitFrom(*out); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
 	}
 	
-	
-	_backgroundManagedSurface.simpleBlitFrom(*out); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
 	_menuManagedSurface.transBlitFrom(_menuSurface, -1);
 	if(_engine->canRender())
 	  _screenSurface.update();
@@ -158,17 +162,18 @@ void RenderManager::renderSceneToScreen() {
 	//*/
 }
 
-void RenderManager::copyToScreen(const Graphics::Surface &surface, Common::Rect &rect, int16 srcLeft, int16 srcTop) {
-	// Convert the surface to RGB565, if needed
-	Graphics::Surface *outSurface = surface.convertTo(_engine->_screenPixelFormat);
-	_system->copyRectToScreen(outSurface->getBasePtr(srcLeft, srcTop),
-		                        outSurface->pitch,
-		                        rect.left,
-		                        rect.top,
-		                        rect.width(),
-		                        rect.height());
-	outSurface->free();
-	delete outSurface;
+Graphics::ManagedSurface &RenderManager::getVidSurface(Common::Rect &dstRect) {
+  Common::Rect _dstRect = dstRect;
+  _dstRect.moveTo(_workingWindow.left, _workingWindow.top);
+	_vidManagedSurface.create(_screenSurface, _dstRect);
+	return _vidManagedSurface;
+}
+
+void RenderManager::copyToScreen(const Graphics::Surface &surface, Common::Rect &dstRect, int16 srcLeft, int16 srcTop) {
+	Common::Rect srcRect = dstRect;
+	srcRect.moveTo(srcLeft, srcTop);
+	_screenSurface.simpleBlitFrom(surface, srcRect, Common::Point(dstRect.left, dstRect.top));  
+  _screenSurface.update();
 }
 
 void RenderManager::renderImageToBackground(const Common::Path &fileName, int16 destX, int16 destY) {
@@ -304,9 +309,9 @@ const Common::Point RenderManager::screenSpaceToImageSpace(const Common::Point &
 		}
 
 		if (state == RenderTable::PANORAMA) {
-			newPoint += (Common::Point(_backgroundOffset - _screenCenterX, 0));
+			newPoint += (Common::Point(_backgroundOffset - _screenCentre.x, 0));
 		} else if (state == RenderTable::TILT) {
-			newPoint += (Common::Point(0, _backgroundOffset - _screenCenterY));
+			newPoint += (Common::Point(0, _backgroundOffset - _screenCentre.y));
 		}
 
 		if (_backgroundWidth)
@@ -634,44 +639,44 @@ void RenderManager::prepareBackground() {
 	if (state == RenderTable::PANORAMA) {
 		// Calculate the visible portion of the background
 		Common::Rect viewPort(_workingWindow.width(), _workingWindow.height());
-		viewPort.translate(-(_screenCenterX - _backgroundOffset), 0);
+		viewPort.translate(-(_screenCentre.x - _backgroundOffset), 0);
 		Common::Rect drawRect = _backgroundDirtyRect;
 		drawRect.clip(viewPort);
 
 		// Render the visible portion
 		if (!drawRect.isEmpty()) {
-			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _screenCenterX - _backgroundOffset + drawRect.left, drawRect.top);
+			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _screenCentre.x - _backgroundOffset + drawRect.left, drawRect.top);
 		}
 
 		// Mark the dirty portion of the surface
 		_backgroundSurfaceDirtyRect = _backgroundDirtyRect;
-		_backgroundSurfaceDirtyRect.translate(_screenCenterX - _backgroundOffset, 0);
+		_backgroundSurfaceDirtyRect.translate(_screenCentre.x - _backgroundOffset, 0);
 
 		// Panorama mode allows the user to spin in circles. Therefore, we need to render
 		// the portion of the image that wrapped to the other side of the screen
-		if (_backgroundOffset < _screenCenterX) {
-			viewPort.moveTo(-(_screenCenterX - (_backgroundOffset + _backgroundWidth)), 0);
+		if (_backgroundOffset < _screenCentre.x) {
+			viewPort.moveTo(-(_screenCentre.x - (_backgroundOffset + _backgroundWidth)), 0);
 			drawRect = _backgroundDirtyRect;
 			drawRect.clip(viewPort);
 
 			if (!drawRect.isEmpty())
-				blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _screenCenterX - (_backgroundOffset + _backgroundWidth) + drawRect.left, drawRect.top);
+				blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _screenCentre.x - (_backgroundOffset + _backgroundWidth) + drawRect.left, drawRect.top);
 
 			Common::Rect tmp = _backgroundDirtyRect;
-			tmp.translate(_screenCenterX - (_backgroundOffset + _backgroundWidth), 0);
+			tmp.translate(_screenCentre.x - (_backgroundOffset + _backgroundWidth), 0);
 			if (!tmp.isEmpty())
 				_backgroundSurfaceDirtyRect.extend(tmp);
 
-		} else if (_backgroundWidth - _backgroundOffset < _screenCenterX) {
-			viewPort.moveTo(-(_screenCenterX + _backgroundWidth - _backgroundOffset), 0);
+		} else if (_backgroundWidth - _backgroundOffset < _screenCentre.x) {
+			viewPort.moveTo(-(_screenCentre.x + _backgroundWidth - _backgroundOffset), 0);
 			drawRect = _backgroundDirtyRect;
 			drawRect.clip(viewPort);
 
 			if (!drawRect.isEmpty())
-				blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _screenCenterX + _backgroundWidth - _backgroundOffset + drawRect.left, drawRect.top);
+				blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _screenCentre.x + _backgroundWidth - _backgroundOffset + drawRect.left, drawRect.top);
 
 			Common::Rect tmp = _backgroundDirtyRect;
-			tmp.translate(_screenCenterX + _backgroundWidth - _backgroundOffset, 0);
+			tmp.translate(_screenCentre.x + _backgroundWidth - _backgroundOffset, 0);
 			if (!tmp.isEmpty())
 				_backgroundSurfaceDirtyRect.extend(tmp);
 
@@ -679,15 +684,15 @@ void RenderManager::prepareBackground() {
 	} else if (state == RenderTable::TILT) {
 		// Tilt doesn't allow wrapping, so we just do a simple clip
 		Common::Rect viewPort(_workingWindow.width(), _workingWindow.height());
-		viewPort.translate(0, -(_screenCenterY - _backgroundOffset));
+		viewPort.translate(0, -(_screenCentre.y - _backgroundOffset));
 		Common::Rect drawRect = _backgroundDirtyRect;
 		drawRect.clip(viewPort);
 		if (!drawRect.isEmpty())
-			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, drawRect.left, _screenCenterY - _backgroundOffset + drawRect.top);
+			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, drawRect.left, _screenCentre.y - _backgroundOffset + drawRect.top);
 
 		// Mark the dirty portion of the surface
 		_backgroundSurfaceDirtyRect = _backgroundDirtyRect;
-		_backgroundSurfaceDirtyRect.translate(0, _screenCenterY - _backgroundOffset);
+		_backgroundSurfaceDirtyRect.translate(0, _screenCentre.y - _backgroundOffset);
 
 	} else {
 		if (!_backgroundDirtyRect.isEmpty())
@@ -709,10 +714,12 @@ void RenderManager::clearMenuSurface(int32 colorkey) {
 void RenderManager::initSubArea(uint32 windowWidth, uint32 windowHeight, const Common::Rect &workingWindow) {
 	_workingWindow = workingWindow;
 
-	_subtitleSurface.free();
+	_subSurface.free();
 
-	_subtitleSurface.create(windowWidth, windowHeight - workingWindow.bottom, _pixelFormat);
-	_subtitleArea = Common::Rect(0, workingWindow.bottom, windowWidth, windowHeight);
+	_subSurface.create(windowWidth, windowHeight - workingWindow.bottom, _pixelFormat);
+	_subArea = Common::Rect(0, workingWindow.bottom, windowWidth, windowHeight);
+  if(_engine->isWidescreen())
+    _subArea.translate(0,-_subArea.height());
 }
 
 uint16 RenderManager::createSubArea(const Common::Rect &area) {
@@ -723,6 +730,14 @@ uint16 RenderManager::createSubArea(const Common::Rect &area) {
 	sub.timer = -1;
 	sub.todelete = false;
 	sub.r = area;
+	
+	//Original game subtitle scripts define subtitle rectangles relative to origin of original 640x480 display
+	//To allow arbitrary aspect ratios, we need to convert these so they are instead placed relative to screen/window centre.
+	//Screen/window centre should always coincide with working area centre!
+	sub.r.translate(_screenCentre.x - 320, _screenCentre.y - 240);
+  //If we are in widescreen mode, then shift the subtitle rectangle upwards to overlay the working window.	
+  if(_engine->isWidescreen())
+    sub.r.translate(0, -_subArea.height());
 
 	_subsList[_subid] = sub;
 
@@ -730,7 +745,7 @@ uint16 RenderManager::createSubArea(const Common::Rect &area) {
 }
 
 uint16 RenderManager::createSubArea() {
-	Common::Rect r(_subtitleArea.left, _subtitleArea.top, _subtitleArea.right, _subtitleArea.bottom);
+	Common::Rect r(_subArea.left, _subArea.top, _subArea.right, _subArea.bottom);
 	r.translate(-_workingWindow.left, -_workingWindow.top);
 	return createSubArea(r);
 }
@@ -770,28 +785,31 @@ void RenderManager::processSubs(uint16 deltatime) {
 	}
 
 	if (redraw) {
-		_subtitleSurface.fillRect(Common::Rect(_subtitleSurface.w, _subtitleSurface.h), 0);
+	  //Blank
+		_subSurface.fillRect(Common::Rect(_subSurface.w, _subSurface.h), 0); //Replace with colorkey for overlay mode
 
+    //
 		for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
 			OneSubtitle *sub = &it->_value;
 			if (sub->txt.size()) {
-				Graphics::Surface subtitleSurface;
-				subtitleSurface.create(sub->r.width(), sub->r.height(), _engine->_resourcePixelFormat);
-				_engine->getTextRenderer()->drawTextWithWordWrapping(sub->txt, subtitleSurface);
+				Graphics::Surface subSurface;
+				subSurface.create(sub->r.width(), sub->r.height(), _engine->_resourcePixelFormat);
+				_engine->getTextRenderer()->drawTextWithWordWrapping(sub->txt, subSurface);
 				Common::Rect empty;
-				blitSurfaceToSurface(subtitleSurface, empty, _subtitleSurface, sub->r.left - _subtitleArea.left + _workingWindow.left, sub->r.top - _subtitleArea.top + _workingWindow.top);
-				subtitleSurface.free();
+				blitSurfaceToSurface(subSurface, empty, _subSurface, sub->r.left - _subArea.left + _workingWindow.left, sub->r.top - _subArea.top + _workingWindow.top);
+				subSurface.free();
 			}
 			sub->redraw = false;
 		}
 
+    //Draw to screen
 		Common::Rect rect(
-			_subtitleArea.left,
-			_subtitleArea.top,
-			_subtitleArea.left + _subtitleSurface.w,
-			_subtitleArea.top + _subtitleSurface.h
+			_subArea.left,
+			_subArea.top,
+			_subArea.left + _subSurface.w,
+			_subArea.top + _subSurface.h
 		);
-		copyToScreen(_subtitleSurface, rect, 0, 0);
+		copyToScreen(_subSurface, rect, 0, 0);
 	}
 }
 
@@ -817,33 +835,33 @@ Common::Rect RenderManager::transformBackgroundSpaceRectToScreenSpace(const Comm
 	RenderTable::RenderState state = _renderTable.getRenderState();
 
 	if (state == RenderTable::PANORAMA) {
-		if (_backgroundOffset < _screenCenterX) {
-			Common::Rect rScreen(_screenCenterX + _backgroundOffset, _workingWindow.height());
+		if (_backgroundOffset < _screenCentre.x) {
+			Common::Rect rScreen(_screenCentre.x + _backgroundOffset, _workingWindow.height());
 			Common::Rect lScreen(_workingWindow.width() - rScreen.width(), _workingWindow.height());
 			lScreen.translate(_backgroundWidth - lScreen.width(), 0);
 			lScreen.clip(src);
 			rScreen.clip(src);
 			if (rScreen.width() < lScreen.width()) {
-				tmp.translate(_screenCenterX - _backgroundOffset - _backgroundWidth, 0);
+				tmp.translate(_screenCentre.x - _backgroundOffset - _backgroundWidth, 0);
 			} else {
-				tmp.translate(_screenCenterX - _backgroundOffset, 0);
+				tmp.translate(_screenCentre.x - _backgroundOffset, 0);
 			}
-		} else if (_backgroundWidth - _backgroundOffset < _screenCenterX) {
-			Common::Rect rScreen(_screenCenterX - (_backgroundWidth - _backgroundOffset), _workingWindow.height());
+		} else if (_backgroundWidth - _backgroundOffset < _screenCentre.x) {
+			Common::Rect rScreen(_screenCentre.x - (_backgroundWidth - _backgroundOffset), _workingWindow.height());
 			Common::Rect lScreen(_workingWindow.width() - rScreen.width(), _workingWindow.height());
 			lScreen.translate(_backgroundWidth - lScreen.width(), 0);
 			lScreen.clip(src);
 			rScreen.clip(src);
 			if (lScreen.width() < rScreen.width()) {
-				tmp.translate(_screenCenterX + (_backgroundWidth - _backgroundOffset), 0);
+				tmp.translate(_screenCentre.x + (_backgroundWidth - _backgroundOffset), 0);
 			} else {
-				tmp.translate(_screenCenterX - _backgroundOffset, 0);
+				tmp.translate(_screenCentre.x - _backgroundOffset, 0);
 			}
 		} else {
-			tmp.translate(_screenCenterX - _backgroundOffset, 0);
+			tmp.translate(_screenCentre.x - _backgroundOffset, 0);
 		}
 	} else if (state == RenderTable::TILT) {
-		tmp.translate(0, (_screenCenterY - _backgroundOffset));
+		tmp.translate(0, (_screenCentre.y - _backgroundOffset));
 	}
 
 	return tmp;
@@ -997,9 +1015,9 @@ void RenderManager::timedMessage(const Common::String &str, uint16 milsecs) {
 
 bool RenderManager::askQuestion(const Common::String &str) {
 	Graphics::Surface textSurface;
-	textSurface.create(_subtitleArea.width(), _subtitleArea.height(), _engine->_resourcePixelFormat);
+	textSurface.create(_subArea.width(), _subArea.height(), _engine->_resourcePixelFormat);
 	_engine->getTextRenderer()->drawTextWithWordWrapping(str, textSurface);
-	copyToScreen(textSurface, _subtitleArea, 0, 0);
+	copyToScreen(textSurface, _subArea, 0, 0);
 
 	_engine->stopClock();
 
@@ -1054,8 +1072,8 @@ bool RenderManager::askQuestion(const Common::String &str) {
 	}
 
 	// Draw over the text in order to clear it
-	textSurface.fillRect(Common::Rect(_subtitleArea.width(), _subtitleArea.height()), 0);
-	copyToScreen(textSurface, _subtitleArea, 0, 0);
+	textSurface.fillRect(Common::Rect(_subArea.width(), _subArea.height()), 0);
+	copyToScreen(textSurface, _subArea, 0, 0);
 
 	// Free the surface
 	textSurface.free();
@@ -1182,6 +1200,8 @@ void RenderManager::rotateTo(int16 _toPos, int16 _time) {
 	if (_renderTable.getRenderState() != RenderTable::PANORAMA)
 		return;
 
+  debug(1,"Rotating panorama to %d", _toPos);
+
 	if (_time == 0)
 		_time = 1;
 
@@ -1222,8 +1242,6 @@ void RenderManager::rotateTo(int16 _toPos, int16 _time) {
 		prepareBackground();
 		renderSceneToScreen();
 
-		_system->updateScreen();
-
 		_system->delayMillis(500 / _time);
 	}
 
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index 0b8408a5572..5901942d096 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -76,11 +76,8 @@ private:
 	 * edges of this Rectangle
 	 */
 	Common::Rect _workingWindow;
-
-	// Center of the screen in the x direction
-	const int _screenCenterX;
-	// Center of the screen in the y direction
-	const int _screenCenterY;
+	
+	const Common::Point _screenCentre; //Centre of the screen at current resolution
 	
 	
 	/**
@@ -110,15 +107,20 @@ private:
 	Common::Rect _backgroundSurfaceDirtyRect;
 
 	// A buffer for subtitles
-	Graphics::Surface _subtitleSurface;
+	Graphics::Surface _subSurface;
+	Graphics::ManagedSurface _subManagedSurface;
+	Common::Rect _subSurfaceDirtyRect;
 
 	// Rectangle for subtitles area
-	Common::Rect _subtitleArea;
+	Common::Rect _subArea;
 
 	// A buffer for menu drawing
 	Graphics::Surface _menuSurface;
 	Graphics::ManagedSurface _menuManagedSurface;
 	Common::Rect _menuSurfaceDirtyRect;
+	
+	//Buffer for video playback (render directly for speed; no backbuffer)
+	Graphics::ManagedSurface _vidManagedSurface;
 
 	// Rectangle for menu area
 	Common::Rect _menuArea;
@@ -144,13 +146,24 @@ private:
 	bool _doubleFPS;
 
 public:
-	void initialize();
+	void init(bool hiRes = false);  //TODO - implement this & add to engine initialisation!
 
 	/**
 	 * Renders the scene to the screen
 	 */
-	void renderSceneToScreen();
+	void renderSceneToScreen(bool videoPlaying = false);
+	
+	Graphics::ManagedSurface &getVidSurface(Common::Rect &dstRect);  //dstRect is defined relative to working window origin
+
 
+  //TODO - eliminate this function and all calls to it; do everything via ManagedSurface approach
+	/**
+	 *
+	 * @param src       Source surface
+	 * @param _srcRect  Rectangle defining area of target surface to blit to
+ 	 * @param srcLeft   X coord of area to blit within source
+	 * @param srcTop    Y coord of area to blit within source
+	 */	
 	void copyToScreen(const Graphics::Surface &surface, Common::Rect &rect, int16 srcLeft, int16 srcTop);
 
 	/**
diff --git a/engines/zvision/video/video.cpp b/engines/zvision/video/video.cpp
index 4faa9929d93..fbe715305e1 100644
--- a/engines/zvision/video/video.cpp
+++ b/engines/zvision/video/video.cpp
@@ -44,6 +44,8 @@ Video::VideoDecoder *ZVision::loadAnimation(const Common::Path &fileName) {
 	Common::String tmpFileName = fileName.baseName();
 	tmpFileName.toLowercase();
 	Video::VideoDecoder *animation = NULL;
+	
+ debug(1, "Loading animation %s", fileName.toString().c_str());
 
 	if (tmpFileName.hasSuffix(".rlf"))
 		animation = new RLFDecoder();
@@ -69,12 +71,26 @@ Video::VideoDecoder *ZVision::loadAnimation(const Common::Path &fileName) {
 	return animation;
 }
 
-void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &destRect, bool skippable, Subtitle *sub) {
-	Common::Rect dst = destRect;
-	// If destRect is empty, no specific scaling was requested. However, we may choose to do scaling anyway
+  /**
+   * Play video at specified location.
+   *
+   * Pauses clock & normal game loop for duration of video; will still update & render subtitles & cursor.
+   *
+   * @param vid       Source video
+   * @param dstRect   Rectangle to play video into, defined relative to working window origin; video will scale to rectangle automatically.
+ 	 * @param skippable Allow video to be skipped
+   * @param sub       Subtitle associated with video
+   */	
+	 
+void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, bool skippable, Subtitle *sub) {
+	Common::Rect dst = dstRect;
+	// If dstRect is empty, no specific scaling was requested. However, we may choose to do scaling anyway
 	if (dst.isEmpty())
 		dst = Common::Rect(vid.getWidth(), vid.getHeight());
 
+	Graphics::ManagedSurface &outSurface = _renderManager->getVidSurface(dst);
+  debug(1, "Playing video, size %d x %d", outSurface.w, outSurface.h);
+
 	Graphics::Surface *scaled = NULL;
 
 	if (vid.getWidth() != dst.width() || vid.getHeight() != dst.height()) {
@@ -82,8 +98,6 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &destRect,
 		scaled->create(dst.width(), dst.height(), vid.getPixelFormat());
 	}
 
-	uint16 x = _workingWindow.left + dst.left;
-	uint16 y = _workingWindow.top + dst.top;
 	uint16 finalWidth = dst.width() < _workingWindow.width() ? dst.width() : _workingWindow.width();
 	uint16 finalHeight = dst.height() < _workingWindow.height() ? dst.height() : _workingWindow.height();
 	bool showSubs = (_scriptManager->getStateValue(StateKey_Subtitles) == 1);
@@ -122,22 +136,20 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &destRect,
 			const Graphics::Surface *frame = vid.decodeNextFrame();
 			if (sub && showSubs)
 				sub->process(vid.getCurFrame());
-
 			if (frame) {
 				if (scaled) {
 					_renderManager->scaleBuffer(frame->getPixels(), scaled->getPixels(), frame->w, frame->h, frame->format.bytesPerPixel, scaled->w, scaled->h);
-					frame = scaled;
+					frame = scaled; 
 				}
-				Common::Rect rect = Common::Rect(x, y, x + finalWidth, y + finalHeight);
-				_renderManager->copyToScreen(*frame, rect, 0, 0);
+				Common::Rect rect = Common::Rect(finalWidth, finalHeight);
+				debug(2,"Blitting from area %d x %d to video output surface", frame->w, frame->h);
+				outSurface.simpleBlitFrom(*frame, rect, Common::Point(0,0));
 				_renderManager->processSubs(0);
 			}
 		}
-
 		// Always update the screen so the mouse continues to render
-		_system->updateScreen();
-
-		_system->delayMillis(vid.getTimeToNextFrame() / 2);
+		_renderManager->renderSceneToScreen(true);
+		_system->delayMillis(vid.getTimeToNextFrame() / 2); //Exponentially decaying delay
 	}
 
 	_cutscenesKeymap->setEnabled(false);


Commit: d4ac1784f857ec0316a1d21bd8bc0afd6c4cdd7f
    https://github.com/scummvm/scummvm/commit/d4ac1784f857ec0316a1d21bd8bc0afd6c4cdd7f
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:54+02:00

Commit Message:
ZVISION: Fix failure of fullscreen video to refresh.
Fix video screen location bug.
Improve subtitle rendering for widescreen, add black background mode.
Code cleanup & additional comments.
Adjust mouse position debug message priority.

# Conflicts:
#	engines/zvision/graphics/render_manager.cpp

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/scripting/menu.cpp
    engines/zvision/scripting/menu.h
    engines/zvision/text/subtitles.cpp
    engines/zvision/text/text.cpp
    engines/zvision/text/text.h
    engines/zvision/video/video.cpp
    engines/zvision/zvision.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index c452b89d272..c3bfb1debd7 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -69,7 +69,7 @@ RenderManager::RenderManager(ZVision *engine, uint32 windowWidth, uint32 windowH
 
 	_menuSurface.create(_menuArea.width(), _menuArea.height(), _pixelFormat);
 	_menuManagedSurface.create(_screenSurface, _menuArea);
-	_subManagedSurface.create(_screenSurface, _subArea);
+	_subManagedSurface.create(_screenSurface, _engine->_subArea);
 
 	initSubArea(windowWidth, windowHeight, workingWindow);
 }
@@ -87,8 +87,11 @@ RenderManager::~RenderManager() {
 	_screenSurface.free();
 }
 
-void RenderManager::renderSceneToScreen(bool videoPlaying) {
-  if(!videoPlaying) {
+bool RenderManager::renderSceneToScreen(bool overlayOnly, bool immediate) {
+
+  //TODO - add functionality to blank sidebars or letterbox bars as appropriate
+
+  if(!overlayOnly) {
 	  Graphics::Surface *out = &_warpedSceneSurface;
 	  Graphics::Surface *in = &_backgroundSurface;
 	  Common::Rect outWndDirtyRect;
@@ -140,32 +143,28 @@ void RenderManager::renderSceneToScreen(bool videoPlaying) {
 	  else {
 		  out = in;
 		  outWndDirtyRect = _backgroundSurfaceDirtyRect;
-	  }
-	  
-	  
+	  }	  
 	  _backgroundManagedSurface.simpleBlitFrom(*out); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
 	}
 	
 	_menuManagedSurface.transBlitFrom(_menuSurface, -1);
-	if(_engine->canRender())
-	  _screenSurface.update();
-
-  /*
-	if (!outWndDirtyRect.isEmpty()) {
-		Common::Rect rect = outWndDirtyRect;
-		rect.translate(_workingWindow.left,_workingWindow.top); //NB - feels like this should really be moveTo(), but that causes an offset bug when rendering doorknocker.  Suspect this is an irregularity elsewhere that will eventually need to be found & fixed, but can be tolerated for now.
-		
-  //Update dirty rectangle of screen
-		//copyToScreen(*out, rect, outWndDirtyRect.left, outWndDirtyRect.top);
-    copyToScreen(_backgroundManagedSurface, rect, outWndDirtyRect.left, outWndDirtyRect.top);
-	}
-	//*/
+  _subManagedSurface.transBlitFrom(_subSurface, -1);
+
+  if(_engine->canRender() || immediate) {
+    _screenSurface.update();
+    return true;
+  }
+  else {
+    debug(1,"Skipping screen update; engine forbids rendering at this time.");
+    return false;
+  }
 }
 
 Graphics::ManagedSurface &RenderManager::getVidSurface(Common::Rect &dstRect) {
   Common::Rect _dstRect = dstRect;
-  _dstRect.moveTo(_workingWindow.left, _workingWindow.top);
+  _dstRect.translate(_workingWindow.left, _workingWindow.top);
 	_vidManagedSurface.create(_screenSurface, _dstRect);
+	debug(1,"Obtaining managed video surface at %d,%d,%d,%d", _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
 	return _vidManagedSurface;
 }
 
@@ -184,11 +183,11 @@ void RenderManager::renderImageToBackground(const Common::Path &fileName, int16
 	surface.free();
 }
 
-void RenderManager::renderImageToBackground(const Common::Path &fileName, int16 destX, int16 destY, uint32 keycolor) {
+void RenderManager::renderImageToBackground(const Common::Path &fileName, int16 destX, int16 destY, uint32 colorkey) {
 	Graphics::Surface surface;
 	readImageToSurface(fileName, surface);
 
-	blitSurfaceToBkg(surface, destX, destY, keycolor);
+	blitSurfaceToBkg(surface, destX, destY, colorkey);
 	surface.free();
 }
 
@@ -532,7 +531,7 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Com
 		return;
 
 	Graphics::Surface *srcAdapted = src.convertTo(dst.format);
-	uint32 keycolor = colorkey & ((1 << (src.format.bytesPerPixel << 3)) - 1);
+	uint32 keycolor = colorkey & ((1 << (src.format.bytesPerPixel << 3)) - 1);  //TODO - figure out what the crap is going on here.
 
 	// Copy srcRect from src surface to dst surface
 	const byte *srcBuffer = (const byte *)srcAdapted->getBasePtr(srcRect.left, srcRect.top);
@@ -583,18 +582,7 @@ void RenderManager::blitSurfaceToBkgScaled(const Graphics::Surface &src, const C
 
 void RenderManager::blitSurfaceToMenu(const Graphics::Surface &src, int16 x, int16 y, int32 colorkey) {
 	Common::Rect empt;
-	Common::Point destPos{x,y};
-  Graphics::Surface *dstSurface = &_menuSurface;
-	if (colorkey >= 0) {
-		//blitSurfaceToSurface(src, empt, _menuSurface, x, y, colorkey);
-    blitSurfaceToSurface(src, empt, *dstSurface, x, y, colorkey);
-    //_menuManagedSurface.transBlitFrom(src,destPos,colorkey);
-  }
-	else {
-		//blitSurfaceToSurface(src, empt, _menuSurface, x, y);
-		blitSurfaceToSurface(src, empt, *dstSurface, x, y);
-    //_menuManagedSurface.blitFrom(src,destPos);
-  }
+	blitSurfaceToSurface(src, empt, _menuSurface, x, y, colorkey);
   //*/
 	Common::Rect dirty(src.w, src.h);
 	dirty.moveTo(x, y);
@@ -707,10 +695,19 @@ void RenderManager::prepareBackground() {
 }
 
 void RenderManager::clearMenuSurface(int32 colorkey) {
+  //TODO - reinstate more efficient dirtyrect system
+  //TODO - blank upper letterbox area when NOT in widescreen mode.
 	_menuSurfaceDirtyRect = Common::Rect(0, 0, _menuSurface.w, _menuSurface.h);
 	_menuSurface.fillRect(_menuSurfaceDirtyRect, colorkey);
 }
 
+void RenderManager::clearSubSurface(int32 colorkey) {
+  //TODO - reinstate more efficient dirtyrect system
+  //TODO - blank lower letterbox area when NOT in widescreen mode.
+	_subSurfaceDirtyRect = Common::Rect(0, 0, _subSurface.w, _subSurface.h);
+	_subSurface.fillRect(_subSurfaceDirtyRect, colorkey);
+}
+
 void RenderManager::initSubArea(uint32 windowWidth, uint32 windowHeight, const Common::Rect &workingWindow) {
 	_workingWindow = workingWindow;
 
@@ -720,11 +717,11 @@ void RenderManager::initSubArea(uint32 windowWidth, uint32 windowHeight, const C
 	_subArea = Common::Rect(0, workingWindow.bottom, windowWidth, windowHeight);
   if(_engine->isWidescreen())
     _subArea.translate(0,-_subArea.height());
+  clearSubSurface();
 }
 
 uint16 RenderManager::createSubArea(const Common::Rect &area) {
 	_subid++;
-
 	OneSubtitle sub;
 	sub.redraw = false;
 	sub.timer = -1;
@@ -739,6 +736,8 @@ uint16 RenderManager::createSubArea(const Common::Rect &area) {
   if(_engine->isWidescreen())
     sub.r.translate(0, -_subArea.height());
 
+  debug(1,"Creating subtitle area %d, dimenisions %dx%d, screen location %d,%d", _subid, sub.r.width(), sub.r.height(), sub.r.left, sub.r.top);
+
 	_subsList[_subid] = sub;
 
 	return _subid;
@@ -770,6 +769,8 @@ void RenderManager::updateSubArea(uint16 id, const Common::String &txt) {
 
 void RenderManager::processSubs(uint16 deltatime) {
 	bool redraw = false;
+	
+	//Update all subtitles' respective timers; delete expired subtitles.
 	for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
 		if (it->_value.timer != -1) {
 			it->_value.timer -= deltatime;
@@ -785,31 +786,23 @@ void RenderManager::processSubs(uint16 deltatime) {
 	}
 
 	if (redraw) {
-	  //Blank
-		_subSurface.fillRect(Common::Rect(_subSurface.w, _subSurface.h), 0); //Replace with colorkey for overlay mode
+	  //Blank subtitle buffer
+	  clearSubSurface();
 
-    //
+    //Cycle through all extant subtitles, if subtitle contains text then render it to an auxiliary buffer within a rectangle specified by that subtitle & blit into main subtitle buffer
 		for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
 			OneSubtitle *sub = &it->_value;
 			if (sub->txt.size()) {
 				Graphics::Surface subSurface;
 				subSurface.create(sub->r.width(), sub->r.height(), _engine->_resourcePixelFormat);
-				_engine->getTextRenderer()->drawTextWithWordWrapping(sub->txt, subSurface);
+				subSurface.fillRect(Common::Rect(sub->r.width(), sub->r.height()), -1);
+				_engine->getTextRenderer()->drawTextWithWordWrapping(sub->txt, subSurface, _engine->isWidescreen());
 				Common::Rect empty;
-				blitSurfaceToSurface(subSurface, empty, _subSurface, sub->r.left - _subArea.left + _workingWindow.left, sub->r.top - _subArea.top + _workingWindow.top);
+				blitSurfaceToSurface(subSurface, empty, _subSurface, sub->r.left - _subArea.left + _workingWindow.left, sub->r.top - _subArea.top + _workingWindow.top, -1);
 				subSurface.free();
 			}
 			sub->redraw = false;
 		}
-
-    //Draw to screen
-		Common::Rect rect(
-			_subArea.left,
-			_subArea.top,
-			_subArea.left + _subSurface.w,
-			_subArea.top + _subSurface.h
-		);
-		copyToScreen(_subSurface, rect, 0, 0);
 	}
 }
 
@@ -1008,16 +1001,17 @@ void RenderManager::bkgFill(uint8 r, uint8 g, uint8 b) {
 #endif
 
 void RenderManager::timedMessage(const Common::String &str, uint16 milsecs) {
+  //TODO - rework to use new renderscene system
 	uint16 msgid = createSubArea();
 	updateSubArea(msgid, str);
 	deleteSubArea(msgid, milsecs);
 }
 
 bool RenderManager::askQuestion(const Common::String &str) {
-	Graphics::Surface textSurface;
-	textSurface.create(_subArea.width(), _subArea.height(), _engine->_resourcePixelFormat);
-	_engine->getTextRenderer()->drawTextWithWordWrapping(str, textSurface);
-	copyToScreen(textSurface, _subArea, 0, 0);
+	Graphics::Surface backupSubSurface;
+	backupSubSurface.copyFrom(_subSurface);
+	_engine->getTextRenderer()->drawTextWithWordWrapping(str, _subSurface, _engine->isWidescreen());
+	renderSceneToScreen(true); 
 
 	_engine->stopClock();
 
@@ -1064,25 +1058,25 @@ bool RenderManager::askQuestion(const Common::String &str) {
 				}
 			}
 		}
-		_system->updateScreen();
+	  renderSceneToScreen(true); 
 		if (_doubleFPS)
 			_system->delayMillis(33);
 		else
 			_system->delayMillis(66);
 	}
 
-	// Draw over the text in order to clear it
-	textSurface.fillRect(Common::Rect(_subArea.width(), _subArea.height()), 0);
-	copyToScreen(textSurface, _subArea, 0, 0);
+  //Clear question graphics by restoring saved subtitle buffer
+  _subSurface.copyFrom(backupSubSurface);
 
 	// Free the surface
-	textSurface.free();
+	backupSubSurface.free();
 
 	_engine->startClock();
 	return result == 2;
 }
 
 void RenderManager::delayedMessage(const Common::String &str, uint16 milsecs) {
+  //TODO - rework to use new renderscene system
 	uint16 msgid = createSubArea();
 	updateSubArea(msgid, str);
 	processSubs(0);
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index 5901942d096..85747e7538c 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -150,8 +150,9 @@ public:
 
 	/**
 	 * Renders the scene to the screen
+	 . Returns true if screen was updated
 	 */
-	void renderSceneToScreen(bool videoPlaying = false);
+	bool renderSceneToScreen(bool overlayOnly = false, bool immediate = false);
 	
 	Graphics::ManagedSurface &getVidSurface(Common::Rect &dstRect);  //dstRect is defined relative to working window origin
 
@@ -264,7 +265,7 @@ public:
 	void blitSurfaceToBkgScaled(const Graphics::Surface &src, const Common::Rect &_dstRect, int32 colorkey = -1);
 
 	// Blitting surface-to-menu methods
-	void blitSurfaceToMenu(const Graphics::Surface &src, int16 x, int16 y, int32 colorkey = -1);
+	void blitSurfaceToMenu(const Graphics::Surface &src, int16 x, int16 y, int32 colorkey = 0);
 
 	// Subtitles methods
 
@@ -295,7 +296,10 @@ public:
 	Graphics::Surface *loadImage(const Common::Path &file, bool transposed);
 
 	// Clear whole/area of menu surface
-	void clearMenuSurface(int32 colorkey = 0);
+	void clearMenuSurface(int32 colorkey = -1);
+	
+	// Clear whole/area of subtitle surface
+	void clearSubSurface(int32 colorkey = -1);
 
 	// Copy needed portion of background surface to workingWindow surface
 	void prepareBackground();
diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index 6bc4b547893..f70d8d339f9 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -118,7 +118,7 @@ void MenuManager::onMouseDown(const Common::Point &Pos) {
         redraw = true;
       }
   }
-  debug("mouse position %d %d", Pos.x, Pos.y);
+  debug(1, "mouse position %d %d", Pos.x, Pos.y);
 }
 
 void MenuManager::onMouseMove(const Common::Point &Pos) {
@@ -178,7 +178,7 @@ void MenuManager::process(uint32 deltatime) {
       redraw = true;
     }
 	if(redraw) {
-	  _engine->getRenderManager()->clearMenuSurface(colorkey);
+	  _engine->getRenderManager()->clearMenuSurface();
   	redrawAll();
   	redraw = false;
   }
diff --git a/engines/zvision/scripting/menu.h b/engines/zvision/scripting/menu.h
index 8f9b1dafcd8..8a871f912fb 100644
--- a/engines/zvision/scripting/menu.h
+++ b/engines/zvision/scripting/menu.h
@@ -115,7 +115,6 @@ protected:
 	bool prevInMenu = false;
 	bool redraw = true;
 	int mouseOnItem = -1;
-	static const int32 colorkey = -1;  //Transparency color for compositing menu over playfield
 	static const uint8 hMainMenu = 32;
   int8 mainClicked = -1;
 
diff --git a/engines/zvision/text/subtitles.cpp b/engines/zvision/text/subtitles.cpp
index 987bbaa4f9c..b338ab012f8 100644
--- a/engines/zvision/text/subtitles.cpp
+++ b/engines/zvision/text/subtitles.cpp
@@ -36,17 +36,18 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool upscaleToH
 			Common::String str = file.readLine();
 			if (str.lastChar() == '~')
 				str.deleteLastChar();
-
 			if (str.matchString("*Initialization*", true)) {
 				// Not used
-			} else if (str.matchString("*Rectangle*", true)) {
+			} 
+			else if (str.matchString("*Rectangle*", true)) {
 				int32 x1, y1, x2, y2;
 				sscanf(str.c_str(), "%*[^:]:%d %d %d %d", &x1, &y1, &x2, &y2);
 				Common::Rect rct = Common::Rect(x1, y1, x2, y2);
 				if (upscaleToHires)
 					_engine->getRenderManager()->upscaleRect(rct);
 				_areaId = _engine->getRenderManager()->createSubArea(rct);
-			} else if (str.matchString("*TextFile*", true)) {
+			} 
+			else if (str.matchString("*TextFile*", true)) {
 				char filename[64];
 				sscanf(str.c_str(), "%*[^:]:%s", filename);
 				Common::File txt;
@@ -62,7 +63,8 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool upscaleToH
 					}
 					txt.close();
 				}
-			} else {
+			} 
+			else {
 				int32 st;
 				int32 en;
 				int32 sb;
@@ -85,7 +87,6 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool upscaleToH
 Subtitle::~Subtitle() {
 	if (_areaId != -1)
 		_engine->getRenderManager()->deleteSubArea(_areaId);
-
 	_subs.clear();
 }
 
diff --git a/engines/zvision/text/text.cpp b/engines/zvision/text/text.cpp
index 0e1fc69737f..de438fd530e 100644
--- a/engines/zvision/text/text.cpp
+++ b/engines/zvision/text/text.cpp
@@ -238,7 +238,6 @@ TextChange TextStyleState::parseStyle(const Common::String &str, int16 len) {
 void TextStyleState::readAllStyles(const Common::String &txt) {
 	int16 startTextPosition = -1;
 	int16 endTextPosition = -1;
-
 	for (uint16 i = 0; i < txt.size(); i++) {
 		if (txt[i] == '<')
 			startTextPosition = i;
@@ -250,13 +249,11 @@ void TextStyleState::readAllStyles(const Common::String &txt) {
 				}
 			}
 		}
-
 	}
 }
 
 void TextStyleState::updateFontWithTextState(StyledTTFont &font) {
 	uint tempStyle = 0;
-
 	if (_bold) {
 		tempStyle |= StyledTTFont::TTF_STYLE_BOLD;
 	}
@@ -272,26 +269,28 @@ void TextStyleState::updateFontWithTextState(StyledTTFont &font) {
 	if (_sharp) {
 		tempStyle |= StyledTTFont::TTF_STYLE_SHARP;
 	}
-
 	font.loadFont(_fontname, _size, tempStyle);
 }
 
 void TextRenderer::drawTextWithJustification(const Common::String &text, StyledTTFont &font, uint32 color, Graphics::Surface &dest, int lineY, TextJustification justify) {
-	if (justify == TEXT_JUSTIFY_LEFT)
-		font.drawString(&dest, text, 0, lineY, dest.w, color, Graphics::kTextAlignLeft);
-	else if (justify == TEXT_JUSTIFY_CENTER)
-		font.drawString(&dest, text, 0, lineY, dest.w, color, Graphics::kTextAlignCenter);
-	else if (justify == TEXT_JUSTIFY_RIGHT)
-		font.drawString(&dest, text, 0, lineY, dest.w, color, Graphics::kTextAlignRight);
+  switch(justify) {
+  case TEXT_JUSTIFY_LEFT :
+	  font.drawString(&dest, text, 0, lineY, dest.w, color, Graphics::kTextAlignLeft);
+	  break;
+  case TEXT_JUSTIFY_CENTER :
+	  font.drawString(&dest, text, 0, lineY, dest.w, color, Graphics::kTextAlignCenter);
+	  break;
+  case TEXT_JUSTIFY_RIGHT :
+	  font.drawString(&dest, text, 0, lineY, dest.w, color, Graphics::kTextAlignRight);
+    break;
+	}
 }
 
 int32 TextRenderer::drawText(const Common::String &text, TextStyleState &state, Graphics::Surface &dest) {
 	StyledTTFont font(_engine);
 	state.updateFontWithTextState(font);
-
 	uint32 color = _engine->_resourcePixelFormat.RGBToColor(state._red, state._green, state._blue);
 	drawTextWithJustification(text, font, color, dest, 0, state._justification);
-
 	return font.getStringWidth(text);
 }
 
@@ -307,7 +306,7 @@ struct TextSurface {
 	uint _lineNumber;
 };
 
-void TextRenderer::drawTextWithWordWrapping(const Common::String &text, Graphics::Surface &dest) {
+void TextRenderer::drawTextWithWordWrapping(const Common::String &text, Graphics::Surface &dest, bool blackFrame) {
 	Common::Array<TextSurface> textSurfaces;
 	Common::Array<uint> lineWidths;
 	Common::Array<TextJustification> lineJustifications;
@@ -337,12 +336,13 @@ void TextRenderer::drawTextWithWordWrapping(const Common::String &text, Graphics
 	uint i = 0u;
 	uint stringlen = text.size();
 
+  //Parse entirety of supplied text
 	while (i < stringlen) {
+	  //Style tag encountered?
 		if (text[i] == '<') {
 			// Flush the currentWord to the currentSentence
 			currentSentence += currentWord;
 			sentenceWidth += wordWidth;
-
 			// Reset the word variables
 			currentWord.clear();
 			wordWidth = 0;
@@ -479,25 +479,28 @@ void TextRenderer::drawTextWithWordWrapping(const Common::String &text, Graphics
 	// Render out any remaining words/sentences
 	if (!currentWord.empty() || !currentSentence.empty()) {
 		currentSentence += currentWord;
-		sentenceWidth += wordWidth;
-
+		sentenceWidth += wordWidth;		
 		textSurfaces.push_back(TextSurface(font.renderSolidText(currentSentence, currentState.getTextColor(_engine)), sentencePixelOffset, currentLineNumber));
 	}
-
 	lineWidths.push_back(lineWidth + sentenceWidth);
 	lineJustifications.push_back(currentState._justification);
-
 	for (Common::Array<TextSurface>::iterator iter = textSurfaces.begin(); iter != textSurfaces.end(); ++iter) {
 		Common::Rect empty;
-
-		if (lineJustifications[iter->_lineNumber] == TEXT_JUSTIFY_LEFT) {
-			_engine->getRenderManager()->blitSurfaceToSurface(*iter->_surface, empty, dest, iter->_surfaceOffset.x, iter->_surfaceOffset.y, 0);
-		} else if (lineJustifications[iter->_lineNumber] == TEXT_JUSTIFY_CENTER) {
-			_engine->getRenderManager()->blitSurfaceToSurface(*iter->_surface, empty, dest, ((dest.w - lineWidths[iter->_lineNumber]) / 2) + iter->_surfaceOffset.x, iter->_surfaceOffset.y, 0);
-		} else if (lineJustifications[iter->_lineNumber] == TEXT_JUSTIFY_RIGHT) {
-			_engine->getRenderManager()->blitSurfaceToSurface(*iter->_surface, empty, dest, dest.w - lineWidths[iter->_lineNumber]  + iter->_surfaceOffset.x, iter->_surfaceOffset.y, 0);
-		}
-
+		int16 Xpos = iter->_surfaceOffset.x;
+    switch (lineJustifications[iter->_lineNumber]) {
+      case TEXT_JUSTIFY_LEFT :
+	      break;
+      case TEXT_JUSTIFY_CENTER :
+        Xpos += ((dest.w - lineWidths[iter->_lineNumber]) / 2);
+	      break;
+      case TEXT_JUSTIFY_RIGHT :
+        Xpos += dest.w - lineWidths[iter->_lineNumber];
+	      break;
+    }
+    if(blackFrame)
+      _engine->getRenderManager()->blitSurfaceToSurface(*iter->_surface, empty, dest, Xpos, iter->_surfaceOffset.y);
+    else
+      _engine->getRenderManager()->blitSurfaceToSurface(*iter->_surface, empty, dest, Xpos, iter->_surfaceOffset.y, 0);
 		// Release memory
 		iter->_surface->free();
 		delete iter->_surface;
@@ -518,7 +521,6 @@ Common::U32String readWideLine(Common::SeekableReadStream &stream) {
 			// End of the line. Break
 			break;
 		}
-
 		asciiString += value;
 	}
 	return asciiString;
diff --git a/engines/zvision/text/text.h b/engines/zvision/text/text.h
index 255ad123082..fd59b7b0a46 100644
--- a/engines/zvision/text/text.h
+++ b/engines/zvision/text/text.h
@@ -76,7 +76,7 @@ public:
 
 	void drawTextWithJustification(const Common::String &text, StyledTTFont &font, uint32 color, Graphics::Surface &dest, int lineY, TextJustification jusification);
 	int32 drawText(const Common::String &text, TextStyleState &state, Graphics::Surface &dest);
-	void drawTextWithWordWrapping(const Common::String &text, Graphics::Surface &dest);
+	void drawTextWithWordWrapping(const Common::String &text, Graphics::Surface &dest, bool blackFrame = false);
 
 private:
 	ZVision *_engine;
diff --git a/engines/zvision/video/video.cpp b/engines/zvision/video/video.cpp
index fbe715305e1..e908f34728a 100644
--- a/engines/zvision/video/video.cpp
+++ b/engines/zvision/video/video.cpp
@@ -89,7 +89,7 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 		dst = Common::Rect(vid.getWidth(), vid.getHeight());
 
 	Graphics::ManagedSurface &outSurface = _renderManager->getVidSurface(dst);
-  debug(1, "Playing video, size %d x %d", outSurface.w, outSurface.h);
+  debug(1, "Playing video, size %d x %d, at working window offset %d, %d", outSurface.w, outSurface.h, dst.left, dst.top);
 
 	Graphics::Surface *scaled = NULL;
 
@@ -142,13 +142,14 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 					frame = scaled; 
 				}
 				Common::Rect rect = Common::Rect(finalWidth, finalHeight);
-				debug(2,"Blitting from area %d x %d to video output surface", frame->w, frame->h);
+				//TODO - fix problem with full-screen video playback not rendering to screen.
+				debug(2,"Blitting from area %d x %d to video output surface at area %d, %d", frame->w, frame->h, dst.left, dst.top);
 				outSurface.simpleBlitFrom(*frame, rect, Common::Point(0,0));
 				_renderManager->processSubs(0);
 			}
 		}
-		// Always update the screen so the mouse continues to render
-		_renderManager->renderSceneToScreen(true);
+		// Always update the screen so the mouse continues to render & video does not skip
+		_renderManager->renderSceneToScreen(true,true);
 		_system->delayMillis(vid.getTimeToNextFrame() / 2); //Exponentially decaying delay
 	}
 
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index a2a436f87f5..644d8dbdd28 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -326,24 +326,18 @@ Common::Error ZVision::run() {
 
 		_cursorManager->setItemID(_scriptManager->getStateValue(StateKey_InventoryItem));
 
-		processEvents();
+		processEvents();  //NB rotateTo or playVideo event will pause clock & call renderSceneToScreen() directly.
 		_renderManager->updateRotation();
-
 		_scriptManager->update(deltaTime);
 		_menu->process(deltaTime);
 
 		// Render the backBuffer to the screen
 		_renderManager->prepareBackground();
-		_renderManager->processSubs(deltaTime); //TODO - alter to blit subs to intermediate buffer, then handle this buffer in renderscenetoscreen, in same manner as menu
-		_renderManager->renderSceneToScreen();
-
-		// Update the screen
-		if (canRender()) {
-			_system->updateScreen();
+		_renderManager->processSubs(deltaTime);
+		if(_renderManager->renderSceneToScreen())
 			_renderedFrameCount++;
-		} else {
+		else
 			_frameRenderDelay--;
-		}
 
 		// Calculate the frame delay based off a desired frame time
 		int delay = _desiredFrameTime - int32(_system->getMillis() - currentTime);
@@ -353,10 +347,8 @@ Common::Error ZVision::run() {
 		if (_doubleFPS) {
 			delay >>= 1;
 		}
-
 		_system->delayMillis(delay);
 	}
-
 	return Common::kNoError;
 }
 
@@ -371,6 +363,7 @@ void ZVision::pauseEngineIntern(bool pause) {
 }
 
 void ZVision::setRenderDelay(uint delay) {
+  debug(2,"Setting framerenderdelay to %d", delay);
 	_frameRenderDelay = delay;
 }
 
@@ -397,23 +390,34 @@ void ZVision::initScreen() {
 	uint16 workingWindowWidth = (getGameId() == GID_NEMESIS) ? ZNM_WORKING_WINDOW_WIDTH : ZGI_WORKING_WINDOW_WIDTH;
 	uint16 workingWindowHeight = (getGameId() == GID_NEMESIS) ? ZNM_WORKING_WINDOW_HEIGHT : ZGI_WORKING_WINDOW_HEIGHT;
 	_workingWindow = Common::Rect(
-						 (WINDOW_WIDTH  -  workingWindowWidth) / 2,
-						 (WINDOW_HEIGHT - workingWindowHeight) / 2,
-						((WINDOW_WIDTH  -  workingWindowWidth) / 2) + workingWindowWidth,
-						((WINDOW_HEIGHT - workingWindowHeight) / 2) + workingWindowHeight
-					 );
+    (WINDOW_WIDTH  -  workingWindowWidth) / 2,
+    (WINDOW_HEIGHT - workingWindowHeight) / 2,
+    ((WINDOW_WIDTH  -  workingWindowWidth) / 2) + workingWindowWidth,
+    ((WINDOW_HEIGHT - workingWindowHeight) / 2) + workingWindowHeight
+  );
 
 	uint16 menuAreaHeight = (getGameId() == GID_NEMESIS) ? ZNM_MENU_HEIGHT : ZGI_MENU_HEIGHT;
+	
   _menuArea = Common::Rect(
-						 (WINDOW_WIDTH  -  workingWindowWidth) / 2,
-						 0,
-						((WINDOW_WIDTH  -  workingWindowWidth) / 2) + workingWindowWidth,
-						menuAreaHeight
-					 );
-
-  if(_widescreen)
+    (WINDOW_WIDTH  -  workingWindowWidth) / 2,
+    0,
+    ((WINDOW_WIDTH  -  workingWindowWidth) / 2) + workingWindowWidth,
+    menuAreaHeight
+  );
+ 
+	uint16 subAreaHeight = (getGameId() == GID_NEMESIS) ? ZNM_SUBTITLE_HEIGHT : ZGI_SUBTITLE_HEIGHT;
+ 
+  _subArea = Common::Rect(
+    0,
+    WINDOW_HEIGHT - subAreaHeight,
+    WINDOW_WIDTH,
+    WINDOW_HEIGHT
+  );
+
+  if(_widescreen) {
     _menuArea.moveTo(_workingWindow.left, _workingWindow.top);
-
+    _subArea.moveTo(0, _workingWindow.bottom - _subArea.height());
+  }
 	initGraphics(WINDOW_WIDTH, WINDOW_HEIGHT, &_screenPixelFormat);
 }
 
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index 5151c6c1d08..60b9e6bba04 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -69,13 +69,13 @@ class Subtitle;
 class MidiManager;
 
 enum {
-	WINDOW_WIDTH = 640,//640,
-	WINDOW_HEIGHT = 480,//480,
+	WINDOW_WIDTH = 640,//Original 640,
+	WINDOW_HEIGHT = 480,//Original 480,
 	WINDOW_WIDTH_WIDE = 854,
 	WINDOW_HEIGHT_WIDE = 480,
 
-	HIRES_WINDOW_WIDTH = 800,
-	HIRES_WINDOW_HEIGHT = 600,
+	HIRES_WINDOW_WIDTH = 800, //Original 800
+	HIRES_WINDOW_HEIGHT = 600,  //Original 600
 
 	// Zork Nemesis working window sizes (original aspect ratio 8:5)
 	ZNM_WORKING_WINDOW_WIDTH = 512, //Original 512
@@ -263,6 +263,10 @@ public:
 	int getFPS() const {
 		return _fps;
 	}
+	
+	bool isWidescreen() {
+	  return _widescreen;
+	}
 
 	void syncSoundSettings() override;
 


Commit: 22fba73b8e8bb395011388d6b10f2bdce5ee444e
    https://github.com/scummvm/scummvm/commit/22fba73b8e8bb395011388d6b10f2bdce5ee444e
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:54+02:00

Commit Message:
ZVISION: Remove redundant copyToScreen() function.

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index c3bfb1debd7..09efd0e8994 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -168,13 +168,6 @@ Graphics::ManagedSurface &RenderManager::getVidSurface(Common::Rect &dstRect) {
 	return _vidManagedSurface;
 }
 
-void RenderManager::copyToScreen(const Graphics::Surface &surface, Common::Rect &dstRect, int16 srcLeft, int16 srcTop) {
-	Common::Rect srcRect = dstRect;
-	srcRect.moveTo(srcLeft, srcTop);
-	_screenSurface.simpleBlitFrom(surface, srcRect, Common::Point(dstRect.left, dstRect.top));  
-  _screenSurface.update();
-}
-
 void RenderManager::renderImageToBackground(const Common::Path &fileName, int16 destX, int16 destY) {
 	Graphics::Surface surface;
 	readImageToSurface(fileName, surface);
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index 85747e7538c..3f988ea0657 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -156,17 +156,6 @@ public:
 	
 	Graphics::ManagedSurface &getVidSurface(Common::Rect &dstRect);  //dstRect is defined relative to working window origin
 
-
-  //TODO - eliminate this function and all calls to it; do everything via ManagedSurface approach
-	/**
-	 *
-	 * @param src       Source surface
-	 * @param _srcRect  Rectangle defining area of target surface to blit to
- 	 * @param srcLeft   X coord of area to blit within source
-	 * @param srcTop    Y coord of area to blit within source
-	 */	
-	void copyToScreen(const Graphics::Surface &surface, Common::Rect &rect, int16 srcLeft, int16 srcTop);
-
 	/**
 	 * Blits the image or a portion of the image to the background.
 	 *


Commit: 26a30438b8d284006c0ae037538115a9495cf201
    https://github.com/scummvm/scummvm/commit/26a30438b8d284006c0ae037538115a9495cf201
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:54+02:00

Commit Message:
COMMON: Add center() & origin() utility functions to Rect.

Changed paths:
    common/rect.h


diff --git a/common/rect.h b/common/rect.h
index d0cf597a521..5923b3aef13 100644
--- a/common/rect.h
+++ b/common/rect.h
@@ -378,15 +378,23 @@ struct Rect {
 		debugC(debuglevel, debugChannel, "%s %d, %d, %d, %d", caption, left, top, right, bottom);
 	}
 
-	/**
-	 * Create a rectangle around the given center.
-	 * @note The center point is rounded up and left when given an odd width and height.
-	 */
+  /**
+  * Create a rectangle around the given center.
+  * @note The center point is rounded up and left when given an odd width and height.
+  */
 	static Rect center(int16 cx, int16 cy, int16 w, int16 h) {
 		int x = cx - w / 2, y = cy - h / 2;
 		return Rect(x, y, x + w, y + h);
 	}
 
+  /**
+  * Return a Point indicating the centroid of the rectangle
+  * @note The center point is rounded up and left when width and/or height are odd
+  */
+  Point center() {
+    return Point((left+right)/2, (bottom+top)/2);
+  }	
+
 	/**
 	 * Given target surface with size clip, this function ensures that
 	 * blit arguments @p dst and @p rect are within the @p clip rectangle,


Commit: 961a6e6aedc0db6c345daae97f9c8cfae912c237
    https://github.com/scummvm/scummvm/commit/961a6e6aedc0db6c345daae97f9c8cfae912c237
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:54+02:00

Commit Message:
ZVISION: Refactor to improve renderManager encapsulation.
Add struct ScreenLayout to zvision.h.
Rename workingWindow to workingArea for consistency.
Add screen resolution change for widescreen mode.
Additional debug() messages added.
Remove redundant functions.
Bugs: Subtitles & other text do not render over working area in widescreen mode.
Subtitle & menu area not blanking correctly in conventional screen layout.

Changed paths:
    engines/zvision/core/events.cpp
    engines/zvision/graphics/effects/fog.cpp
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/menu.h
    engines/zvision/text/subtitles.cpp
    engines/zvision/video/video.cpp
    engines/zvision/zvision.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/core/events.cpp b/engines/zvision/core/events.cpp
index 1dfb97f717b..8e9a87e8d0f 100644
--- a/engines/zvision/core/events.cpp
+++ b/engines/zvision/core/events.cpp
@@ -292,8 +292,10 @@ void ZVision::processEvents() {
 }
 
 void ZVision::onMouseMove(const Common::Point &pos) {
+  debug(6,"ZVision::onMouseMove()");
 	_menu->onMouseMove(pos);
 	Common::Point imageCoord(_renderManager->screenSpaceToImageSpace(pos));
+	Common::Rect _workingArea = _renderManager->getWorkingArea();
 
 	bool cursorWasChanged = false;
 
@@ -328,32 +330,33 @@ void ZVision::onMouseMove(const Common::Point &pos) {
 	//               ^
 
 	// Clip the horizontal mouse position to the working window
+	debug(6,"Mouse pos.x, %d, clipping with %d+1, %d+1", pos.x, _workingArea.left, _workingArea.right);
 	Common::Point clippedPos = pos;
-	clippedPos.x = CLIP<int16>(pos.x, _workingWindow.left + 1, _workingWindow.right - 1);
+	clippedPos.x = CLIP<int16>(pos.x, _workingArea.left + 1, _workingArea.right - 1);
 
-	if (_workingWindow.contains(clippedPos) && !_menu->inMenu()) {
+	if (_workingArea.contains(clippedPos) && !_menu->inMenu()) {
 		cursorWasChanged = _scriptManager->onMouseMove(clippedPos, imageCoord);
 
 		RenderTable::RenderState renderState = _renderManager->getRenderTable()->getRenderState();
 		if (renderState == RenderTable::PANORAMA) {
-			if (clippedPos.x >= _workingWindow.left && clippedPos.x < _workingWindow.left + ROTATION_SCREEN_EDGE_OFFSET) {
+			if (clippedPos.x >= _workingArea.left && clippedPos.x < _workingArea.left + ROTATION_SCREEN_EDGE_OFFSET) {
 
 				int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
 				if (mspeed <= 0) {
 					mspeed = 25;
 				}
-				_mouseVelocity  = MIN(((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (clippedPos.x - _workingWindow.left)) - mspeed).toInt(), -1);
+				_mouseVelocity  = MIN(((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (clippedPos.x - _workingArea.left)) - mspeed).toInt(), -1);
 
 
 				_cursorManager->changeCursor(CursorIndex_Left);
 				cursorWasChanged = true;
-			} else if (clippedPos.x <= _workingWindow.right && clippedPos.x > _workingWindow.right - ROTATION_SCREEN_EDGE_OFFSET) {
+			} else if (clippedPos.x <= _workingArea.right && clippedPos.x > _workingArea.right - ROTATION_SCREEN_EDGE_OFFSET) {
 
 				int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
 				if (mspeed <= 0) {
 					mspeed = 25;
 				}
-				_mouseVelocity  = MAX((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (clippedPos.x - _workingWindow.right + ROTATION_SCREEN_EDGE_OFFSET)).toInt(), 1);
+				_mouseVelocity  = MAX((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (clippedPos.x - _workingArea.right + ROTATION_SCREEN_EDGE_OFFSET)).toInt(), 1);
 
 				_cursorManager->changeCursor(CursorIndex_Right);
 				cursorWasChanged = true;
@@ -361,23 +364,23 @@ void ZVision::onMouseMove(const Common::Point &pos) {
 				_mouseVelocity = 0;
 			}
 		} else if (renderState == RenderTable::TILT) {
-			if (clippedPos.y >= _workingWindow.top && clippedPos.y < _workingWindow.top + ROTATION_SCREEN_EDGE_OFFSET) {
+			if (clippedPos.y >= _workingArea.top && clippedPos.y < _workingArea.top + ROTATION_SCREEN_EDGE_OFFSET) {
 
 				int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
 				if (mspeed <= 0) {
 					mspeed = 25;
 				}
-				_mouseVelocity  = MIN(((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (pos.y - _workingWindow.top)) - mspeed).toInt(), -1);
+				_mouseVelocity  = MIN(((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (pos.y - _workingArea.top)) - mspeed).toInt(), -1);
 
 				_cursorManager->changeCursor(CursorIndex_UpArr);
 				cursorWasChanged = true;
-			} else if (clippedPos.y <= _workingWindow.bottom && clippedPos.y > _workingWindow.bottom - ROTATION_SCREEN_EDGE_OFFSET) {
+			} else if (clippedPos.y <= _workingArea.bottom && clippedPos.y > _workingArea.bottom - ROTATION_SCREEN_EDGE_OFFSET) {
 
 				int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
 				if (mspeed <= 0) {
 					mspeed = 25;
 				}
-				_mouseVelocity = MAX((Common::Rational(MAX_ROTATION_SPEED, ROTATION_SCREEN_EDGE_OFFSET) * (pos.y - _workingWindow.bottom + ROTATION_SCREEN_EDGE_OFFSET)).toInt(), 1);
+				_mouseVelocity = MAX((Common::Rational(MAX_ROTATION_SPEED, ROTATION_SCREEN_EDGE_OFFSET) * (pos.y - _workingArea.bottom + ROTATION_SCREEN_EDGE_OFFSET)).toInt(), 1);
 
 				_cursorManager->changeCursor(CursorIndex_DownArr);
 				cursorWasChanged = true;
diff --git a/engines/zvision/graphics/effects/fog.cpp b/engines/zvision/graphics/effects/fog.cpp
index 2669eb99827..82af1de4ea0 100644
--- a/engines/zvision/graphics/effects/fog.cpp
+++ b/engines/zvision/graphics/effects/fog.cpp
@@ -111,7 +111,7 @@ const Graphics::Surface *FogFx::draw(const Graphics::Surface &srcSubRect) {
 void FogFx::update() {
 	_pos += _engine->getScriptManager()->getStateValue(StateKey_EF9_Speed);
 	_pos %= _fog.w;
-
+  debug(2,"Updating fog effect");
 	uint8 dr = _engine->getScriptManager()->getStateValue(StateKey_EF9_R);
 	uint8 dg = _engine->getScriptManager()->getStateValue(StateKey_EF9_G);
 	uint8 db = _engine->getScriptManager()->getStateValue(StateKey_EF9_B);
diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 09efd0e8994..f5be698f08e 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -43,54 +43,100 @@
 
 namespace ZVision {
 
-RenderManager::RenderManager(ZVision *engine, uint32 windowWidth, uint32 windowHeight, const Common::Rect workingWindow, const Common::Rect menuArea, const Graphics::PixelFormat pixelFormat, bool doubleFPS)
+RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const Graphics::PixelFormat pixelFormat, bool doubleFPS, bool widescreen)
 	: _engine(engine),
 	  _system(engine->_system),
-	  _workingWindow(workingWindow),
-	  _screenCentre(windowWidth / 2, windowHeight / 2),
+	  _layout(layout),
+	  _screenArea(_layout.screenArea),
+	  _screenCentre(_screenArea.center()),
+	  _workingArea(_layout.workingArea),
+	  _menuArea(_layout.menuArea),
+	  _textArea(_layout.textArea),
 	  _pixelFormat(pixelFormat),
 	  _backgroundWidth(0),
 	  _backgroundHeight(0),
 	  _backgroundOffset(0),
-	  _renderTable(_workingWindow.width(), _workingWindow.height()),
+	  _renderTable(_layout.workingArea.width(), _layout.workingArea.height()),
 	  _doubleFPS(doubleFPS),
-	  _subid(0),
-	  _menuArea(menuArea) {
-	  
-  _screenSurface.create(WINDOW_WIDTH, WINDOW_HEIGHT, _pixelFormat);
-	_screenSurface.setTransparentColor(-1);
-	_screenSurface.clear();
-  
-	_backgroundSurface.create(_workingWindow.width(), _workingWindow.height(), _pixelFormat);
-	_backgroundManagedSurface.create(_screenSurface, _workingWindow);
-
-	_effectSurface.create(_workingWindow.width(), _workingWindow.height(), _pixelFormat);
-	_warpedSceneSurface.create(_workingWindow.width(), _workingWindow.height(), _pixelFormat);
-
+	  _widescreen(widescreen),
+	  _subid(0) {
+	debug(1,"creating render manager");
+  //Define graphics modes & screen subarea geometry
+	Graphics::ModeList modes;
+  if (_widescreen) {
+    //*
+    _workingArea.moveTo(0,0);
+    _screenArea = _workingArea;
+    _screenCentre = _screenArea.center();
+    //*/
+    _menuArea.moveTo(_workingArea.origin());
+    _textArea.moveTo(_workingArea.left, _workingArea.bottom - _textArea.height());
+  } 
+  modes.push_back(Graphics::Mode(_screenArea.width(), _screenArea.height()));
+#if defined(USE_MPEG2) && defined(USE_A52)
+	if (_engine->getGameId() == GID_GRANDINQUISITOR && (_engine->getFeatures() & ADGF_DVD))
+		modes.push_back(Graphics::Mode(HIRES_WINDOW_WIDTH, HIRES_WINDOW_HEIGHT));
+#endif
+	initGraphicsModes(modes);
+  //Create backbuffers
+	_backgroundSurface.create(_workingArea.width(), _workingArea.height(), _pixelFormat);
+	_effectSurface.create(_workingArea.width(), _workingArea.height(), _pixelFormat);
+	_warpedSceneSurface.create(_workingArea.width(), _workingArea.height(), _pixelFormat);
 	_menuSurface.create(_menuArea.width(), _menuArea.height(), _pixelFormat);
-	_menuManagedSurface.create(_screenSurface, _menuArea);
-	_subManagedSurface.create(_screenSurface, _engine->_subArea);
-
-	initSubArea(windowWidth, windowHeight, workingWindow);
+	_subSurface.create(_textArea.width(), _textArea.height(), _pixelFormat);
+	debug(1,"render manager created");
 }
 
 RenderManager::~RenderManager() {
 	_currentBackgroundImage.free();
 	_backgroundSurface.free();
-	_backgroundManagedSurface.free();
+	_workingManagedSurface.free();
 	_effectSurface.free();
 	_warpedSceneSurface.free();
 	_menuSurface.free();
 	_menuManagedSurface.free();
 	_subSurface.free();
-	_subManagedSurface.free();
-	_screenSurface.free();
+	_textManagedSurface.free();
+	_screen.free();
 }
 
-bool RenderManager::renderSceneToScreen(bool overlayOnly, bool immediate) {
+void RenderManager::initialize(bool hiRes) {
+  debug(1,"Initializing render manager");
+  _hiRes = hiRes;
+  //Screen
+  if(_hiRes)
+    _screen.create(HIRES_WINDOW_WIDTH, HIRES_WINDOW_HEIGHT, _pixelFormat);
+  else
+    _screen.create(_screenArea.width(), _screenArea.height(), _pixelFormat);
+	_screen.setTransparentColor(-1);
+	_screen.clear();
+	//Managed screen subsurfaces
+	if(_hiRes) {
+	  Common::Rect hiResWorkingArea = _workingArea;
+  	upscaleRect(hiResWorkingArea);
+  	_workingManagedSurface.create(_screen, hiResWorkingArea);
+	  Common::Rect hiResTextArea = _textArea;
+  	upscaleRect(hiResTextArea);
+  	_textManagedSurface.create(_screen, hiResTextArea);
+	}
+	else {
+    debug("_menuArea %d, %d, %d, %d", _menuArea.left, _menuArea.top, _menuArea.right, _menuArea.bottom);
+  	_workingManagedSurface.create(_screen, _workingArea);
+	  _menuManagedSurface.create(_screen, _menuArea);
+  	_textManagedSurface.create(_screen, _textArea);
+	}
+	//Clear backbuffer surfaces
+	clearMenuSurface();
+  clearSubSurface();
+  
+  //Set hardware/window resolution
+  initGraphics(_screen.w, _screen.h, &_engine->_screenPixelFormat); 
+	debug(1,"Render manager initialized");
+}
 
+bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
+  debug(10,"renderSceneToScreen");
   //TODO - add functionality to blank sidebars or letterbox bars as appropriate
-
   if(!overlayOnly) {
 	  Graphics::Surface *out = &_warpedSceneSurface;
 	  Graphics::Surface *in = &_backgroundSurface;
@@ -99,7 +145,7 @@ bool RenderManager::renderSceneToScreen(bool overlayOnly, bool immediate) {
 	  //Apply graphical effects to temporary effects buffer and/or directly to current background image, as appropriate
 	  if (!_effects.empty()) {
 		  bool copied = false;
-		  const Common::Rect windowRect(_workingWindow.width(), _workingWindow.height());
+		  const Common::Rect windowRect(_workingArea.width(), _workingArea.height());
 
 		  for (EffectsList::iterator it = _effects.begin(); it != _effects.end(); it++) {
 			  Common::Rect rect = (*it)->getRegion();
@@ -121,6 +167,7 @@ bool RenderManager::renderSceneToScreen(bool overlayOnly, bool immediate) {
 					  post = (*it)->draw(_effectSurface.getSubArea(rect));
 				  Common::Rect empty;
 				  blitSurfaceToSurface(*post, empty, _effectSurface, screenSpaceLocation.left, screenSpaceLocation.top);
+				  debug(1,"windowRect %d,%d,%d,%d, screenSpaceLocation %d,%d,%d,%d", windowRect.left, windowRect.top, windowRect.bottom, windowRect.right, screenSpaceLocation.left, screenSpaceLocation.top, screenSpaceLocation.bottom, screenSpaceLocation.right);
 				  screenSpaceLocation.clip(windowRect);
 				  if (_backgroundSurfaceDirtyRect .isEmpty()) {
 					  _backgroundSurfaceDirtyRect = screenSpaceLocation;
@@ -137,33 +184,35 @@ bool RenderManager::renderSceneToScreen(bool overlayOnly, bool immediate) {
 		  if (!_backgroundSurfaceDirtyRect.isEmpty()) {
 			  _renderTable.mutateImage(&_warpedSceneSurface, in);
 			  out = &_warpedSceneSurface;
-			  outWndDirtyRect = Common::Rect(_workingWindow.width(), _workingWindow.height());
+			  outWndDirtyRect = Common::Rect(_workingArea.width(), _workingArea.height());
 		  }
 	  } 
 	  else {
 		  out = in;
 		  outWndDirtyRect = _backgroundSurfaceDirtyRect;
 	  }	  
-	  _backgroundManagedSurface.simpleBlitFrom(*out); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
+	  _workingManagedSurface.simpleBlitFrom(*out); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
 	}
 	
 	_menuManagedSurface.transBlitFrom(_menuSurface, -1);
-  _subManagedSurface.transBlitFrom(_subSurface, -1);
+  _textManagedSurface.transBlitFrom(_subSurface, -1);
 
   if(_engine->canRender() || immediate) {
-    _screenSurface.update();
+    _screen.update();
+    debug(10,"~renderSceneToScreen");
     return true;
   }
   else {
     debug(1,"Skipping screen update; engine forbids rendering at this time.");
+    debug(10,"~renderSceneToScreen");
     return false;
   }
 }
 
 Graphics::ManagedSurface &RenderManager::getVidSurface(Common::Rect &dstRect) {
   Common::Rect _dstRect = dstRect;
-  _dstRect.translate(_workingWindow.left, _workingWindow.top);
-	_vidManagedSurface.create(_screenSurface, _dstRect);
+  _dstRect.translate(_workingArea.left, _workingArea.top);
+	_vidManagedSurface.create(_screen, _dstRect);
 	debug(1,"Obtaining managed video surface at %d,%d,%d,%d", _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
 	return _vidManagedSurface;
 }
@@ -171,7 +220,6 @@ Graphics::ManagedSurface &RenderManager::getVidSurface(Common::Rect &dstRect) {
 void RenderManager::renderImageToBackground(const Common::Path &fileName, int16 destX, int16 destY) {
 	Graphics::Surface surface;
 	readImageToSurface(fileName, surface);
-
 	blitSurfaceToBkg(surface, destX, destY);
 	surface.free();
 }
@@ -179,7 +227,6 @@ void RenderManager::renderImageToBackground(const Common::Path &fileName, int16
 void RenderManager::renderImageToBackground(const Common::Path &fileName, int16 destX, int16 destY, uint32 colorkey) {
 	Graphics::Surface surface;
 	readImageToSurface(fileName, surface);
-
 	blitSurfaceToBkg(surface, destX, destY, colorkey);
 	surface.free();
 }
@@ -291,9 +338,10 @@ void RenderManager::readImageToSurface(const Common::Path &fileName, Graphics::S
 }
 
 const Common::Point RenderManager::screenSpaceToImageSpace(const Common::Point &point) {
-	if (_workingWindow.contains(point)) {
+  debug(9,"screenSpaceToImageSpace()");
+	if (_workingArea.contains(point)) {
 		// Convert from screen space to working window space
-		Common::Point newPoint(point - Common::Point(_workingWindow.left, _workingWindow.top));
+		Common::Point newPoint(point - Common::Point(_workingArea.left, _workingArea.top));
 
 		RenderTable::RenderState state = _renderTable.getRenderState();
 		if (state == RenderTable::PANORAMA || state == RenderTable::TILT) {
@@ -315,9 +363,10 @@ const Common::Point RenderManager::screenSpaceToImageSpace(const Common::Point &
 			newPoint.x += _backgroundWidth;
 		if (newPoint.y < 0)
 			newPoint.y += _backgroundHeight;
-
+    debug(9,"~screenSpaceToImageSpace()");
 		return newPoint;
 	} else {
+    debug(9,"~screenSpaceToImageSpace()");
 		return Common::Point(0, 0);
 	}
 }
@@ -339,7 +388,6 @@ void RenderManager::setBackgroundPosition(int offset) {
 		if (_backgroundOffset != offset)
 			_backgroundDirtyRect = Common::Rect(_backgroundWidth, _backgroundHeight);
 	_backgroundOffset = offset;
-
 	_engine->getScriptManager()->setStateValue(StateKey_ViewPos, offset);
 }
 
@@ -404,6 +452,7 @@ void RenderManager::scaleBuffer(const void *src, void *dst, uint32 srcWidth, uin
 //ORIGINAL FUNCTION
 //*
 void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect , Graphics::Surface &dst, int _x, int _y) {
+  debug(9,"blitSurfaceToSurface");
 	Common::Rect srcRect = _srcRect;
 	Common::Point dstPos = Common::Point(_x,_y);
 	//Default to using whole source surface
@@ -512,6 +561,7 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Com
 //*/
 
 void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect , Graphics::Surface &dst, int _x, int _y, uint32 colorkey) {
+  debug(9,"blitSurfaceToSurface");
 	Common::Rect srcRect = _srcRect;
 	if (srcRect.isEmpty())
 		srcRect = Common::Rect(src.w, src.h);
@@ -587,6 +637,7 @@ void RenderManager::blitSurfaceToMenu(const Graphics::Surface &src, int16 x, int
 }
 
 Graphics::Surface *RenderManager::getBkgRect(Common::Rect &rect) {
+  debug(11,"getBkgRect()");
 	Common::Rect dst = rect;
 	dst.clip(_backgroundWidth, _backgroundHeight);
 
@@ -614,12 +665,13 @@ Graphics::Surface *RenderManager::loadImage(const Common::Path &file, bool trans
 }
 
 void RenderManager::prepareBackground() {
+  debug(11,"prepareBackground()");
 	_backgroundDirtyRect.clip(_backgroundWidth, _backgroundHeight);
 	RenderTable::RenderState state = _renderTable.getRenderState();
 
 	if (state == RenderTable::PANORAMA) {
 		// Calculate the visible portion of the background
-		Common::Rect viewPort(_workingWindow.width(), _workingWindow.height());
+		Common::Rect viewPort(_workingArea.width(), _workingArea.height());
 		viewPort.translate(-(_screenCentre.x - _backgroundOffset), 0);
 		Common::Rect drawRect = _backgroundDirtyRect;
 		drawRect.clip(viewPort);
@@ -664,7 +716,7 @@ void RenderManager::prepareBackground() {
 		}
 	} else if (state == RenderTable::TILT) {
 		// Tilt doesn't allow wrapping, so we just do a simple clip
-		Common::Rect viewPort(_workingWindow.width(), _workingWindow.height());
+		Common::Rect viewPort(_workingArea.width(), _workingArea.height());
 		viewPort.translate(0, -(_screenCentre.y - _backgroundOffset));
 		Common::Rect drawRect = _backgroundDirtyRect;
 		drawRect.clip(viewPort);
@@ -684,7 +736,9 @@ void RenderManager::prepareBackground() {
 	// Clear the dirty rect since everything is clean now
 	_backgroundDirtyRect = Common::Rect();
 
-	_backgroundSurfaceDirtyRect.clip(_workingWindow.width(), _workingWindow.height());
+	_backgroundSurfaceDirtyRect.clip(_workingArea.width(), _workingArea.height());
+	
+  debug(11,"~prepareBackground()");
 }
 
 void RenderManager::clearMenuSurface(int32 colorkey) {
@@ -701,17 +755,18 @@ void RenderManager::clearSubSurface(int32 colorkey) {
 	_subSurface.fillRect(_subSurfaceDirtyRect, colorkey);
 }
 
-void RenderManager::initSubArea(uint32 windowWidth, uint32 windowHeight, const Common::Rect &workingWindow) {
-	_workingWindow = workingWindow;
-
+/*
+//TODO - confirm redundancy and remove
+void RenderManager::initSubArea(uint32 windowWidth, uint32 windowHeight, const Common::Rect workingArea) {
+	_workingArea = workingArea;
 	_subSurface.free();
-
-	_subSurface.create(windowWidth, windowHeight - workingWindow.bottom, _pixelFormat);
-	_subArea = Common::Rect(0, workingWindow.bottom, windowWidth, windowHeight);
+	_subSurface.create(windowWidth, windowHeight - workingArea.bottom, _pixelFormat);
+	_textArea = Common::Rect(0, workingArea.bottom, windowWidth, windowHeight);
   if(_engine->isWidescreen())
-    _subArea.translate(0,-_subArea.height());
+    _textArea.translate(0,-_textArea.height());
   clearSubSurface();
 }
+//*/
 
 uint16 RenderManager::createSubArea(const Common::Rect &area) {
 	_subid++;
@@ -721,15 +776,15 @@ uint16 RenderManager::createSubArea(const Common::Rect &area) {
 	sub.todelete = false;
 	sub.r = area;
 	
-	//Original game subtitle scripts define subtitle rectangles relative to origin of original 640x480 display
-	//To allow arbitrary aspect ratios, we need to convert these so they are instead placed relative to screen/window centre.
-	//Screen/window centre should always coincide with working area centre!
+	//Original game subtitle scripts appear to define subtitle rectangles relative to origin of working area.
+	//To allow arbitrary aspect ratios, we need to instead place these relative to origin of text area.
+	//This will allow the managed text area to then be arbitrarily placed on the screen to suit different aspect ratios.
 	sub.r.translate(_screenCentre.x - 320, _screenCentre.y - 240);
   //If we are in widescreen mode, then shift the subtitle rectangle upwards to overlay the working window.	
   if(_engine->isWidescreen())
-    sub.r.translate(0, -_subArea.height());
+    sub.r.translate(0, -_textArea.height());
 
-  debug(1,"Creating subtitle area %d, dimenisions %dx%d, screen location %d,%d", _subid, sub.r.width(), sub.r.height(), sub.r.left, sub.r.top);
+  debug(1,"Creating subtitle area %d, dimenisions %dx%d, working window location %d,%d, screen location", _subid, sub.r.width(), sub.r.height(),  sub.r.left, sub.r.top);
 
 	_subsList[_subid] = sub;
 
@@ -737,8 +792,8 @@ uint16 RenderManager::createSubArea(const Common::Rect &area) {
 }
 
 uint16 RenderManager::createSubArea() {
-	Common::Rect r(_subArea.left, _subArea.top, _subArea.right, _subArea.bottom);
-	r.translate(-_workingWindow.left, -_workingWindow.top);
+	Common::Rect r(_textArea.left, _textArea.top, _textArea.right, _textArea.bottom);
+	r.translate(-_workingArea.left, -_workingArea.top);
 	return createSubArea(r);
 }
 
@@ -761,6 +816,7 @@ void RenderManager::updateSubArea(uint16 id, const Common::String &txt) {
 }
 
 void RenderManager::processSubs(uint16 deltatime) {
+  debug(5,"processSubs()");
 	bool redraw = false;
 	
 	//Update all subtitles' respective timers; delete expired subtitles.
@@ -788,15 +844,16 @@ void RenderManager::processSubs(uint16 deltatime) {
 			if (sub->txt.size()) {
 				Graphics::Surface subSurface;
 				subSurface.create(sub->r.width(), sub->r.height(), _engine->_resourcePixelFormat);
-				subSurface.fillRect(Common::Rect(sub->r.width(), sub->r.height()), -1);
+				subSurface.fillRect(Common::Rect(sub->r.width(), sub->r.height()), -1); //TODO Unnecessary operation?  Check later.
 				_engine->getTextRenderer()->drawTextWithWordWrapping(sub->txt, subSurface, _engine->isWidescreen());
 				Common::Rect empty;
-				blitSurfaceToSurface(subSurface, empty, _subSurface, sub->r.left - _subArea.left + _workingWindow.left, sub->r.top - _subArea.top + _workingWindow.top, -1);
+				blitSurfaceToSurface(subSurface, empty, _subSurface, sub->r.left - _textArea.left + _workingArea.left, sub->r.top - _textArea.top + _workingArea.top, -1);
 				subSurface.free();
 			}
 			sub->redraw = false;
 		}
 	}
+  debug(5,"~processSubs()");
 }
 
 Common::Point RenderManager::getBkgSize() {
@@ -817,13 +874,14 @@ void RenderManager::deleteEffect(uint32 ID) {
 }
 
 Common::Rect RenderManager::transformBackgroundSpaceRectToScreenSpace(const Common::Rect &src) {
+  debug(10,"transformBackgroundSpaceRectToScreenSpace");
 	Common::Rect tmp = src;
 	RenderTable::RenderState state = _renderTable.getRenderState();
 
 	if (state == RenderTable::PANORAMA) {
 		if (_backgroundOffset < _screenCentre.x) {
-			Common::Rect rScreen(_screenCentre.x + _backgroundOffset, _workingWindow.height());
-			Common::Rect lScreen(_workingWindow.width() - rScreen.width(), _workingWindow.height());
+			Common::Rect rScreen(_screenCentre.x + _backgroundOffset, _workingArea.height());
+			Common::Rect lScreen(_workingArea.width() - rScreen.width(), _workingArea.height());
 			lScreen.translate(_backgroundWidth - lScreen.width(), 0);
 			lScreen.clip(src);
 			rScreen.clip(src);
@@ -833,8 +891,8 @@ Common::Rect RenderManager::transformBackgroundSpaceRectToScreenSpace(const Comm
 				tmp.translate(_screenCentre.x - _backgroundOffset, 0);
 			}
 		} else if (_backgroundWidth - _backgroundOffset < _screenCentre.x) {
-			Common::Rect rScreen(_screenCentre.x - (_backgroundWidth - _backgroundOffset), _workingWindow.height());
-			Common::Rect lScreen(_workingWindow.width() - rScreen.width(), _workingWindow.height());
+			Common::Rect rScreen(_screenCentre.x - (_backgroundWidth - _backgroundOffset), _workingArea.height());
+			Common::Rect lScreen(_workingArea.width() - rScreen.width(), _workingArea.height());
 			lScreen.translate(_backgroundWidth - lScreen.width(), 0);
 			lScreen.clip(src);
 			rScreen.clip(src);
@@ -1069,11 +1127,12 @@ bool RenderManager::askQuestion(const Common::String &str) {
 }
 
 void RenderManager::delayedMessage(const Common::String &str, uint16 milsecs) {
-  //TODO - rework to use new renderscene system
+  //TODO - find bug in current render system; shows up with widescreen disabled, but not with it enabled.
 	uint16 msgid = createSubArea();
 	updateSubArea(msgid, str);
+  debug(1,"initiating delayed message: %s to subtitle id %d", str.c_str(), msgid);
 	processSubs(0);
-	renderSceneToScreen();
+	renderSceneToScreen(true);
 	_engine->stopClock();
 
 	uint32 stopTime = _system->getMillis() + milsecs;
@@ -1086,7 +1145,7 @@ void RenderManager::delayedMessage(const Common::String &str, uint16 milsecs) {
 			         evnt.kbd.keycode == Common::KEYCODE_ESCAPE))
 				break;
 		}
-		_system->updateScreen();
+	  renderSceneToScreen(true);
 		if (_doubleFPS)
 			_system->delayMillis(33);
 		else
@@ -1099,6 +1158,7 @@ void RenderManager::delayedMessage(const Common::String &str, uint16 milsecs) {
 void RenderManager::showDebugMsg(const Common::String &msg, int16 delay) {
 	uint16 msgid = createSubArea();
 	updateSubArea(msgid, msg);
+  debug(1,"initiating in-game debug message: %s to subtitle id %d", msg.c_str(), msgid);
 	deleteSubArea(msgid, delay);
 }
 
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index 3f988ea0657..03574b98b96 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -50,7 +50,9 @@ namespace ZVision {
 
 class RenderManager {
 public:
-	RenderManager(ZVision *engine, uint32 windowWidth, uint32 windowHeight, const Common::Rect workingWindow, const Common::Rect menuArea, const Graphics::PixelFormat pixelFormat, bool doubleFPS);
+  //TODO - eliminate this; old system
+//	RenderManager(ZVision *engine, uint32 windowWidth, uint32 windowHeight, const Common::Rect workingArea, const Common::Rect menuArea, const Graphics::PixelFormat pixelFormat, bool doubleFPS);
+	RenderManager(ZVision *engine, const ScreenLayout layout, const Graphics::PixelFormat pixelFormat, bool doubleFPS, bool widescreen = false);
 	~RenderManager();
 
 private:
@@ -69,21 +71,27 @@ private:
 	ZVision *_engine;
 	OSystem *_system;
 	const Graphics::PixelFormat _pixelFormat;
+	const ScreenLayout _layout;
+	bool _hiRes = false;
 
 	/**
-	 * A Rectangle centered inside the actual window. All in-game coordinates
+	 * A Rectangle representing the screen/window resolution.
+	 */	
+	Common::Rect _screenArea;
+	
+	Common::Point _screenCentre; //Centre of the screen at current resolution
+
+	/**
+	 * A Rectangle placed inside _screenArea All in-game coordinates
 	 * are given in this coordinate space. Also, all images are clipped to the
 	 * edges of this Rectangle
 	 */
-	Common::Rect _workingWindow;
-	
-	const Common::Point _screenCentre; //Centre of the screen at current resolution
-	
+	Common::Rect _workingArea;
 	
 	/**
 	Managed surface representing physical screen; dirty rectangles will be handled automatically by this from now on
     */
-	Graphics::Screen _screenSurface;
+	Graphics::Screen _screen;
 
 	/** A buffer for background image that's being used to create the background */
 	Graphics::Surface _currentBackgroundImage;
@@ -103,18 +111,18 @@ private:
 	// If it's a normal scene, the pixels will be blitted directly to the screen
 	// If it's a panorma / tilt scene, the pixels will be first warped to _warpedSceneSurface
 	Graphics::Surface _backgroundSurface;
-	Graphics::ManagedSurface _backgroundManagedSurface;
+	Graphics::ManagedSurface _workingManagedSurface;
 	Common::Rect _backgroundSurfaceDirtyRect;
 
-	// A buffer for subtitles
+	// Buffer for subtitles
 	Graphics::Surface _subSurface;
-	Graphics::ManagedSurface _subManagedSurface;
 	Common::Rect _subSurfaceDirtyRect;
 
-	// Rectangle for subtitles area
-	Common::Rect _subArea;
+	// Rectangle for subtitles & other messages
+	Graphics::ManagedSurface _textManagedSurface;
+	Common::Rect _textArea;
 
-	// A buffer for menu drawing
+	// Buffer for menu drawing
 	Graphics::Surface _menuSurface;
 	Graphics::ManagedSurface _menuManagedSurface;
 	Common::Rect _menuSurfaceDirtyRect;
@@ -144,17 +152,21 @@ private:
 	EffectsList _effects;
 
 	bool _doubleFPS;
+	bool _widescreen;
 
 public:
-	void init(bool hiRes = false);  //TODO - implement this & add to engine initialisation!
+	void initialize(bool hiRes = false);
 
 	/**
 	 * Renders the scene to the screen
 	 . Returns true if screen was updated
 	 */
-	bool renderSceneToScreen(bool overlayOnly = false, bool immediate = false);
+	bool renderSceneToScreen(bool immediate = false, bool overlayOnly = false);
 	
 	Graphics::ManagedSurface &getVidSurface(Common::Rect &dstRect);  //dstRect is defined relative to working window origin
+	
+	Common::Rect getMenuArea() {return _menuArea;}
+	Common::Rect getWorkingArea() {return _workingArea;}
 
 	/**
 	 * Blits the image or a portion of the image to the background.
@@ -206,6 +218,8 @@ public:
 	 */
 	void setBackgroundPosition(int offset);
 
+
+
 	/**
 	 * Converts a point in screen coordinate space to image coordinate space
 	 *
@@ -257,8 +271,7 @@ public:
 	void blitSurfaceToMenu(const Graphics::Surface &src, int16 x, int16 y, int32 colorkey = 0);
 
 	// Subtitles methods
-
-	void initSubArea(uint32 windowWidth, uint32 windowHeight, const Common::Rect &workingWindow);
+	//void initSubArea(uint32 windowWidth, uint32 windowHeight, const Common::Rect workingArea);
 
 	// Create subtitle area and return ID
 	uint16 createSubArea(const Common::Rect &area);
@@ -290,7 +303,7 @@ public:
 	// Clear whole/area of subtitle surface
 	void clearSubSurface(int32 colorkey = -1);
 
-	// Copy needed portion of background surface to workingWindow surface
+	// Copy needed portion of background surface to workingArea surface
 	void prepareBackground();
 
 	/**
diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index ae4a8829fca..f91200c1f85 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -996,15 +996,13 @@ bool ActionStreamVideo::execute() {
 
 	decoder = _engine->loadAnimation(_fileName);
 	Subtitle *sub = (subtitleExists) ? new Subtitle(_engine, subpath, switchToHires) : NULL;
-
 	_engine->getCursorManager()->showMouse(false);
 
 	if (switchToHires) {
-		_engine->initHiresScreen();
-		destRect = Common::Rect(40, -40, 760, 440);
-		Common::Rect workingWindow = _engine->_workingWindow;
-		workingWindow.translate(0, -40);
-		_engine->getRenderManager()->initSubArea(HIRES_WINDOW_WIDTH, HIRES_WINDOW_HEIGHT, workingWindow);
+		_engine->getRenderManager()->initialize(true);
+		destRect = Common::Rect(40, -40, 760, 440); //Placed relative to working window origin, of course.
+		//ZGI hi-res video resolution = 720x480, with baked-in letterboxing around video at 720x387 resolution (at origin 0,77) conforming to playfield aspect ratio 0f 1.86
+		//At 800x600 screen resolution, with original video origin position of (40,-40), the letterboxed are will play at position 40,37.  Weird.
 	}
 
 	// WORKAROUND for what appears to be a script bug. When riding with
@@ -1018,22 +1016,14 @@ bool ActionStreamVideo::execute() {
 	// simply pause the ScummVM mixer during the ride.
 
 	bool pauseBackgroundMusic = _engine->getGameId() == GID_GRANDINQUISITOR && (_fileName == "hp3ea021.avi" || _fileName == "hp4ea051.avi");
-
-	if (pauseBackgroundMusic) {
+	if (pauseBackgroundMusic)
 		_engine->_mixer->pauseAll(true);
-	}
-
 	_engine->playVideo(*decoder, destRect, _skippable, sub);
-
-	if (pauseBackgroundMusic) {
+	if (pauseBackgroundMusic)
 		_engine->_mixer->pauseAll(false);
-	}
-
-	if (switchToHires) {
-		_engine->initScreen();
-		_engine->getRenderManager()->initSubArea(WINDOW_WIDTH, WINDOW_HEIGHT, _engine->_workingWindow);
-	}
 
+	if (switchToHires)
+		_engine->getRenderManager()->initialize(false);
 	_engine->getCursorManager()->showMouse(true);
 
 	delete decoder;
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 34786880646..61b02ff7fc9 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -113,7 +113,7 @@ MusicNode::~MusicNode() {
 		_engine->getScriptManager()->setStateValue(_key, 2);
 	if (_sub)
 		delete _sub;
-	debug(1, "MusicNode: %d destroyed", _key);
+	debug(2, "MusicNode: %d destroyed", _key);
 }
 
 void MusicNode::setDeltaVolume(uint8 volume) {
diff --git a/engines/zvision/scripting/menu.h b/engines/zvision/scripting/menu.h
index 8a871f912fb..178a9db9560 100644
--- a/engines/zvision/scripting/menu.h
+++ b/engines/zvision/scripting/menu.h
@@ -44,7 +44,7 @@ enum {
 
 struct MenuParams {
   int16 wxButs[4][2];   //Widths & X positions of main menu buttons; {Save, Restore, Prefs, Quit}
-  int16 wMain;  //Widths & X position of main menu background
+  int16 wMain;  //Width of main menu background
   int8 idleFrame; //Frame to display of unselected main menu button
   int8 activeFrame; //Frame to display of selected main menu button when mouse is down
   int8 clickedFrame; //Frame to display of selected main menu button when mouse is down
diff --git a/engines/zvision/text/subtitles.cpp b/engines/zvision/text/subtitles.cpp
index b338ab012f8..72c07320b2f 100644
--- a/engines/zvision/text/subtitles.cpp
+++ b/engines/zvision/text/subtitles.cpp
@@ -46,6 +46,7 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool upscaleToH
 				if (upscaleToHires)
 					_engine->getRenderManager()->upscaleRect(rct);
 				_areaId = _engine->getRenderManager()->createSubArea(rct);
+				debug(1,"Original subtitle script rectangle coordinates: l%d, t%d, r%d, b%d", x1, y1, x2, y2);
 			} 
 			else if (str.matchString("*TextFile*", true)) {
 				char filename[64];
diff --git a/engines/zvision/video/video.cpp b/engines/zvision/video/video.cpp
index e908f34728a..c455ea59ce5 100644
--- a/engines/zvision/video/video.cpp
+++ b/engines/zvision/video/video.cpp
@@ -59,15 +59,12 @@ Video::VideoDecoder *ZVision::loadAnimation(const Common::Path &fileName) {
 #endif
 	else
 		error("Unknown suffix for animation %s", fileName.toString().c_str());
-
 	Common::File *_file = getSearchManager()->openFile(fileName);
 	if (!_file)
 		error("Error opening %s", fileName.toString().c_str());
-
 	bool loaded = animation->loadStream(_file);
 	if (!loaded)
 		error("Error loading animation %s", fileName.toString().c_str());
-
 	return animation;
 }
 
@@ -84,6 +81,7 @@ Video::VideoDecoder *ZVision::loadAnimation(const Common::Path &fileName) {
 	 
 void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, bool skippable, Subtitle *sub) {
 	Common::Rect dst = dstRect;
+	Common::Rect _workingArea = _renderManager->getWorkingArea();
 	// If dstRect is empty, no specific scaling was requested. However, we may choose to do scaling anyway
 	if (dst.isEmpty())
 		dst = Common::Rect(vid.getWidth(), vid.getHeight());
@@ -98,8 +96,8 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 		scaled->create(dst.width(), dst.height(), vid.getPixelFormat());
 	}
 
-	uint16 finalWidth = dst.width() < _workingWindow.width() ? dst.width() : _workingWindow.width();
-	uint16 finalHeight = dst.height() < _workingWindow.height() ? dst.height() : _workingWindow.height();
+	uint16 finalWidth = dst.width() < _workingArea.width() ? dst.width() : _workingArea.width();
+	uint16 finalHeight = dst.height() < _workingArea.height() ? dst.height() : _workingArea.height();
 	bool showSubs = (_scriptManager->getStateValue(StateKey_Subtitles) == 1);
 
 	_clock.stop();
@@ -142,7 +140,6 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 					frame = scaled; 
 				}
 				Common::Rect rect = Common::Rect(finalWidth, finalHeight);
-				//TODO - fix problem with full-screen video playback not rendering to screen.
 				debug(2,"Blitting from area %d x %d to video output surface at area %d, %d", frame->w, frame->h, dst.left, dst.top);
 				outSurface.simpleBlitFrom(*frame, rect, Common::Point(0,0));
 				_renderManager->processSubs(0);
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index 644d8dbdd28..23cde39ce80 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -148,14 +148,13 @@ void ZVision::loadSettings() {
 	for (int i = 0; i < ZVISION_SETTINGS_KEYS_COUNT; i++) {
 		if (settingsKeys[i].defaultValue >= 0) {
 			value = (settingsKeys[i].allowEditing) ? ConfMan.getInt(settingsKeys[i].name) : settingsKeys[i].defaultValue;
-		} else {
+		} 
+		else {
 			boolValue = (settingsKeys[i].allowEditing) ? ConfMan.getBool(settingsKeys[i].name) : settingsKeys[i].defaultBoolValue;
 			value = (boolValue) ? 1 : 0;
 		}
-
 		_scriptManager->setStateValue(settingsKeys[i].slot, value);
 	}
-
 	if (getGameId() == GID_NEMESIS)
 		_scriptManager->setStateValue(StateKey_ExecScopeStyle, 1);
 	else
@@ -163,52 +162,38 @@ void ZVision::loadSettings() {
 }
 
 void ZVision::saveSettings() {
-	for (int i = 0; i < ZVISION_SETTINGS_KEYS_COUNT; i++) {
+	for (int i = 0; i < ZVISION_SETTINGS_KEYS_COUNT; i++)
 		if (settingsKeys[i].allowEditing) {
 			if (settingsKeys[i].defaultValue >= 0)
 				ConfMan.setInt(settingsKeys[i].name, _scriptManager->getStateValue(settingsKeys[i].slot));
 			else
 				ConfMan.setBool(settingsKeys[i].name, (_scriptManager->getStateValue(settingsKeys[i].slot) == 1));
 		}
-	}
-
 	ConfMan.flushToDisk();
 }
 
 void ZVision::initialize() {
+  //File Paths
 	const Common::FSNode gameDataDir(ConfMan.getPath("path"));
-
 	_searchManager = new SearchManager(ConfMan.getPath("path"), 6);
-
 	_searchManager->addDir("FONTS");
 	_searchManager->addDir("addon");
-
 	if (getGameId() == GID_GRANDINQUISITOR) {
 		if (!_searchManager->loadZix("INQUIS.ZIX"))
 			error("Unable to load file INQUIS.ZIX");
-	} else if (getGameId() == GID_NEMESIS) {
+	} 
+	else if (getGameId() == GID_NEMESIS) {
 		if (!_searchManager->loadZix("NEMESIS.ZIX")) {
 			// The game might not be installed, try MEDIUM.ZIX instead
 			if (!_searchManager->loadZix("ZNEMSCR/MEDIUM.ZIX"))
 				error("Unable to load the file ZNEMSCR/MEDIUM.ZIX");
 		}
 	}
-
+	
+	//Graphics
 	_widescreen = ConfMan.getBool("widescreen");
-
-	Graphics::ModeList modes;
-	modes.push_back(Graphics::Mode(WINDOW_WIDTH, WINDOW_HEIGHT));
-  if (_widescreen)
-	  modes.push_back(Graphics::Mode(WINDOW_WIDTH_WIDE, WINDOW_HEIGHT_WIDE));    
-#if defined(USE_MPEG2) && defined(USE_A52)
-	// For the DVD version of ZGI we can play high resolution videos
-	if (getGameId() == GID_GRANDINQUISITOR && (getFeatures() & ADGF_DVD))
-		modes.push_back(Graphics::Mode(HIRES_WINDOW_WIDTH, HIRES_WINDOW_HEIGHT));
-#endif
-	initGraphicsModes(modes);
-
-	initScreen();
-
+	
+  //Keymaps
 	Common::Keymapper *keymapper = _system->getEventManager()->getKeymapper();
 	_gameKeymap = keymapper->getKeymap(gameKeymapId);
 	_gameKeymap->setEnabled(true);
@@ -219,26 +204,34 @@ void ZVision::initialize() {
 	_rnd = new Common::RandomSource("zvision");
 
 	// Create managers
+  switch (getGameId()) {
+    case GID_NEMESIS:
+      _renderManager = new RenderManager(this, nemesisLayout, _resourcePixelFormat, _doubleFPS, _widescreen);
+	    _menu = new MenuNemesis(this, _renderManager->getMenuArea());
+	    break;
+    case GID_GRANDINQUISITOR:
+      _renderManager = new RenderManager(this, zgiLayout, _resourcePixelFormat, _doubleFPS, _widescreen);
+		  _menu = new MenuZGI(this, _renderManager->getMenuArea());
+		  break;
+	  case GID_NONE:
+	  default:
+  		error("Unknown/unspecified GameId");
+	    break;
+  }
 	_scriptManager = new ScriptManager(this);
-	_renderManager = new RenderManager(this, WINDOW_WIDTH, WINDOW_HEIGHT, _workingWindow, _menuArea, _resourcePixelFormat, _doubleFPS);
 	_saveManager = new SaveManager(this);
 	_stringManager = new StringManager(this);
 	_cursorManager = new CursorManager(this, _resourcePixelFormat);
 	_textRenderer = new TextRenderer(this);
 	_midiManager = new MidiManager();
 
-	if (getGameId() == GID_GRANDINQUISITOR)
-		_menu = new MenuZGI(this, _menuArea);
-	else
-		_menu = new MenuNemesis(this, _menuArea);
-
 	// Initialize the managers
+	_renderManager->initialize();
 	_cursorManager->initialize();
 	_scriptManager->initialize();
 	_stringManager->initialize(getGameId());
 
 	registerDefaultSettings();
-
 	loadSettings();
 
 #if !defined(USE_MPEG2) || !defined(USE_A52)
@@ -263,9 +256,8 @@ Common::Error ZVision::run() {
 	if (ConfMan.hasKey("save_slot"))
 		_saveManager->loadGame(ConfMan.getInt("save_slot"));
 
-	bool foundAllFonts = true;
-
 	// Before starting, make absolutely sure that the user has copied the needed fonts
+	bool foundAllFonts = true;
 	for (int i = 0; i < FONT_COUNT; i++) {
 		FontStyle curFont = getSystemFont(i);
 
@@ -297,11 +289,9 @@ Common::Error ZVision::run() {
 				break;
 			}
 		}
-
 		if (!foundAllFonts)
 			break;
 	}
-
 	if (!foundAllFonts) {
 		GUI::MessageDialog dialog(_(
 				"Before playing this game, you'll need to copy the required "
@@ -320,17 +310,24 @@ Common::Error ZVision::run() {
 
 	// Main loop
 	while (!shouldQuit()) {
+	  debug(5,"Timers");
+	  //Timers
 		_clock.update();
 		uint32 currentTime = _clock.getLastMeasuredTime();
 		uint32 deltaTime = _clock.getDeltaTime();
-
+	  debug(5,"Logic");
+    //Process game logic & update backbuffers as necessary
+    debug(5,"Cursor");
 		_cursorManager->setItemID(_scriptManager->getStateValue(StateKey_InventoryItem));
-
+    debug(5,"Events");
 		processEvents();  //NB rotateTo or playVideo event will pause clock & call renderSceneToScreen() directly.
+    debug(5,"Rotation");
 		_renderManager->updateRotation();
+    debug(5,"Scripts");
 		_scriptManager->update(deltaTime);
+    debug(5,"Menu");
 		_menu->process(deltaTime);
-
+	  debug(5,"Render");
 		// Render the backBuffer to the screen
 		_renderManager->prepareBackground();
 		_renderManager->processSubs(deltaTime);
@@ -338,12 +335,11 @@ Common::Error ZVision::run() {
 			_renderedFrameCount++;
 		else
 			_frameRenderDelay--;
-
+	  debug(5,"Frame delay");
 		// Calculate the frame delay based off a desired frame time
 		int delay = _desiredFrameTime - int32(_system->getMillis() - currentTime);
 		// Ensure non-negative
 		delay = delay < 0 ? 0 : delay;
-
 		if (_doubleFPS) {
 			delay >>= 1;
 		}
@@ -354,7 +350,6 @@ Common::Error ZVision::run() {
 
 void ZVision::pauseEngineIntern(bool pause) {
 	_mixer->pauseAll(pause);
-
 	if (pause) {
 		_clock.stop();
 	} else {
@@ -386,45 +381,4 @@ void ZVision::fpsTimer() {
 	_renderedFrameCount = 0;
 }
 
-void ZVision::initScreen() {
-	uint16 workingWindowWidth = (getGameId() == GID_NEMESIS) ? ZNM_WORKING_WINDOW_WIDTH : ZGI_WORKING_WINDOW_WIDTH;
-	uint16 workingWindowHeight = (getGameId() == GID_NEMESIS) ? ZNM_WORKING_WINDOW_HEIGHT : ZGI_WORKING_WINDOW_HEIGHT;
-	_workingWindow = Common::Rect(
-    (WINDOW_WIDTH  -  workingWindowWidth) / 2,
-    (WINDOW_HEIGHT - workingWindowHeight) / 2,
-    ((WINDOW_WIDTH  -  workingWindowWidth) / 2) + workingWindowWidth,
-    ((WINDOW_HEIGHT - workingWindowHeight) / 2) + workingWindowHeight
-  );
-
-	uint16 menuAreaHeight = (getGameId() == GID_NEMESIS) ? ZNM_MENU_HEIGHT : ZGI_MENU_HEIGHT;
-	
-  _menuArea = Common::Rect(
-    (WINDOW_WIDTH  -  workingWindowWidth) / 2,
-    0,
-    ((WINDOW_WIDTH  -  workingWindowWidth) / 2) + workingWindowWidth,
-    menuAreaHeight
-  );
- 
-	uint16 subAreaHeight = (getGameId() == GID_NEMESIS) ? ZNM_SUBTITLE_HEIGHT : ZGI_SUBTITLE_HEIGHT;
- 
-  _subArea = Common::Rect(
-    0,
-    WINDOW_HEIGHT - subAreaHeight,
-    WINDOW_WIDTH,
-    WINDOW_HEIGHT
-  );
-
-  if(_widescreen) {
-    _menuArea.moveTo(_workingWindow.left, _workingWindow.top);
-    _subArea.moveTo(0, _workingWindow.bottom - _subArea.height());
-  }
-	initGraphics(WINDOW_WIDTH, WINDOW_HEIGHT, &_screenPixelFormat);
-}
-
-void ZVision::initHiresScreen() {
-	_renderManager->upscaleRect(_workingWindow);
-
-	initGraphics(HIRES_WINDOW_WIDTH, HIRES_WINDOW_HEIGHT, &_screenPixelFormat);
-}
-
 } // End of namespace ZVision
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index 60b9e6bba04..81813ed0457 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -68,6 +68,32 @@ class TextRenderer;
 class Subtitle;
 class MidiManager;
 
+struct ScreenLayout {
+  Common::Rect screenArea;  //Original screen resolution
+  Common::Rect menuArea;  //Menu display area, relative to original screen
+  Common::Rect workingArea;   //Playfield & video playback area, relative to original screen
+  Common::Rect textArea;  //Subtitle & message area, relative to original screen
+};
+
+//NB Footage of original DOS Nemesis engine indicates playfield was centrally placed on screen.
+//Subtitle scripts, however, suggest playfield was higher up, otherwise they run off the bottom of the screen.  Could just be an error in the scripts.
+//TODO Need to make a decision how to handle this.  Should be irrelevant for widescreen mode anyway, & purists will want original appearance for 4:3 ratio.
+//Figures below currently have playfield offset to fit subtitles entirely in lower bar
+
+static const ScreenLayout nemesisLayout {
+  Common::Rect(640,480),  //Screen
+  Common::Rect(Common::Point(64,0), 512, 32), //Menu
+  Common::Rect(Common::Point(64,40), 512, 320), //Working
+  Common::Rect(Common::Point(64,380), 512, 100) //Text
+};
+
+static const ScreenLayout zgiLayout {
+  Common::Rect(640,480),  //Screen
+  Common::Rect(Common::Point(0,0), 640, 32), //Menu
+  Common::Rect(Common::Point(0,40), 640, 344), //Working
+  Common::Rect(Common::Point(0,400), 640, 80) //Text
+};
+
 enum {
 	WINDOW_WIDTH = 640,//Original 640,
 	WINDOW_HEIGHT = 480,//Original 480,
@@ -77,14 +103,14 @@ enum {
 	HIRES_WINDOW_WIDTH = 800, //Original 800
 	HIRES_WINDOW_HEIGHT = 600,  //Original 600
 
-	// Zork Nemesis working window sizes (original aspect ratio 8:5)
+	// Zork Nemesis working window size (original aspect ratio 1.6)
 	ZNM_WORKING_WINDOW_WIDTH = 512, //Original 512
 	ZNM_WORKING_WINDOW_HEIGHT = 320,  //Original 320
 	
 	ZNM_SUBTITLE_HEIGHT = 80, //Original 80
 	ZNM_MENU_HEIGHT = 32,  //Original 80
 
-	// ZGI working window sizes (original aspect ratio 2:1)
+	// ZGI working window size (original aspect ratio 1.86)
 	ZGI_WORKING_WINDOW_WIDTH = 640, //Original 640
 	ZGI_WORKING_WINDOW_HEIGHT = 344,  //Original 344
 	
@@ -124,11 +150,11 @@ public:
 
 public:
 	/**
-	 * A Rectangle centered inside the actual window. All in-game coordinates
+	 * A Rectangle centered inside the game window. All in-game coordinates
 	 * are given in this coordinate space. Also, all images are clipped to the
 	 * edges of this Rectangle
 	 */
-	Common::Rect _workingWindow;
+//	Common::Rect _workingArea;
 	/**
 	 * A Rectangle in which the menu will be rendered.  
 	 * In the original game, this is always separate from the working window,
@@ -136,8 +162,8 @@ public:
 	 * In the widescreen mod, this window may intersect the working window,
 	 * and thus must be composited and rendered within renderSceneToScreen().
 	 */
-	Common::Rect _menuArea;
-	Common::Rect _subArea;
+//	Common::Rect _menuArea;
+//	Common::Rect _textArea;
 	const Graphics::PixelFormat _resourcePixelFormat;
 	const Graphics::PixelFormat _screenPixelFormat;
 
@@ -241,7 +267,7 @@ public:
 		_clock.stop();
 	}
 
-	void initScreen();
+	void initScreen(bool hiRes=false);
 	void initHiresScreen();
 
 	/**


Commit: a7aedfedfe9b315a5b02f45c03b314848d8c9992
    https://github.com/scummvm/scummvm/commit/a7aedfedfe9b315a5b02f45c03b314848d8c9992
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:55+02:00

Commit Message:
COMMON: Make center() const.

Changed paths:
    common/rect.h


diff --git a/common/rect.h b/common/rect.h
index 5923b3aef13..9f7bd9db56e 100644
--- a/common/rect.h
+++ b/common/rect.h
@@ -391,7 +391,7 @@ struct Rect {
   * Return a Point indicating the centroid of the rectangle
   * @note The center point is rounded up and left when width and/or height are odd
   */
-  Point center() {
+  Point center() const {
     return Point((left+right)/2, (bottom+top)/2);
   }	
 


Commit: 76fa0a120e5f2b0c035b1784b00ace8311e37355
    https://github.com/scummvm/scummvm/commit/76fa0a120e5f2b0c035b1784b00ace8311e37355
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:55+02:00

Commit Message:
ZVISION: Add isAvailable() to midi manager.

Changed paths:
    engines/zvision/sound/midi.cpp
    engines/zvision/sound/midi.h


diff --git a/engines/zvision/sound/midi.cpp b/engines/zvision/sound/midi.cpp
index 2bc62778f90..8647dabb030 100644
--- a/engines/zvision/sound/midi.cpp
+++ b/engines/zvision/sound/midi.cpp
@@ -30,8 +30,12 @@ namespace ZVision {
 MidiManager::MidiManager() {
 	MidiDriver::DeviceHandle dev = MidiDriver::detectDevice(MDT_MIDI | MDT_ADLIB);
 	_driver = MidiDriver::createMidi(dev);
-	if (_driver->open())
+	if (_driver->open()) {
 		warning("Can't open MIDI, no MIDI output!");
+		available = false;
+		}
+	else
+	  available = true;
 }
 
 MidiManager::~MidiManager() {
diff --git a/engines/zvision/sound/midi.h b/engines/zvision/sound/midi.h
index da24bd07a3e..b9022baf387 100644
--- a/engines/zvision/sound/midi.h
+++ b/engines/zvision/sound/midi.h
@@ -39,13 +39,15 @@ public:
 	void setProgram(int8 channel, int8 prog);
 
 	int8 getFreeChannel();
+	bool isAvailable() {
+	  return available;
+	};
 
 protected:
-
+  bool available = false;
 	struct chan {
 		bool playing;
 		int8 note;
-
 		chan() : playing(false), note(0) {};
 	};
 


Commit: 6850ebce0a8168b2d12693acbfa48a4741e2430a
    https://github.com/scummvm/scummvm/commit/6850ebce0a8168b2d12693acbfa48a4741e2430a
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:55+02:00

Commit Message:
ZVISION: Simplification of subtitle rendering system.
Subtitles render in correct location in both widescreen & conventional mode.

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/text/subtitles.cpp
    engines/zvision/video/video.cpp
    engines/zvision/zvision.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index f5be698f08e..9033e894ad1 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -48,7 +48,7 @@ RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const G
 	  _system(engine->_system),
 	  _layout(layout),
 	  _screenArea(_layout.screenArea),
-	  _screenCentre(_screenArea.center()),
+	  _screenCenter(_screenArea.center()),
 	  _workingArea(_layout.workingArea),
 	  _menuArea(_layout.menuArea),
 	  _textArea(_layout.textArea),
@@ -64,14 +64,16 @@ RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const G
   //Define graphics modes & screen subarea geometry
 	Graphics::ModeList modes;
   if (_widescreen) {
-    //*
     _workingArea.moveTo(0,0);
     _screenArea = _workingArea;
-    _screenCentre = _screenArea.center();
-    //*/
+    _screenCenter = _screenArea.center();
     _menuArea.moveTo(_workingArea.origin());
     _textArea.moveTo(_workingArea.left, _workingArea.bottom - _textArea.height());
-  } 
+  }
+  _textOffset = _layout.workingArea.origin() - _layout.textArea.origin();
+  debug(2,"working area: %d,%d,%d,%d", _workingArea.left, _workingArea.top, _workingArea.bottom, _workingArea.right);
+  debug(2,"text area: %d,%d,%d,%d", _textArea.left, _textArea.top, _textArea.bottom, _textArea.right);
+  debug(2,"text offset: %d,%d", _textOffset.x, _textOffset.y);
   modes.push_back(Graphics::Mode(_screenArea.width(), _screenArea.height()));
 #if defined(USE_MPEG2) && defined(USE_A52)
 	if (_engine->getGameId() == GID_GRANDINQUISITOR && (_engine->getFeatures() & ADGF_DVD))
@@ -83,7 +85,7 @@ RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const G
 	_effectSurface.create(_workingArea.width(), _workingArea.height(), _pixelFormat);
 	_warpedSceneSurface.create(_workingArea.width(), _workingArea.height(), _pixelFormat);
 	_menuSurface.create(_menuArea.width(), _menuArea.height(), _pixelFormat);
-	_subSurface.create(_textArea.width(), _textArea.height(), _pixelFormat);
+	_textSurface.create(_textArea.width(), _textArea.height(), _pixelFormat);
 	debug(1,"render manager created");
 }
 
@@ -95,7 +97,7 @@ RenderManager::~RenderManager() {
 	_warpedSceneSurface.free();
 	_menuSurface.free();
 	_menuManagedSurface.free();
-	_subSurface.free();
+	_textSurface.free();
 	_textManagedSurface.free();
 	_screen.free();
 }
@@ -127,7 +129,7 @@ void RenderManager::initialize(bool hiRes) {
 	}
 	//Clear backbuffer surfaces
 	clearMenuSurface();
-  clearSubSurface();
+  clearTextSurface();
   
   //Set hardware/window resolution
   initGraphics(_screen.w, _screen.h, &_engine->_screenPixelFormat); 
@@ -195,7 +197,7 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
 	}
 	
 	_menuManagedSurface.transBlitFrom(_menuSurface, -1);
-  _textManagedSurface.transBlitFrom(_subSurface, -1);
+  _textManagedSurface.transBlitFrom(_textSurface, -1);
 
   if(_engine->canRender() || immediate) {
     _screen.update();
@@ -349,9 +351,9 @@ const Common::Point RenderManager::screenSpaceToImageSpace(const Common::Point &
 		}
 
 		if (state == RenderTable::PANORAMA) {
-			newPoint += (Common::Point(_backgroundOffset - _screenCentre.x, 0));
+			newPoint += (Common::Point(_backgroundOffset - _screenCenter.x, 0));
 		} else if (state == RenderTable::TILT) {
-			newPoint += (Common::Point(0, _backgroundOffset - _screenCentre.y));
+			newPoint += (Common::Point(0, _backgroundOffset - _screenCenter.y));
 		}
 
 		if (_backgroundWidth)
@@ -672,44 +674,44 @@ void RenderManager::prepareBackground() {
 	if (state == RenderTable::PANORAMA) {
 		// Calculate the visible portion of the background
 		Common::Rect viewPort(_workingArea.width(), _workingArea.height());
-		viewPort.translate(-(_screenCentre.x - _backgroundOffset), 0);
+		viewPort.translate(-(_screenCenter.x - _backgroundOffset), 0);
 		Common::Rect drawRect = _backgroundDirtyRect;
 		drawRect.clip(viewPort);
 
 		// Render the visible portion
 		if (!drawRect.isEmpty()) {
-			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _screenCentre.x - _backgroundOffset + drawRect.left, drawRect.top);
+			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _screenCenter.x - _backgroundOffset + drawRect.left, drawRect.top);
 		}
 
 		// Mark the dirty portion of the surface
 		_backgroundSurfaceDirtyRect = _backgroundDirtyRect;
-		_backgroundSurfaceDirtyRect.translate(_screenCentre.x - _backgroundOffset, 0);
+		_backgroundSurfaceDirtyRect.translate(_screenCenter.x - _backgroundOffset, 0);
 
 		// Panorama mode allows the user to spin in circles. Therefore, we need to render
 		// the portion of the image that wrapped to the other side of the screen
-		if (_backgroundOffset < _screenCentre.x) {
-			viewPort.moveTo(-(_screenCentre.x - (_backgroundOffset + _backgroundWidth)), 0);
+		if (_backgroundOffset < _screenCenter.x) {
+			viewPort.moveTo(-(_screenCenter.x - (_backgroundOffset + _backgroundWidth)), 0);
 			drawRect = _backgroundDirtyRect;
 			drawRect.clip(viewPort);
 
 			if (!drawRect.isEmpty())
-				blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _screenCentre.x - (_backgroundOffset + _backgroundWidth) + drawRect.left, drawRect.top);
+				blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _screenCenter.x - (_backgroundOffset + _backgroundWidth) + drawRect.left, drawRect.top);
 
 			Common::Rect tmp = _backgroundDirtyRect;
-			tmp.translate(_screenCentre.x - (_backgroundOffset + _backgroundWidth), 0);
+			tmp.translate(_screenCenter.x - (_backgroundOffset + _backgroundWidth), 0);
 			if (!tmp.isEmpty())
 				_backgroundSurfaceDirtyRect.extend(tmp);
 
-		} else if (_backgroundWidth - _backgroundOffset < _screenCentre.x) {
-			viewPort.moveTo(-(_screenCentre.x + _backgroundWidth - _backgroundOffset), 0);
+		} else if (_backgroundWidth - _backgroundOffset < _screenCenter.x) {
+			viewPort.moveTo(-(_screenCenter.x + _backgroundWidth - _backgroundOffset), 0);
 			drawRect = _backgroundDirtyRect;
 			drawRect.clip(viewPort);
 
 			if (!drawRect.isEmpty())
-				blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _screenCentre.x + _backgroundWidth - _backgroundOffset + drawRect.left, drawRect.top);
+				blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _screenCenter.x + _backgroundWidth - _backgroundOffset + drawRect.left, drawRect.top);
 
 			Common::Rect tmp = _backgroundDirtyRect;
-			tmp.translate(_screenCentre.x + _backgroundWidth - _backgroundOffset, 0);
+			tmp.translate(_screenCenter.x + _backgroundWidth - _backgroundOffset, 0);
 			if (!tmp.isEmpty())
 				_backgroundSurfaceDirtyRect.extend(tmp);
 
@@ -717,15 +719,15 @@ void RenderManager::prepareBackground() {
 	} else if (state == RenderTable::TILT) {
 		// Tilt doesn't allow wrapping, so we just do a simple clip
 		Common::Rect viewPort(_workingArea.width(), _workingArea.height());
-		viewPort.translate(0, -(_screenCentre.y - _backgroundOffset));
+		viewPort.translate(0, -(_screenCenter.y - _backgroundOffset));
 		Common::Rect drawRect = _backgroundDirtyRect;
 		drawRect.clip(viewPort);
 		if (!drawRect.isEmpty())
-			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, drawRect.left, _screenCentre.y - _backgroundOffset + drawRect.top);
+			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, drawRect.left, _screenCenter.y - _backgroundOffset + drawRect.top);
 
 		// Mark the dirty portion of the surface
 		_backgroundSurfaceDirtyRect = _backgroundDirtyRect;
-		_backgroundSurfaceDirtyRect.translate(0, _screenCentre.y - _backgroundOffset);
+		_backgroundSurfaceDirtyRect.translate(0, _screenCenter.y - _backgroundOffset);
 
 	} else {
 		if (!_backgroundDirtyRect.isEmpty())
@@ -748,66 +750,47 @@ void RenderManager::clearMenuSurface(int32 colorkey) {
 	_menuSurface.fillRect(_menuSurfaceDirtyRect, colorkey);
 }
 
-void RenderManager::clearSubSurface(int32 colorkey) {
+void RenderManager::clearTextSurface(int32 colorkey) {
   //TODO - reinstate more efficient dirtyrect system
   //TODO - blank lower letterbox area when NOT in widescreen mode.
-	_subSurfaceDirtyRect = Common::Rect(0, 0, _subSurface.w, _subSurface.h);
-	_subSurface.fillRect(_subSurfaceDirtyRect, colorkey);
+	_textSurfaceDirtyRect = Common::Rect(0, 0, _textSurface.w, _textSurface.h);
+	_textSurface.fillRect(_textSurfaceDirtyRect, colorkey);
 }
 
-/*
-//TODO - confirm redundancy and remove
-void RenderManager::initSubArea(uint32 windowWidth, uint32 windowHeight, const Common::Rect workingArea) {
-	_workingArea = workingArea;
-	_subSurface.free();
-	_subSurface.create(windowWidth, windowHeight - workingArea.bottom, _pixelFormat);
-	_textArea = Common::Rect(0, workingArea.bottom, windowWidth, windowHeight);
-  if(_engine->isWidescreen())
-    _textArea.translate(0,-_textArea.height());
-  clearSubSurface();
-}
-//*/
-
-uint16 RenderManager::createSubArea(const Common::Rect &area) {
+uint16 RenderManager::registerSubtitle(const Common::Rect &area) {
 	_subid++;
 	OneSubtitle sub;
 	sub.redraw = false;
 	sub.timer = -1;
 	sub.todelete = false;
 	sub.r = area;
-	
 	//Original game subtitle scripts appear to define subtitle rectangles relative to origin of working area.
 	//To allow arbitrary aspect ratios, we need to instead place these relative to origin of text area.
 	//This will allow the managed text area to then be arbitrarily placed on the screen to suit different aspect ratios.
-	sub.r.translate(_screenCentre.x - 320, _screenCentre.y - 240);
-  //If we are in widescreen mode, then shift the subtitle rectangle upwards to overlay the working window.	
-  if(_engine->isWidescreen())
-    sub.r.translate(0, -_textArea.height());
-
-  debug(1,"Creating subtitle area %d, dimenisions %dx%d, working window location %d,%d, screen location", _subid, sub.r.width(), sub.r.height(),  sub.r.left, sub.r.top);
-
+	sub.r.translate(_textOffset.x, _textOffset.y);  //Convert working area coordinates to text area coordinates
+  debug(1,"Registering subtitle area %d, dimenisions %dx%d, position within text area x%d,y%d", _subid, sub.r.width(), sub.r.height(), sub.r.left, sub.r.top);
 	_subsList[_subid] = sub;
-
 	return _subid;
 }
 
-uint16 RenderManager::createSubArea() {
+uint16 RenderManager::registerSubtitle() {
+  //TODO - double check validity of this geometry
 	Common::Rect r(_textArea.left, _textArea.top, _textArea.right, _textArea.bottom);
 	r.translate(-_workingArea.left, -_workingArea.top);
-	return createSubArea(r);
+	return registerSubtitle(r);
 }
 
-void RenderManager::deleteSubArea(uint16 id) {
+void RenderManager::deregisterSubtitle(uint16 id) {
 	if (_subsList.contains(id))
 		_subsList[id].todelete = true;
 }
 
-void RenderManager::deleteSubArea(uint16 id, int16 delay) {
+void RenderManager::deregisterSubtitle(uint16 id, int16 delay) {
 	if (_subsList.contains(id))
 		_subsList[id].timer = delay;
 }
 
-void RenderManager::updateSubArea(uint16 id, const Common::String &txt) {
+void RenderManager::updateSubtitle(uint16 id, const Common::String &txt) {
 	if (_subsList.contains(id)) {
 		OneSubtitle *sub = &_subsList[id];
 		sub->txt = txt;
@@ -815,8 +798,8 @@ void RenderManager::updateSubArea(uint16 id, const Common::String &txt) {
 	}
 }
 
-void RenderManager::processSubs(uint16 deltatime) {
-  debug(5,"processSubs()");
+void RenderManager::processSubtitles(uint16 deltatime) {
+  debug(5,"processSubtitles()");
 	bool redraw = false;
 	
 	//Update all subtitles' respective timers; delete expired subtitles.
@@ -836,24 +819,24 @@ void RenderManager::processSubs(uint16 deltatime) {
 
 	if (redraw) {
 	  //Blank subtitle buffer
-	  clearSubSurface();
+	  clearTextSurface();
 
     //Cycle through all extant subtitles, if subtitle contains text then render it to an auxiliary buffer within a rectangle specified by that subtitle & blit into main subtitle buffer
 		for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
 			OneSubtitle *sub = &it->_value;
 			if (sub->txt.size()) {
-				Graphics::Surface subSurface;
-				subSurface.create(sub->r.width(), sub->r.height(), _engine->_resourcePixelFormat);
-				subSurface.fillRect(Common::Rect(sub->r.width(), sub->r.height()), -1); //TODO Unnecessary operation?  Check later.
-				_engine->getTextRenderer()->drawTextWithWordWrapping(sub->txt, subSurface, _engine->isWidescreen());
+				Graphics::Surface textSurface;
+				textSurface.create(sub->r.width(), sub->r.height(), _engine->_resourcePixelFormat);
+				textSurface.fillRect(Common::Rect(sub->r.width(), sub->r.height()), -1); //TODO Unnecessary operation?  Check later.
+				_engine->getTextRenderer()->drawTextWithWordWrapping(sub->txt, textSurface, _engine->isWidescreen());
 				Common::Rect empty;
-				blitSurfaceToSurface(subSurface, empty, _subSurface, sub->r.left - _textArea.left + _workingArea.left, sub->r.top - _textArea.top + _workingArea.top, -1);
-				subSurface.free();
+				blitSurfaceToSurface(textSurface, empty, _textSurface, sub->r.left, sub->r.top, -1);
+				textSurface.free();
 			}
 			sub->redraw = false;
 		}
 	}
-  debug(5,"~processSubs()");
+  debug(5,"~processSubtitles()");
 }
 
 Common::Point RenderManager::getBkgSize() {
@@ -879,33 +862,33 @@ Common::Rect RenderManager::transformBackgroundSpaceRectToScreenSpace(const Comm
 	RenderTable::RenderState state = _renderTable.getRenderState();
 
 	if (state == RenderTable::PANORAMA) {
-		if (_backgroundOffset < _screenCentre.x) {
-			Common::Rect rScreen(_screenCentre.x + _backgroundOffset, _workingArea.height());
+		if (_backgroundOffset < _screenCenter.x) {
+			Common::Rect rScreen(_screenCenter.x + _backgroundOffset, _workingArea.height());
 			Common::Rect lScreen(_workingArea.width() - rScreen.width(), _workingArea.height());
 			lScreen.translate(_backgroundWidth - lScreen.width(), 0);
 			lScreen.clip(src);
 			rScreen.clip(src);
 			if (rScreen.width() < lScreen.width()) {
-				tmp.translate(_screenCentre.x - _backgroundOffset - _backgroundWidth, 0);
+				tmp.translate(_screenCenter.x - _backgroundOffset - _backgroundWidth, 0);
 			} else {
-				tmp.translate(_screenCentre.x - _backgroundOffset, 0);
+				tmp.translate(_screenCenter.x - _backgroundOffset, 0);
 			}
-		} else if (_backgroundWidth - _backgroundOffset < _screenCentre.x) {
-			Common::Rect rScreen(_screenCentre.x - (_backgroundWidth - _backgroundOffset), _workingArea.height());
+		} else if (_backgroundWidth - _backgroundOffset < _screenCenter.x) {
+			Common::Rect rScreen(_screenCenter.x - (_backgroundWidth - _backgroundOffset), _workingArea.height());
 			Common::Rect lScreen(_workingArea.width() - rScreen.width(), _workingArea.height());
 			lScreen.translate(_backgroundWidth - lScreen.width(), 0);
 			lScreen.clip(src);
 			rScreen.clip(src);
 			if (lScreen.width() < rScreen.width()) {
-				tmp.translate(_screenCentre.x + (_backgroundWidth - _backgroundOffset), 0);
+				tmp.translate(_screenCenter.x + (_backgroundWidth - _backgroundOffset), 0);
 			} else {
-				tmp.translate(_screenCentre.x - _backgroundOffset, 0);
+				tmp.translate(_screenCenter.x - _backgroundOffset, 0);
 			}
 		} else {
-			tmp.translate(_screenCentre.x - _backgroundOffset, 0);
+			tmp.translate(_screenCenter.x - _backgroundOffset, 0);
 		}
 	} else if (state == RenderTable::TILT) {
-		tmp.translate(0, (_screenCentre.y - _backgroundOffset));
+		tmp.translate(0, (_screenCenter.y - _backgroundOffset));
 	}
 
 	return tmp;
@@ -1053,15 +1036,15 @@ void RenderManager::bkgFill(uint8 r, uint8 g, uint8 b) {
 
 void RenderManager::timedMessage(const Common::String &str, uint16 milsecs) {
   //TODO - rework to use new renderscene system
-	uint16 msgid = createSubArea();
-	updateSubArea(msgid, str);
-	deleteSubArea(msgid, milsecs);
+	uint16 msgid = registerSubtitle();
+	updateSubtitle(msgid, str);
+	deregisterSubtitle(msgid, milsecs);
 }
 
 bool RenderManager::askQuestion(const Common::String &str) {
-	Graphics::Surface backupSubSurface;
-	backupSubSurface.copyFrom(_subSurface);
-	_engine->getTextRenderer()->drawTextWithWordWrapping(str, _subSurface, _engine->isWidescreen());
+	Graphics::Surface backuptextSurface;
+	backuptextSurface.copyFrom(_textSurface);
+	_engine->getTextRenderer()->drawTextWithWordWrapping(str, _textSurface, _engine->isWidescreen());
 	renderSceneToScreen(true); 
 
 	_engine->stopClock();
@@ -1117,10 +1100,10 @@ bool RenderManager::askQuestion(const Common::String &str) {
 	}
 
   //Clear question graphics by restoring saved subtitle buffer
-  _subSurface.copyFrom(backupSubSurface);
+  _textSurface.copyFrom(backuptextSurface);
 
 	// Free the surface
-	backupSubSurface.free();
+	backuptextSurface.free();
 
 	_engine->startClock();
 	return result == 2;
@@ -1128,10 +1111,10 @@ bool RenderManager::askQuestion(const Common::String &str) {
 
 void RenderManager::delayedMessage(const Common::String &str, uint16 milsecs) {
   //TODO - find bug in current render system; shows up with widescreen disabled, but not with it enabled.
-	uint16 msgid = createSubArea();
-	updateSubArea(msgid, str);
+	uint16 msgid = registerSubtitle();
+	updateSubtitle(msgid, str);
   debug(1,"initiating delayed message: %s to subtitle id %d", str.c_str(), msgid);
-	processSubs(0);
+	processSubtitles(0);
 	renderSceneToScreen(true);
 	_engine->stopClock();
 
@@ -1151,15 +1134,15 @@ void RenderManager::delayedMessage(const Common::String &str, uint16 milsecs) {
 		else
 			_system->delayMillis(66);
 	}
-	deleteSubArea(msgid);
+	deregisterSubtitle(msgid);
 	_engine->startClock();
 }
 
 void RenderManager::showDebugMsg(const Common::String &msg, int16 delay) {
-	uint16 msgid = createSubArea();
-	updateSubArea(msgid, msg);
+	uint16 msgid = registerSubtitle();
+	updateSubtitle(msgid, msg);
   debug(1,"initiating in-game debug message: %s to subtitle id %d", msg.c_str(), msgid);
-	deleteSubArea(msgid, delay);
+	deregisterSubtitle(msgid, delay);
 }
 
 void RenderManager::updateRotation() {
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index 03574b98b96..b68da8e9f2b 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -79,7 +79,9 @@ private:
 	 */	
 	Common::Rect _screenArea;
 	
-	Common::Point _screenCentre; //Centre of the screen at current resolution
+	Common::Point _screenCenter; //Center of the screen at current resolution
+	
+	Common::Point _textOffset;  //Position vector of text area origin relative to working window origin
 
 	/**
 	 * A Rectangle placed inside _screenArea All in-game coordinates
@@ -115,8 +117,8 @@ private:
 	Common::Rect _backgroundSurfaceDirtyRect;
 
 	// Buffer for subtitles
-	Graphics::Surface _subSurface;
-	Common::Rect _subSurfaceDirtyRect;
+	Graphics::Surface _textSurface;
+	Common::Rect _textSurfaceDirtyRect;
 
 	// Rectangle for subtitles & other messages
 	Graphics::ManagedSurface _textManagedSurface;
@@ -165,8 +167,12 @@ public:
 	
 	Graphics::ManagedSurface &getVidSurface(Common::Rect &dstRect);  //dstRect is defined relative to working window origin
 	
-	Common::Rect getMenuArea() {return _menuArea;}
-	Common::Rect getWorkingArea() {return _workingArea;}
+	Common::Rect getMenuArea() {
+	  return _menuArea;
+  }  
+	Common::Rect getWorkingArea() {
+	  return _workingArea;
+  }
 
 	/**
 	 * Blits the image or a portion of the image to the background.
@@ -218,8 +224,6 @@ public:
 	 */
 	void setBackgroundPosition(int offset);
 
-
-
 	/**
 	 * Converts a point in screen coordinate space to image coordinate space
 	 *
@@ -270,22 +274,19 @@ public:
 	// Blitting surface-to-menu methods
 	void blitSurfaceToMenu(const Graphics::Surface &src, int16 x, int16 y, int32 colorkey = 0);
 
-	// Subtitles methods
-	//void initSubArea(uint32 windowWidth, uint32 windowHeight, const Common::Rect workingArea);
+	// Create subtitle graphics object and return ID
+	uint16 registerSubtitle(const Common::Rect &area);
+	uint16 registerSubtitle();
 
-	// Create subtitle area and return ID
-	uint16 createSubArea(const Common::Rect &area);
-	uint16 createSubArea();
+	// Delete subtitle graphics object by ID
+	void deregisterSubtitle(uint16 id);
+	void deregisterSubtitle(uint16 id, int16 delay);
 
-	// Delete subtitle by ID
-	void deleteSubArea(uint16 id);
-	void deleteSubArea(uint16 id, int16 delay);
-
-	// Update subtitle area
-	void updateSubArea(uint16 id, const Common::String &txt);
+	// Update subtitle graphics object string content
+	void updateSubtitle(uint16 id, const Common::String &txt);
 
 	// Processing subtitles
-	void processSubs(uint16 deltatime);
+	void processSubtitles(uint16 deltatime);
 
 	// Return background size
 	Common::Point getBkgSize();
@@ -301,7 +302,7 @@ public:
 	void clearMenuSurface(int32 colorkey = -1);
 	
 	// Clear whole/area of subtitle surface
-	void clearSubSurface(int32 colorkey = -1);
+	void clearTextSurface(int32 colorkey = -1);
 
 	// Copy needed portion of background surface to workingArea surface
 	void prepareBackground();
@@ -361,11 +362,9 @@ public:
 	void delayedMessage(const Common::String &str, uint16 milsecs);
 	void timedMessage(const Common::String &str, uint16 milsecs);
 	void showDebugMsg(const Common::String &msg, int16 delay = 3000);
-
 	void checkBorders();
 	void rotateTo(int16 to, int16 time);
 	void updateRotation();
-
 	void upscaleRect(Common::Rect &rect);
 };
 
diff --git a/engines/zvision/text/subtitles.cpp b/engines/zvision/text/subtitles.cpp
index 72c07320b2f..c3d7b8ae12a 100644
--- a/engines/zvision/text/subtitles.cpp
+++ b/engines/zvision/text/subtitles.cpp
@@ -31,6 +31,7 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool upscaleToH
 	_areaId(-1),
 	_subId(-1) {
 	Common::File file;
+	//Parse subtitle parameters from script
 	if (_engine->getSearchManager()->openFile(file, subname)) {
 		while (!file.eos()) {
 			Common::String str = file.readLine();
@@ -45,7 +46,7 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool upscaleToH
 				Common::Rect rct = Common::Rect(x1, y1, x2, y2);
 				if (upscaleToHires)
 					_engine->getRenderManager()->upscaleRect(rct);
-				_areaId = _engine->getRenderManager()->createSubArea(rct);
+				_areaId = _engine->getRenderManager()->registerSubtitle(rct);
 				debug(1,"Original subtitle script rectangle coordinates: l%d, t%d, r%d, b%d", x1, y1, x2, y2);
 			} 
 			else if (str.matchString("*TextFile*", true)) {
@@ -87,7 +88,7 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool upscaleToH
 
 Subtitle::~Subtitle() {
 	if (_areaId != -1)
-		_engine->getRenderManager()->deleteSubArea(_areaId);
+		_engine->getRenderManager()->deregisterSubtitle(_areaId);
 	_subs.clear();
 }
 
@@ -101,14 +102,14 @@ void Subtitle::process(int32 time) {
 
 	if (j == -1 && _subId != -1) {
 		if (_areaId != -1)
-			_engine->getRenderManager()->updateSubArea(_areaId, "");
+			_engine->getRenderManager()->updateSubtitle(_areaId, "");
 		_subId = -1;
 	}
 
 	if (j != -1 && j != _subId) {
 		if (_subs[j].subStr.size())
 			if (_areaId != -1)
-				_engine->getRenderManager()->updateSubArea(_areaId, _subs[j].subStr);
+				_engine->getRenderManager()->updateSubtitle(_areaId, _subs[j].subStr);
 		_subId = j;
 	}
 }
diff --git a/engines/zvision/video/video.cpp b/engines/zvision/video/video.cpp
index c455ea59ce5..4a628cf1c51 100644
--- a/engines/zvision/video/video.cpp
+++ b/engines/zvision/video/video.cpp
@@ -142,7 +142,7 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 				Common::Rect rect = Common::Rect(finalWidth, finalHeight);
 				debug(2,"Blitting from area %d x %d to video output surface at area %d, %d", frame->w, frame->h, dst.left, dst.top);
 				outSurface.simpleBlitFrom(*frame, rect, Common::Point(0,0));
-				_renderManager->processSubs(0);
+				_renderManager->processSubtitles(0);
 			}
 		}
 		// Always update the screen so the mouse continues to render & video does not skip
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index 23cde39ce80..4c309a7763c 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -117,7 +117,6 @@ ZVision::ZVision(OSystem *syst, const ZVisionGameDescription *gameDesc)
 
 ZVision::~ZVision() {
 	debug(1, "ZVision::~ZVision");
-
 	// Dispose of resources
 	delete _cursorManager;
 	delete _stringManager;
@@ -126,7 +125,6 @@ ZVision::~ZVision() {
 	delete _renderManager;	// should be deleted after the script manager
 	delete _rnd;
 	delete _midiManager;
-
 	getTimerManager()->removeTimerProc(&fpsTimerCallback);
 }
 
@@ -144,11 +142,9 @@ void ZVision::registerDefaultSettings() {
 void ZVision::loadSettings() {
 	int16 value = 0;
 	bool boolValue = false;
-
 	for (int i = 0; i < ZVISION_SETTINGS_KEYS_COUNT; i++) {
-		if (settingsKeys[i].defaultValue >= 0) {
+		if (settingsKeys[i].defaultValue >= 0)
 			value = (settingsKeys[i].allowEditing) ? ConfMan.getInt(settingsKeys[i].name) : settingsKeys[i].defaultValue;
-		} 
 		else {
 			boolValue = (settingsKeys[i].allowEditing) ? ConfMan.getBool(settingsKeys[i].name) : settingsKeys[i].defaultBoolValue;
 			value = (boolValue) ? 1 : 0;
@@ -307,6 +303,19 @@ Common::Error ZVision::run() {
 		quitGame();
 		return Common::kUnknownError;
 	}
+	if(getGameId() == GID_NEMESIS && !_midiManager->isAvailable()) {
+		GUI::MessageDialog MIDIdialog(_(
+	      "MIDI playback is not available, or else improperly configured. "
+	      "Zork Nemesis contains several music puzzles which require "
+	      "MIDI audio in order to be solved.  These puzzles may alternatively "
+	      "be solved using subtitles, if supported. Continue launching game?" 
+      ),
+	    _("Yes"),
+	    _("No")
+    );
+	  if (MIDIdialog.runModal() != GUI::kMessageOK)
+		  quitGame();
+  }
 
 	// Main loop
 	while (!shouldQuit()) {
@@ -330,7 +339,7 @@ Common::Error ZVision::run() {
 	  debug(5,"Render");
 		// Render the backBuffer to the screen
 		_renderManager->prepareBackground();
-		_renderManager->processSubs(deltaTime);
+		_renderManager->processSubtitles(deltaTime);
 		if(_renderManager->renderSceneToScreen())
 			_renderedFrameCount++;
 		else
@@ -340,9 +349,8 @@ Common::Error ZVision::run() {
 		int delay = _desiredFrameTime - int32(_system->getMillis() - currentTime);
 		// Ensure non-negative
 		delay = delay < 0 ? 0 : delay;
-		if (_doubleFPS) {
+		if (_doubleFPS)
 			delay >>= 1;
-		}
 		_system->delayMillis(delay);
 	}
 	return Common::kNoError;
@@ -350,11 +358,10 @@ Common::Error ZVision::run() {
 
 void ZVision::pauseEngineIntern(bool pause) {
 	_mixer->pauseAll(pause);
-	if (pause) {
+	if (pause)
 		_clock.stop();
-	} else {
+  else
 		_clock.start();
-	}
 }
 
 void ZVision::setRenderDelay(uint delay) {
@@ -368,7 +375,6 @@ bool ZVision::canRender() {
 
 void ZVision::syncSoundSettings() {
 	Engine::syncSoundSettings();
-
 	_scriptManager->setStateValue(StateKey_Subtitles, ConfMan.getBool("subtitles") ? 1 : 0);
 }
 
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index 81813ed0457..a3946298551 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -83,43 +83,24 @@ struct ScreenLayout {
 static const ScreenLayout nemesisLayout {
   Common::Rect(640,480),  //Screen
   Common::Rect(Common::Point(64,0), 512, 32), //Menu
-  Common::Rect(Common::Point(64,40), 512, 320), //Working
+  Common::Rect(Common::Point(64,40), 512, 320), //Working; aspect ratio 1.6
   Common::Rect(Common::Point(64,380), 512, 100) //Text
 };
 
 static const ScreenLayout zgiLayout {
   Common::Rect(640,480),  //Screen
   Common::Rect(Common::Point(0,0), 640, 32), //Menu
-  Common::Rect(Common::Point(0,40), 640, 344), //Working
+  Common::Rect(Common::Point(0,40), 640, 344), //Working; aspect ratio 1.86
   Common::Rect(Common::Point(0,400), 640, 80) //Text
 };
 
 enum {
 	WINDOW_WIDTH = 640,//Original 640,
 	WINDOW_HEIGHT = 480,//Original 480,
-	WINDOW_WIDTH_WIDE = 854,
-	WINDOW_HEIGHT_WIDE = 480,
-
 	HIRES_WINDOW_WIDTH = 800, //Original 800
 	HIRES_WINDOW_HEIGHT = 600,  //Original 600
-
-	// Zork Nemesis working window size (original aspect ratio 1.6)
-	ZNM_WORKING_WINDOW_WIDTH = 512, //Original 512
-	ZNM_WORKING_WINDOW_HEIGHT = 320,  //Original 320
-	
-	ZNM_SUBTITLE_HEIGHT = 80, //Original 80
-	ZNM_MENU_HEIGHT = 32,  //Original 80
-
-	// ZGI working window size (original aspect ratio 1.86)
-	ZGI_WORKING_WINDOW_WIDTH = 640, //Original 640
-	ZGI_WORKING_WINDOW_HEIGHT = 344,  //Original 344
-	
-  ZGI_SUBTITLE_HEIGHT = 68, //Original 68
-	ZGI_MENU_HEIGHT = 32,  //Original 68
-
 	ROTATION_SCREEN_EDGE_OFFSET = 60,
 	MAX_ROTATION_SPEED = 400, // Pixels per second
-
 	KEYBUF_SIZE = 20
 };
 
@@ -135,7 +116,6 @@ enum ZVisionAction {
 	kZVisionActionPreferences,
 	kZVisionActionShowFPS,
 	kZVisionActionSkipCutscene,
-
 	kZVisionActionCount
 };
 
@@ -268,7 +248,6 @@ public:
 	}
 
 	void initScreen(bool hiRes=false);
-	void initHiresScreen();
 
 	/**
 	 * Play a video until it is finished. This is a blocking call. It will call


Commit: a5101e0fa1bcf5bfc28efc53bf7f935e5478f8e9
    https://github.com/scummvm/scummvm/commit/a5101e0fa1bcf5bfc28efc53bf7f935e5478f8e9
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:55+02:00

Commit Message:
ZVISION: Create new common directory for general purpose functions.
Move scroller.h & scroller.cpp to this directory.
Abstract focus tracking code from MenuManager into own FocusList class.

Changed paths:
  A engines/zvision/common/focus_list.h
  A engines/zvision/common/scroller.cpp
  A engines/zvision/common/scroller.h
  R engines/zvision/scripting/scroller.cpp
  R engines/zvision/scripting/scroller.h
    engines/zvision/scripting/menu.cpp
    engines/zvision/scripting/menu.h


diff --git a/engines/zvision/common/focus_list.h b/engines/zvision/common/focus_list.h
new file mode 100644
index 00000000000..795cf1fa773
--- /dev/null
+++ b/engines/zvision/common/focus_list.h
@@ -0,0 +1,91 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef focus_list_H
+#define focus_list_H
+
+#include "common/array.h"
+
+template<typename T>
+class FocusList {
+private:
+  Common::Array<T> focus;
+  typedef uint _size_type;  //TODO - find a way to make this typedef inherit from the definition in Common::Array
+public:
+  void set(T currentFocus) {
+    if(!focus.size())
+      focus.push_back(currentFocus);     
+    else {
+      if(focus.front() != currentFocus) {
+        Common::Array<T> buffer;
+        while(focus.size() > 0) {
+          if(focus.back() != currentFocus)
+            buffer.push_back(focus.back());
+          focus.pop_back();
+        }
+        focus.push_back(currentFocus);
+        while(buffer.size() > 0) {
+          focus.push_back(buffer.back());
+          buffer.pop_back();
+        }
+      }
+    }
+  }
+
+  T get(_size_type idx=0) {
+    return focus[idx];
+  }
+
+  T front() {
+    return focus.front();
+  }
+  
+	T &operator[](_size_type idx) {
+		assert(idx < focus.size());
+		return focus[idx];
+	}
+
+  _size_type size() {
+    return focus.size();
+  }
+  
+  void clear() {
+    focus.clear();
+  }
+  
+  void remove(T value) {
+    if(focus.size()) {
+      Common::Array<T> buffer;
+      while(focus.size() > 0) {
+        if(focus.back() != value)
+          buffer.push_back(focus.back());
+        focus.pop_back();
+      }
+      while(buffer.size() > 0) {
+        focus.push_back(buffer.back());
+        buffer.pop_back();
+      }
+    }
+  }
+  
+};
+
+#endif
diff --git a/engines/zvision/scripting/scroller.cpp b/engines/zvision/common/scroller.cpp
similarity index 98%
rename from engines/zvision/scripting/scroller.cpp
rename to engines/zvision/common/scroller.cpp
index fca33a2de1e..72160433baa 100644
--- a/engines/zvision/scripting/scroller.cpp
+++ b/engines/zvision/common/scroller.cpp
@@ -19,7 +19,7 @@
  *
  */
 
-#include "zvision/scripting/scroller.h"
+#include "./scroller.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/scroller.h b/engines/zvision/common/scroller.h
similarity index 100%
rename from engines/zvision/scripting/scroller.h
rename to engines/zvision/common/scroller.h
diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index f70d8d339f9..8488dfbf752 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -35,13 +35,13 @@ enum {
 };
 
 MenuManager::MenuManager(ZVision *engine, const Common::Rect menuArea, const MenuParams params) :
-	_engine{engine},
-  _params{params},
-	menuBarFlag{0xFFFF},
-	_menuArea{menuArea},
-  menuOrigin{menuArea.left,menuArea.top},
-  menuTriggerArea{menuOrigin,_menuArea.width(),_params.triggerHeight},
-  mainScroller{params.activePos, params.idlePos, params.period} {
+	_engine(engine),
+  _params(params),
+	menuBarFlag(0xFFFF),
+	_menuArea(menuArea),
+  menuOrigin(menuArea.left,menuArea.top),
+  menuTriggerArea(menuOrigin,_menuArea.width(),_params.triggerHeight),
+  mainScroller(params.activePos, params.idlePos, params.period) {
 	
 	enableFlags.set_size(6);
   for(int8 i = 0; i < 4; i++) {
@@ -52,7 +52,7 @@ MenuManager::MenuManager(ZVision *engine, const Common::Rect menuArea, const Men
 	}
 	for (int i = 0; i < 4; i++)
     buttonAnim[i] = new LinearScroller(_params.activeFrame,_params.idleFrame,_params.buttonPeriod);
-	menuFocus.push_back(kFocusNone);
+	setFocus(kFocusNone); //Ensure focus list is initialised
 	mainArea = Common::Rect(_params.wMain,hMainMenu);
 	mainArea.moveTo(menuOrigin+mainScroller.Pos);
 }
@@ -204,29 +204,18 @@ void MenuManager::redrawMain() {
   clean = false;
 }
 
+
 void MenuManager::setFocus(int8 currentFocus) {
-  if(menuFocus.front() != currentFocus) {
-    Common::Array<int8> _menuFocus;
-    while(menuFocus.size() > 0) {
-      if(menuFocus.back() != currentFocus)
-        _menuFocus.push_back(menuFocus.back());
-      menuFocus.pop_back();
-    }
-    menuFocus.push_back(currentFocus);
-    while(_menuFocus.size() > 0) {
-      menuFocus.push_back(_menuFocus.back());
-      _menuFocus.pop_back();
-    }
-  }
+  menuFocus.set(currentFocus);
   assert(menuFocus.size() <= 4);
 }
 
 MenuZGI::MenuZGI(ZVision *engine, const Common::Rect menuArea) :
 	MenuManager(engine, menuArea, zgiParams),
-	itemsScroller{Common::Point(0,0), Common::Point(wSideMenuTab-wSideMenu,0), 1000},
-	magicScroller{Common::Point(-wSideMenu,0), Common::Point(-wSideMenuTab,0), 1000},
-	itemsOrigin{menuArea.left, menuArea.top},
-	magicOrigin{menuArea.right, menuArea.top} {
+	itemsScroller(Common::Point(0,0), Common::Point(wSideMenuTab-wSideMenu,0), 1000),
+	magicScroller(Common::Point(-wSideMenu,0), Common::Point(-wSideMenuTab,0), 1000),
+	itemsOrigin(menuArea.left, menuArea.top),
+	magicOrigin(menuArea.right, menuArea.top) {
 
   magicArea = Common::Rect(magicOrigin + magicScroller.Pos, wSideMenu, hSideMenu);
   itemsArea = Common::Rect(itemsOrigin + itemsScroller.Pos, wSideMenu, hSideMenu);
diff --git a/engines/zvision/scripting/menu.h b/engines/zvision/scripting/menu.h
index 178a9db9560..f203bd4988e 100644
--- a/engines/zvision/scripting/menu.h
+++ b/engines/zvision/scripting/menu.h
@@ -29,7 +29,8 @@
 
 #include "zvision/zvision.h"
 #include "zvision/scripting/script_manager.h"
-#include "zvision/scripting/scroller.h"
+#include "zvision/common/scroller.h"
+#include "zvision/common/focus_list.h"
 
 namespace ZVision {
 
@@ -131,7 +132,7 @@ protected:
 	Common::Rect menuHotspots[4];
   int8 mainFrames[4]; //Frame to display of each main menu button; first row is currently displayed, 2nd row is backbuffer for idle animations
   Scroller mainScroller;
-	Common::Array<int8> menuFocus; //Order in which menus have most recently had focus; determines current mouse focus & order in which to redraw them.
+	FocusList<int8> menuFocus;  //Order in which menus have most recently had focus; determines current mouse focus & order in which to redraw them.
 	bool clean = false; //Whether or not to blank
   LinearScroller* buttonAnim[4];
 };


Commit: 4746de599d76a50529cefbbf534d72fbbcd44363
    https://github.com/scummvm/scummvm/commit/4746de599d76a50529cefbbf534d72fbbcd44363
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:55+02:00

Commit Message:
ZVISION: Complete rework of subtitle & message system.
Improve encapsulation by addition of SubtitleManager class.
Tested with standard definition ZGI & Nemesis.
Support for DVD edition still incomplete.
Bug remains in Nemesis that causes forward motion to offset next panorama to incorrect position.

# Conflicts:
#	engines/zvision/video/video.cpp

Changed paths:
  A engines/zvision/text/subtitle_manager.cpp
  A engines/zvision/text/subtitle_manager.h
  R engines/zvision/text/subtitles.cpp
  R engines/zvision/text/subtitles.h
    engines/zvision/core/events.cpp
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/module.mk
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/controls/save_control.cpp
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/effects/music_effect.h
    engines/zvision/scripting/effects/syncsound_effect.cpp
    engines/zvision/scripting/effects/syncsound_effect.h
    engines/zvision/video/video.cpp
    engines/zvision/zvision.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/core/events.cpp b/engines/zvision/core/events.cpp
index 8e9a87e8d0f..0ebe32bc0ac 100644
--- a/engines/zvision/core/events.cpp
+++ b/engines/zvision/core/events.cpp
@@ -26,6 +26,7 @@
 #include "zvision/core/console.h"
 #include "zvision/graphics/cursors/cursor_manager.h"
 #include "zvision/graphics/render_manager.h"
+#include "zvision/text/subtitle_manager.h"
 #include "zvision/scripting/script_manager.h"
 #include "zvision/scripting/menu.h"
 #include "zvision/sound/zork_raw.h"
@@ -78,11 +79,11 @@ void ZVision::cheatCodes(uint8 key) {
 	if (getGameId() == GID_GRANDINQUISITOR) {
 		if (checkCode("IMNOTDEAF")) {
 			// Unknown cheat
-			_renderManager->showDebugMsg(Common::String::format("IMNOTDEAF cheat or debug, not implemented"));
+			_subtitleManager->showDebugMsg(Common::String::format("IMNOTDEAF cheat or debug, not implemented"));
 		}
 
 		if (checkCode("3100OPB")) {
-			_renderManager->showDebugMsg(Common::String::format("Current location: %c%c%c%c",
+			_subtitleManager->showDebugMsg(Common::String::format("Current location: %c%c%c%c",
 			                                    _scriptManager->getStateValue(StateKey_World),
 			                                    _scriptManager->getStateValue(StateKey_Room),
 			                                    _scriptManager->getStateValue(StateKey_Node),
@@ -109,7 +110,7 @@ void ZVision::cheatCodes(uint8 key) {
 		}
 
 		if (checkCode("77MASSAVE")) {
-			_renderManager->showDebugMsg(Common::String::format("Current location: %c%c%c%c",
+			_subtitleManager->showDebugMsg(Common::String::format("Current location: %c%c%c%c",
 			                                    _scriptManager->getStateValue(StateKey_World),
 			                                    _scriptManager->getStateValue(StateKey_Room),
 			                                    _scriptManager->getStateValue(StateKey_Node),
@@ -139,11 +140,11 @@ void ZVision::cheatCodes(uint8 key) {
 
 	if (checkCode("FRAME")) {
 		Common::String fpsStr = Common::String::format("FPS: %d", getFPS());
-		_renderManager->showDebugMsg(fpsStr);
+		_subtitleManager->showDebugMsg(fpsStr);
 	}
 
 	if (checkCode("COMPUTERARCH"))
-		_renderManager->showDebugMsg("COMPUTERARCH: var-viewer not implemented");
+		_subtitleManager->showDebugMsg("COMPUTERARCH: var-viewer not implemented");
 
 	// This cheat essentially toggles the GOxxxx cheat below
 	if (checkCode("XYZZY"))
@@ -248,7 +249,7 @@ void ZVision::processEvents() {
 
 			case kZVisionActionShowFPS: {
 				Common::String fpsStr = Common::String::format("FPS: %d", getFPS());
-				_renderManager->showDebugMsg(fpsStr);
+				_subtitleManager->showDebugMsg(fpsStr);
 				}
 				break;
 			default:
@@ -502,7 +503,7 @@ uint8 ZVision::getZvisionKey(Common::KeyCode scummKeyCode) {
 }
 
 bool ZVision::ifQuit() {
-	if (_renderManager->askQuestion(_stringManager->getTextLine(StringManager::ZVISION_STR_EXITPROMT))) {
+	if (_subtitleManager->askQuestion(_stringManager->getTextLine(StringManager::ZVISION_STR_EXITPROMT))) {
 		quitGame();
 		return true;
 	}
diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 9033e894ad1..2e0f1cdadfe 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -50,16 +50,15 @@ RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const G
 	  _screenArea(_layout.screenArea),
 	  _screenCenter(_screenArea.center()),
 	  _workingArea(_layout.workingArea),
-	  _menuArea(_layout.menuArea),
 	  _textArea(_layout.textArea),
+	  _menuArea(_layout.menuArea),
 	  _pixelFormat(pixelFormat),
 	  _backgroundWidth(0),
 	  _backgroundHeight(0),
 	  _backgroundOffset(0),
 	  _renderTable(_layout.workingArea.width(), _layout.workingArea.height()),
 	  _doubleFPS(doubleFPS),
-	  _widescreen(widescreen),
-	  _subid(0) {
+	  _widescreen(widescreen) {
 	debug(1,"creating render manager");
   //Define graphics modes & screen subarea geometry
 	Graphics::ModeList modes;
@@ -68,12 +67,14 @@ RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const G
     _screenArea = _workingArea;
     _screenCenter = _screenArea.center();
     _menuArea.moveTo(_workingArea.origin());
+    _menuLetterbox.moveTo(_menuArea.origin());
     _textArea.moveTo(_workingArea.left, _workingArea.bottom - _textArea.height());
+    _textLetterbox.moveTo(_textArea.origin());
   }
+  
   _textOffset = _layout.workingArea.origin() - _layout.textArea.origin();
   debug(2,"working area: %d,%d,%d,%d", _workingArea.left, _workingArea.top, _workingArea.bottom, _workingArea.right);
   debug(2,"text area: %d,%d,%d,%d", _textArea.left, _textArea.top, _textArea.bottom, _textArea.right);
-  debug(2,"text offset: %d,%d", _textOffset.x, _textOffset.y);
   modes.push_back(Graphics::Mode(_screenArea.width(), _screenArea.height()));
 #if defined(USE_MPEG2) && defined(USE_A52)
 	if (_engine->getGameId() == GID_GRANDINQUISITOR && (_engine->getFeatures() & ADGF_DVD))
@@ -127,9 +128,29 @@ void RenderManager::initialize(bool hiRes) {
 	  _menuManagedSurface.create(_screen, _menuArea);
   	_textManagedSurface.create(_screen, _textArea);
 	}
+	
+  //Menu & text area dirty rectangles
+  _menuOverlay = _menuArea.findIntersectingRect(_workingArea);
+  if(!_menuOverlay.isEmpty() && _menuArea.left >= _workingArea.left && _menuArea.right <= _workingArea.right)
+    _menuLetterbox = Common::Rect(_menuArea.left, _menuArea.top, _menuArea.right, _workingArea.top);
+  else
+    _menuLetterbox = _menuArea;
+  //Convert to menuArea coordinates
+  _menuLetterbox.translate(-_menuArea.left, -_menuArea.top);
+  _menuOverlay.translate(-_menuArea.left, -_menuArea.top);
+    
+  _textOverlay = _textArea.findIntersectingRect(_workingArea);
+  if(!_textOverlay.isEmpty() && _textArea.left >= _workingArea.left && _textArea.right <= _workingArea.right)
+    _textLetterbox = Common::Rect(_textArea.left, _workingArea.bottom, _textArea.right, _textArea.bottom);
+  else
+    _textLetterbox = _textArea;
+  //Convert to textArea coordinates
+  _textOverlay.translate(-_textArea.left, -_textArea.top);
+  _textLetterbox.translate(-_textArea.left, -_textArea.top);
+	
 	//Clear backbuffer surfaces
-	clearMenuSurface();
-  clearTextSurface();
+	clearMenuSurface(true);
+  clearTextSurface(true);
   
   //Set hardware/window resolution
   initGraphics(_screen.w, _screen.h, &_engine->_screenPixelFormat); 
@@ -138,7 +159,6 @@ void RenderManager::initialize(bool hiRes) {
 
 bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
   debug(10,"renderSceneToScreen");
-  //TODO - add functionality to blank sidebars or letterbox bars as appropriate
   if(!overlayOnly) {
 	  Graphics::Surface *out = &_warpedSceneSurface;
 	  Graphics::Surface *in = &_backgroundSurface;
@@ -343,6 +363,7 @@ const Common::Point RenderManager::screenSpaceToImageSpace(const Common::Point &
   debug(9,"screenSpaceToImageSpace()");
 	if (_workingArea.contains(point)) {
 		// Convert from screen space to working window space
+		//TODO - find & fix bug that causes frame not to be aligned with movement direction in Nemesis when not in widescreen mode.
 		Common::Point newPoint(point - Common::Point(_workingArea.left, _workingArea.top));
 
 		RenderTable::RenderState state = _renderTable.getRenderState();
@@ -576,7 +597,7 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Com
 		return;
 
 	Graphics::Surface *srcAdapted = src.convertTo(dst.format);
-	uint32 keycolor = colorkey & ((1 << (src.format.bytesPerPixel << 3)) - 1);  //TODO - figure out what the crap is going on here.
+	uint32 keycolor = colorkey & ((1 << (src.format.bytesPerPixel << 3)) - 1);
 
 	// Copy srcRect from src surface to dst surface
 	const byte *srcBuffer = (const byte *)srcAdapted->getBasePtr(srcRect.left, srcRect.top);
@@ -628,14 +649,55 @@ void RenderManager::blitSurfaceToBkgScaled(const Graphics::Surface &src, const C
 void RenderManager::blitSurfaceToMenu(const Graphics::Surface &src, int16 x, int16 y, int32 colorkey) {
 	Common::Rect empt;
 	blitSurfaceToSurface(src, empt, _menuSurface, x, y, colorkey);
-  //*/
 	Common::Rect dirty(src.w, src.h);
 	dirty.moveTo(x, y);
 	if (_menuSurfaceDirtyRect.isEmpty())
 		_menuSurfaceDirtyRect = dirty;
 	else
 		_menuSurfaceDirtyRect.extend(dirty);
-	//*/
+}
+
+void RenderManager::clearMenuSurface(bool force, int32 colorkey) {
+  if(force)
+    _menuSurfaceDirtyRect = Common::Rect(_menuArea.width(), _menuArea.height());
+  if(!_menuSurfaceDirtyRect.isEmpty()) {
+	  Common::Rect _menuLetterboxDirty = _menuSurfaceDirtyRect.findIntersectingRect(_menuLetterbox);
+    if(!_menuLetterboxDirty.isEmpty())
+      _menuSurface.fillRect(_menuLetterboxDirty, 0);
+	  Common::Rect _menuOverlayDirty = _menuSurfaceDirtyRect.findIntersectingRect(_menuOverlay);
+    if(!_menuOverlayDirty.isEmpty()) {
+	    _menuSurface.fillRect(_menuOverlayDirty, colorkey);
+      //TODO - mark working window dirty here so that it will redraw & blank overlaid residue on next frame
+    }
+    _menuSurfaceDirtyRect = Common::Rect(0,0);
+  }
+}
+
+void RenderManager::blitSurfaceToText(const Graphics::Surface &src, int16 x, int16 y, int32 colorkey) {
+	Common::Rect empt;
+	blitSurfaceToSurface(src, empt, _textSurface, x, y, colorkey);
+	Common::Rect dirty(src.w, src.h);
+	dirty.moveTo(x, y);
+	if (_textSurfaceDirtyRect.isEmpty())
+		_textSurfaceDirtyRect = dirty;
+	else
+		_textSurfaceDirtyRect.extend(dirty);
+}
+
+void RenderManager::clearTextSurface(bool force, int32 colorkey) {
+  if(force)
+    _textSurfaceDirtyRect = Common::Rect(_textArea.width(),_textArea.height());
+  if(!_textSurfaceDirtyRect.isEmpty()) {
+	  Common::Rect _textLetterboxDirty = _textSurfaceDirtyRect.findIntersectingRect(_textLetterbox);
+    if(!_textLetterboxDirty.isEmpty())
+      _textSurface.fillRect(_textLetterboxDirty, 0);
+	  Common::Rect _textOverlayDirty = _textSurfaceDirtyRect.findIntersectingRect(_textOverlay);
+    if(!_textOverlayDirty.isEmpty()) {
+	    _textSurface.fillRect(_textOverlayDirty, colorkey);
+      //TODO - mark working window dirty here so that it will redraw & blank overlaid residue on next frame
+    }
+    _textSurfaceDirtyRect = Common::Rect(0,0);
+  }
 }
 
 Graphics::Surface *RenderManager::getBkgRect(Common::Rect &rect) {
@@ -743,102 +805,6 @@ void RenderManager::prepareBackground() {
   debug(11,"~prepareBackground()");
 }
 
-void RenderManager::clearMenuSurface(int32 colorkey) {
-  //TODO - reinstate more efficient dirtyrect system
-  //TODO - blank upper letterbox area when NOT in widescreen mode.
-	_menuSurfaceDirtyRect = Common::Rect(0, 0, _menuSurface.w, _menuSurface.h);
-	_menuSurface.fillRect(_menuSurfaceDirtyRect, colorkey);
-}
-
-void RenderManager::clearTextSurface(int32 colorkey) {
-  //TODO - reinstate more efficient dirtyrect system
-  //TODO - blank lower letterbox area when NOT in widescreen mode.
-	_textSurfaceDirtyRect = Common::Rect(0, 0, _textSurface.w, _textSurface.h);
-	_textSurface.fillRect(_textSurfaceDirtyRect, colorkey);
-}
-
-uint16 RenderManager::registerSubtitle(const Common::Rect &area) {
-	_subid++;
-	OneSubtitle sub;
-	sub.redraw = false;
-	sub.timer = -1;
-	sub.todelete = false;
-	sub.r = area;
-	//Original game subtitle scripts appear to define subtitle rectangles relative to origin of working area.
-	//To allow arbitrary aspect ratios, we need to instead place these relative to origin of text area.
-	//This will allow the managed text area to then be arbitrarily placed on the screen to suit different aspect ratios.
-	sub.r.translate(_textOffset.x, _textOffset.y);  //Convert working area coordinates to text area coordinates
-  debug(1,"Registering subtitle area %d, dimenisions %dx%d, position within text area x%d,y%d", _subid, sub.r.width(), sub.r.height(), sub.r.left, sub.r.top);
-	_subsList[_subid] = sub;
-	return _subid;
-}
-
-uint16 RenderManager::registerSubtitle() {
-  //TODO - double check validity of this geometry
-	Common::Rect r(_textArea.left, _textArea.top, _textArea.right, _textArea.bottom);
-	r.translate(-_workingArea.left, -_workingArea.top);
-	return registerSubtitle(r);
-}
-
-void RenderManager::deregisterSubtitle(uint16 id) {
-	if (_subsList.contains(id))
-		_subsList[id].todelete = true;
-}
-
-void RenderManager::deregisterSubtitle(uint16 id, int16 delay) {
-	if (_subsList.contains(id))
-		_subsList[id].timer = delay;
-}
-
-void RenderManager::updateSubtitle(uint16 id, const Common::String &txt) {
-	if (_subsList.contains(id)) {
-		OneSubtitle *sub = &_subsList[id];
-		sub->txt = txt;
-		sub->redraw = true;
-	}
-}
-
-void RenderManager::processSubtitles(uint16 deltatime) {
-  debug(5,"processSubtitles()");
-	bool redraw = false;
-	
-	//Update all subtitles' respective timers; delete expired subtitles.
-	for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
-		if (it->_value.timer != -1) {
-			it->_value.timer -= deltatime;
-			if (it->_value.timer <= 0)
-				it->_value.todelete = true;
-		}
-		if (it->_value.todelete) {
-			_subsList.erase(it);
-			redraw = true;
-		} else if (it->_value.redraw) {
-			redraw = true;
-		}
-	}
-
-	if (redraw) {
-	  //Blank subtitle buffer
-	  clearTextSurface();
-
-    //Cycle through all extant subtitles, if subtitle contains text then render it to an auxiliary buffer within a rectangle specified by that subtitle & blit into main subtitle buffer
-		for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
-			OneSubtitle *sub = &it->_value;
-			if (sub->txt.size()) {
-				Graphics::Surface textSurface;
-				textSurface.create(sub->r.width(), sub->r.height(), _engine->_resourcePixelFormat);
-				textSurface.fillRect(Common::Rect(sub->r.width(), sub->r.height()), -1); //TODO Unnecessary operation?  Check later.
-				_engine->getTextRenderer()->drawTextWithWordWrapping(sub->txt, textSurface, _engine->isWidescreen());
-				Common::Rect empty;
-				blitSurfaceToSurface(textSurface, empty, _textSurface, sub->r.left, sub->r.top, -1);
-				textSurface.free();
-			}
-			sub->redraw = false;
-		}
-	}
-  debug(5,"~processSubtitles()");
-}
-
 Common::Point RenderManager::getBkgSize() {
 	return Common::Point(_backgroundWidth, _backgroundHeight);
 }
@@ -1034,117 +1000,6 @@ void RenderManager::bkgFill(uint8 r, uint8 g, uint8 b) {
 }
 #endif
 
-void RenderManager::timedMessage(const Common::String &str, uint16 milsecs) {
-  //TODO - rework to use new renderscene system
-	uint16 msgid = registerSubtitle();
-	updateSubtitle(msgid, str);
-	deregisterSubtitle(msgid, milsecs);
-}
-
-bool RenderManager::askQuestion(const Common::String &str) {
-	Graphics::Surface backuptextSurface;
-	backuptextSurface.copyFrom(_textSurface);
-	_engine->getTextRenderer()->drawTextWithWordWrapping(str, _textSurface, _engine->isWidescreen());
-	renderSceneToScreen(true); 
-
-	_engine->stopClock();
-
-	int result = 0;
-
-	while (result == 0) {
-		Common::Event evnt;
-		while (_engine->getEventManager()->pollEvent(evnt)) {
-			if (evnt.type == Common::EVENT_KEYDOWN) {
-				// English: yes/no
-				// German: ja/nein
-				// Spanish: si/no
-				// French Nemesis: F4/any other key
-				// French ZGI: oui/non
-				// TODO: Handle this using the keymapper
-				switch (evnt.kbd.keycode) {
-				case Common::KEYCODE_y:
-					if (_engine->getLanguage() == Common::EN_ANY)
-						result = 2;
-					break;
-				case Common::KEYCODE_j:
-					if (_engine->getLanguage() == Common::DE_DEU)
-						result = 2;
-					break;
-				case Common::KEYCODE_s:
-					if (_engine->getLanguage() == Common::ES_ESP)
-						result = 2;
-					break;
-				case Common::KEYCODE_o:
-					if (_engine->getLanguage() == Common::FR_FRA && _engine->getGameId() == GID_GRANDINQUISITOR)
-						result = 2;
-					break;
-				case Common::KEYCODE_F4:
-					if (_engine->getLanguage() == Common::FR_FRA && _engine->getGameId() == GID_NEMESIS)
-						result = 2;
-					break;
-				case Common::KEYCODE_n:
-					result = 1;
-					break;
-				default:
-					if (_engine->getLanguage() == Common::FR_FRA && _engine->getGameId() == GID_NEMESIS)
-						result = 1;
-					break;
-				}
-			}
-		}
-	  renderSceneToScreen(true); 
-		if (_doubleFPS)
-			_system->delayMillis(33);
-		else
-			_system->delayMillis(66);
-	}
-
-  //Clear question graphics by restoring saved subtitle buffer
-  _textSurface.copyFrom(backuptextSurface);
-
-	// Free the surface
-	backuptextSurface.free();
-
-	_engine->startClock();
-	return result == 2;
-}
-
-void RenderManager::delayedMessage(const Common::String &str, uint16 milsecs) {
-  //TODO - find bug in current render system; shows up with widescreen disabled, but not with it enabled.
-	uint16 msgid = registerSubtitle();
-	updateSubtitle(msgid, str);
-  debug(1,"initiating delayed message: %s to subtitle id %d", str.c_str(), msgid);
-	processSubtitles(0);
-	renderSceneToScreen(true);
-	_engine->stopClock();
-
-	uint32 stopTime = _system->getMillis() + milsecs;
-	while (_system->getMillis() < stopTime) {
-		Common::Event evnt;
-		while (_engine->getEventManager()->pollEvent(evnt)) {
-			if (evnt.type == Common::EVENT_KEYDOWN &&
-			        (evnt.kbd.keycode == Common::KEYCODE_SPACE ||
-			         evnt.kbd.keycode == Common::KEYCODE_RETURN ||
-			         evnt.kbd.keycode == Common::KEYCODE_ESCAPE))
-				break;
-		}
-	  renderSceneToScreen(true);
-		if (_doubleFPS)
-			_system->delayMillis(33);
-		else
-			_system->delayMillis(66);
-	}
-	deregisterSubtitle(msgid);
-	_engine->startClock();
-}
-
-void RenderManager::showDebugMsg(const Common::String &msg, int16 delay) {
-	uint16 msgid = registerSubtitle();
-	updateSubtitle(msgid, msg);
-  debug(1,"initiating in-game debug message: %s to subtitle id %d", msg.c_str(), msgid);
-	deregisterSubtitle(msgid, delay);
-}
-
 void RenderManager::updateRotation() {
 	int16 _velocity = _engine->getMouseVelocity() + _engine->getKeyboardVelocity();
 	ScriptManager *scriptManager = _engine->getScriptManager();
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index b68da8e9f2b..d7de44b7b99 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -50,23 +50,10 @@ namespace ZVision {
 
 class RenderManager {
 public:
-  //TODO - eliminate this; old system
-//	RenderManager(ZVision *engine, uint32 windowWidth, uint32 windowHeight, const Common::Rect workingArea, const Common::Rect menuArea, const Graphics::PixelFormat pixelFormat, bool doubleFPS);
 	RenderManager(ZVision *engine, const ScreenLayout layout, const Graphics::PixelFormat pixelFormat, bool doubleFPS, bool widescreen = false);
 	~RenderManager();
 
-private:
-	struct OneSubtitle {
-		Common::Rect r;
-		Common::String txt;
-		int16  timer;
-		bool todelete;
-		bool redraw;
-	};
-
-	typedef Common::HashMap<uint16, OneSubtitle> SubtitleMap;
 	typedef Common::List<GraphicsEffect *> EffectsList;
-
 private:
 	ZVision *_engine;
 	OSystem *_system;
@@ -116,24 +103,31 @@ private:
 	Graphics::ManagedSurface _workingManagedSurface;
 	Common::Rect _backgroundSurfaceDirtyRect;
 
-	// Buffer for subtitles
+//TODO: Migrate this functionality to SubtitleManager to improve encapsulation
+//*
+	// Buffer for drawing subtitles & other messages
 	Graphics::Surface _textSurface;
+	Graphics::ManagedSurface _textManagedSurface;
 	Common::Rect _textSurfaceDirtyRect;
+//*/
 
 	// Rectangle for subtitles & other messages
-	Graphics::ManagedSurface _textManagedSurface;
 	Common::Rect _textArea;
+	Common::Rect _textLetterbox;  //Section of text area to be filled with black when blanked
+	Common::Rect _textOverlay;	//Section of text area to be filled with colorkey when blanked (may potentially intersect text letterbox area if screen/window is wider than working area!)
 
-	// Buffer for menu drawing
+	// Buffer for drawing menu
 	Graphics::Surface _menuSurface;
 	Graphics::ManagedSurface _menuManagedSurface;
-	Common::Rect _menuSurfaceDirtyRect;
-	
-	//Buffer for video playback (render directly for speed; no backbuffer)
-	Graphics::ManagedSurface _vidManagedSurface;
+	Common::Rect _menuSurfaceDirtyRect;  //subrectangle of menu area outside working area
 
 	// Rectangle for menu area
 	Common::Rect _menuArea;
+	Common::Rect _menuLetterbox; //Section of menu area to be filled with black when blanked
+	Common::Rect _menuOverlay;	//Section of menu area to be filled with colorkey when blanked (may potentially intersect menu letterbox area if screen/window is wider than working area!)
+
+	//Buffer for video playback (render directly for speed; no backbuffer)
+	Graphics::ManagedSurface _vidManagedSurface;
 
 	// A buffer used for apply graphics effects
 	Graphics::Surface _effectSurface;
@@ -144,12 +138,6 @@ private:
 	/** Used to warp the background image */
 	RenderTable _renderTable;
 
-	// Internal subtitles counter
-	uint16 _subid;
-
-	// Subtitle list
-	SubtitleMap _subsList;
-
 	// Visual effects list
 	EffectsList _effects;
 
@@ -271,22 +259,23 @@ public:
 	// Blitting surface-to-background methods with scale
 	void blitSurfaceToBkgScaled(const Graphics::Surface &src, const Common::Rect &_dstRect, int32 colorkey = -1);
 
-	// Blitting surface-to-menu methods
+	/**
+	 * Blit from source surface to menu area
+	 *
+	 * @param src       Source surface
+ 	 * @param x         x coordinate relative to menu area origin
+	 * @param y         y coordinate relative to menu area origin
+	 */	
 	void blitSurfaceToMenu(const Graphics::Surface &src, int16 x, int16 y, int32 colorkey = 0);
 
-	// Create subtitle graphics object and return ID
-	uint16 registerSubtitle(const Common::Rect &area);
-	uint16 registerSubtitle();
-
-	// Delete subtitle graphics object by ID
-	void deregisterSubtitle(uint16 id);
-	void deregisterSubtitle(uint16 id, int16 delay);
-
-	// Update subtitle graphics object string content
-	void updateSubtitle(uint16 id, const Common::String &txt);
-
-	// Processing subtitles
-	void processSubtitles(uint16 deltatime);
+	/**
+	 * Blit from source surface to text area
+	 *
+	 * @param src       Source surface
+ 	 * @param x         x coordinate relative to text area origin
+	 * @param y         y coordinate relative to text area origin
+	 */	
+	void blitSurfaceToText(const Graphics::Surface &src, int16 x, int16 y, int32 colorkey = 0);
 
 	// Return background size
 	Common::Point getBkgSize();
@@ -298,11 +287,11 @@ public:
 	Graphics::Surface *loadImage(const Common::Path &file);
 	Graphics::Surface *loadImage(const Common::Path &file, bool transposed);
 
-	// Clear whole/area of menu surface
-	void clearMenuSurface(int32 colorkey = -1);
+	// Clear whole/area of menu backbuffer
+	void clearMenuSurface(bool force=false, int32 colorkey = -1);
 	
-	// Clear whole/area of subtitle surface
-	void clearTextSurface(int32 colorkey = -1);
+	// Clear whole/area of subtitle backbuffer
+	void clearTextSurface(bool force=false, int32 colorkey = -1);
 
 	// Copy needed portion of background surface to workingArea surface
 	void prepareBackground();
@@ -357,11 +346,7 @@ public:
 	// Fill background surface by color
 	void bkgFill(uint8 r, uint8 g, uint8 b);
 #endif
-
-	bool askQuestion(const Common::String &str);
-	void delayedMessage(const Common::String &str, uint16 milsecs);
-	void timedMessage(const Common::String &str, uint16 milsecs);
-	void showDebugMsg(const Common::String &msg, int16 delay = 3000);
+	
 	void checkBorders();
 	void rotateTo(int16 to, int16 time);
 	void updateRotation();
diff --git a/engines/zvision/module.mk b/engines/zvision/module.mk
index 6562501f84c..87ed0033f19 100644
--- a/engines/zvision/module.mk
+++ b/engines/zvision/module.mk
@@ -4,6 +4,7 @@ MODULE_OBJS := \
 	core/console.o \
 	core/clock.o \
 	core/events.o \
+	common/scroller.o \
 	file/lzss_read_stream.o \
 	file/save_manager.o \
 	file/search_manager.o \
@@ -30,7 +31,6 @@ MODULE_OBJS := \
 	scripting/controls/titler_control.o \
 	scripting/inventory.o \
 	scripting/menu.o \
-	scripting/scroller.o \
 	scripting/scr_file_handling.o \
 	scripting/script_manager.o \
 	scripting/effects/animation_effect.o \
@@ -43,7 +43,7 @@ MODULE_OBJS := \
 	sound/midi.o \
 	sound/zork_raw.o \
 	text/string_manager.o \
-	text/subtitles.o \
+	text/subtitle_manager.o \
 	text/text.o \
 	text/truetype_font.o \
 	video/rlf_decoder.o \
diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index f91200c1f85..78148999bc1 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -995,7 +995,8 @@ bool ActionStreamVideo::execute() {
 #endif
 
 	decoder = _engine->loadAnimation(_fileName);
-	Subtitle *sub = (subtitleExists) ? new Subtitle(_engine, subpath, switchToHires) : NULL;
+	uint16 sub = (subtitleExists) ? _engine->getSubtitleManager()->create(subpath) : 0;
+	
 	_engine->getCursorManager()->showMouse(false);
 
 	if (switchToHires) {
@@ -1026,8 +1027,7 @@ bool ActionStreamVideo::execute() {
 		_engine->getRenderManager()->initialize(false);
 	_engine->getCursorManager()->showMouse(true);
 
-	delete decoder;
-	delete sub;
+  _engine->getSubtitleManager()->destroy(sub);
 
 	return true;
 }
diff --git a/engines/zvision/scripting/controls/save_control.cpp b/engines/zvision/scripting/controls/save_control.cpp
index 59b37f0d59b..55d7581396d 100644
--- a/engines/zvision/scripting/controls/save_control.cpp
+++ b/engines/zvision/scripting/controls/save_control.cpp
@@ -29,7 +29,7 @@
 #include "zvision/text/string_manager.h"
 
 #include "zvision/file/save_manager.h"
-#include "zvision/graphics/render_manager.h"
+#include "zvision/text/subtitle_manager.h"
 
 #include "common/str.h"
 #include "common/stream.h"
@@ -97,16 +97,16 @@ bool SaveControl::process(uint32 deltaTimeInMillis) {
 					if (inp->getText().size() > 0) {
 						bool toSave = true;
 						if (iter->exist)
-							if (!_engine->getRenderManager()->askQuestion(_engine->getStringManager()->getTextLine(StringManager::ZVISION_STR_SAVEEXIST)))
+							if (!_engine->getSubtitleManager()->askQuestion(_engine->getStringManager()->getTextLine(StringManager::ZVISION_STR_SAVEEXIST)))
 								toSave = false;
 
 						if (toSave) {
 							_engine->getSaveManager()->saveGame(iter->saveId, inp->getText(), true);
-							_engine->getRenderManager()->delayedMessage(_engine->getStringManager()->getTextLine(StringManager::ZVISION_STR_SAVED), 2000);
+							_engine->getSubtitleManager()->delayedMessage(_engine->getStringManager()->getTextLine(StringManager::ZVISION_STR_SAVED), 2000);
 							_engine->getScriptManager()->changeLocation(_engine->getScriptManager()->getLastMenuLocation());
 						}
 					} else {
-						_engine->getRenderManager()->timedMessage(_engine->getStringManager()->getTextLine(StringManager::ZVISION_STR_SAVEEMPTY), 2000);
+						_engine->getSubtitleManager()->timedMessage(_engine->getStringManager()->getTextLine(StringManager::ZVISION_STR_SAVEEMPTY), 2000);
 					}
 				} else {
 					_engine->getSaveManager()->loadGame(iter->saveId);
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 61b02ff7fc9..61a76c7d982 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -64,7 +64,7 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 	_crossfade = false;
 	_crossfadeTarget = 0;
 	_crossfadeTime = 0;
-	_sub = NULL;
+	_sub = 0;
 	_stereo = false;
 	_loaded = false;
 
@@ -98,10 +98,10 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 		subname.setChar('u', subname.size() - 2);
 		subname.setChar('b', subname.size() - 1);
 
+
 		Common::Path subpath(filename.getParent().appendComponent(subname));
 		if (_engine->getSearchManager()->hasFile(subpath))
-			_sub = new Subtitle(_engine, subpath);
-
+		  _sub = _engine->getSubtitleManager()->create(subpath);
 		_loaded = true;
 	}
 }
@@ -112,7 +112,7 @@ MusicNode::~MusicNode() {
 	if (_key != StateKey_NotSet)
 		_engine->getScriptManager()->setStateValue(_key, 2);
 	if (_sub)
-		delete _sub;
+		_engine->getSubtitleManager()->destroy(_sub);
 	debug(2, "MusicNode: %d destroyed", _key);
 }
 
@@ -152,9 +152,8 @@ bool MusicNode::process(uint32 deltaTimeInMillis) {
 
 		if (_volume != _newvol)
 			setVolume(_newvol);
-
 		if (_sub && _engine->getScriptManager()->getStateValue(StateKey_Subtitles) == 1)
-			_sub->process(_engine->_mixer->getSoundElapsedTime(_handle) / 100);
+			_engine->getSubtitleManager()->update(_engine->_mixer->getSoundElapsedTime(_handle) / 100, _sub);
 	}
 	return false;
 }
diff --git a/engines/zvision/scripting/effects/music_effect.h b/engines/zvision/scripting/effects/music_effect.h
index e39aa3f20c8..06be4f14729 100644
--- a/engines/zvision/scripting/effects/music_effect.h
+++ b/engines/zvision/scripting/effects/music_effect.h
@@ -24,7 +24,7 @@
 
 #include "audio/mixer.h"
 #include "zvision/scripting/scripting_effect.h"
-#include "zvision/text/subtitles.h"
+#include "zvision/text/subtitle_manager.h"
 
 namespace Common {
 class String;
@@ -85,7 +85,7 @@ private:
 	int32 _crossfadeTime;
 	bool _stereo;
 	Audio::SoundHandle _handle;
-	Subtitle *_sub;
+	uint16 _sub;
 	bool _loaded;
 };
 
diff --git a/engines/zvision/scripting/effects/syncsound_effect.cpp b/engines/zvision/scripting/effects/syncsound_effect.cpp
index 9a3b9087df3..fade0238be2 100644
--- a/engines/zvision/scripting/effects/syncsound_effect.cpp
+++ b/engines/zvision/scripting/effects/syncsound_effect.cpp
@@ -37,7 +37,7 @@ namespace ZVision {
 SyncSoundNode::SyncSoundNode(ZVision *engine, uint32 key, Common::Path &filename, int32 syncto)
 	: ScriptingEffect(engine, key, SCRIPTING_EFFECT_AUDIO) {
 	_syncto = syncto;
-	_sub = NULL;
+	_sub = 0;
 
 	Audio::RewindableAudioStream *audioStream = NULL;
 
@@ -59,25 +59,23 @@ SyncSoundNode::SyncSoundNode(ZVision *engine, uint32 key, Common::Path &filename
 
 	Common::Path subpath(filename.getParent().appendComponent(subname));
 	if (_engine->getSearchManager()->hasFile(subpath))
-		_sub = new Subtitle(_engine, subpath);
+		_sub = _engine->getSubtitleManager()->create(subpath);
 }
 
 SyncSoundNode::~SyncSoundNode() {
 	_engine->_mixer->stopHandle(_handle);
 	if (_sub)
-		delete _sub;
+		_engine->getSubtitleManager()->destroy(_sub);
 }
 
 bool SyncSoundNode::process(uint32 deltaTimeInMillis) {
 	if (! _engine->_mixer->isSoundHandleActive(_handle))
 		return stop();
 	else {
-
 		if (_engine->getScriptManager()->getSideFX(_syncto) == NULL)
 			return stop();
-
 		if (_sub && _engine->getScriptManager()->getStateValue(StateKey_Subtitles) == 1)
-			_sub->process(_engine->_mixer->getSoundElapsedTime(_handle) / 100);
+			_engine->getSubtitleManager()->update(_engine->_mixer->getSoundElapsedTime(_handle) / 100, _sub);
 	}
 	return false;
 }
diff --git a/engines/zvision/scripting/effects/syncsound_effect.h b/engines/zvision/scripting/effects/syncsound_effect.h
index 7fd0d4bef26..ad8af81428c 100644
--- a/engines/zvision/scripting/effects/syncsound_effect.h
+++ b/engines/zvision/scripting/effects/syncsound_effect.h
@@ -24,7 +24,7 @@
 
 #include "audio/mixer.h"
 #include "zvision/scripting/scripting_effect.h"
-#include "zvision/text/subtitles.h"
+#include "zvision/text/subtitle_manager.h"
 
 namespace Common {
 class String;
@@ -47,7 +47,7 @@ public:
 private:
 	int32 _syncto;
 	Audio::SoundHandle _handle;
-	Subtitle *_sub;
+	uint16 _sub;
 };
 
 } // End of namespace ZVision
diff --git a/engines/zvision/text/subtitle_manager.cpp b/engines/zvision/text/subtitle_manager.cpp
new file mode 100644
index 00000000000..1b51554faec
--- /dev/null
+++ b/engines/zvision/text/subtitle_manager.cpp
@@ -0,0 +1,359 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "zvision/graphics/render_manager.h"
+#include "zvision/text/subtitle_manager.h"
+#include "zvision/file/search_manager.h"
+#include "zvision/text/text.h"
+#include "common/system.h"
+
+namespace ZVision {
+
+SubtitleManager::SubtitleManager(ZVision *engine, const ScreenLayout layout, const Graphics::PixelFormat pixelFormat, bool doubleFPS) :
+  _engine(engine),
+  _system(engine->_system),
+  _renderManager(engine->getRenderManager()),
+	_pixelFormat(pixelFormat),
+  _textOffset( layout.workingArea.origin() - layout.textArea.origin() ),
+  _textArea( layout.textArea.width(), layout.textArea.height() ),
+  redraw(false),
+	_doubleFPS(doubleFPS),
+  _subId(0)
+  {
+}
+
+SubtitleManager::~SubtitleManager() {
+  //Delete all subtitles referenced in subslist
+  for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
+    delete it->_value;
+		_subsList.erase(it);
+		_subsFocus.clear();
+  }
+}
+
+void SubtitleManager::process(int32 deltatime) {
+	//Update all subtitles' respective deletion timers
+  for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
+		if (it->_value->process(deltatime)) {
+      debug(2,"Deleting subtitle, subId=%d", it->_key);
+			_subsFocus.remove(it->_key);			
+		  delete it->_value;
+			_subsList.erase(it);
+			redraw = true;
+	  }
+  }
+	if(_subsList.size() == 0)
+	  if(_subId != 0) {
+      debug(1,"Resetting subId to 0");
+	    _subId = 0;
+      _subsFocus.clear();
+    }
+	if (redraw) {
+    debug(2,"Redrawing subtitles");
+	  //Blank subtitle buffer
+	  _renderManager->clearTextSurface();
+    //Render just the most recent subtitle
+  	if(_subsFocus.size()) {
+  	  uint16 curSub = _subsFocus.get();
+      debug(2,"Rendering subtitle %d", curSub);     
+      Subtitle *sub = _subsList[curSub];
+		  if (sub->lineId >= 0) { 
+			  Graphics::Surface textSurface;
+			  textSurface.create(sub->r.width(), sub->r.height(), _engine->_resourcePixelFormat);
+			  textSurface.fillRect(Common::Rect(sub->r.width(), sub->r.height()), -1); //TODO Unnecessary operation?  Check later.
+			  _engine->getTextRenderer()->drawTextWithWordWrapping(sub->_lines[sub->lineId].subStr, textSurface, _engine->isWidescreen());
+			  _renderManager->blitSurfaceToText(textSurface, sub->r.left, sub->r.top, -1);
+			  textSurface.free();
+			  sub->redraw = false;
+		  }
+	  }
+	redraw = false;
+	}
+}
+
+
+void SubtitleManager::update(int32 count, uint16 subid) {
+	if (_subsList.contains(subid))
+    if( _subsList[subid]->update(count) ) {
+      //_subsFocus.set(subid);
+      redraw = true;
+    }
+}
+
+uint16 SubtitleManager::create(const Common::Path &subname, bool vob) {
+  _subId++;
+  debug(2,"Creating scripted subtitle, subId=%d", _subId);
+  _subsList[_subId] = new Subtitle(_engine, subname, vob);
+  _subsFocus.set(_subId);
+  return _subId;
+}
+
+uint16 SubtitleManager::create(const Common::String &str) {
+  _subId++;
+  debug(2,"Creating simple subtitle, subId=%d, message %s", _subId, str.c_str());
+  _subsList[_subId] = new Subtitle(_engine, str, _textArea);
+  _subsFocus.set(_subId);
+  return _subId;
+}
+
+void SubtitleManager::destroy(uint16 id) {
+	if (_subsList.contains(id)) {
+    debug(2,"Marking subtitle %d for immediate deletion", id);
+		_subsList[id]->todelete = true;
+		}
+}
+
+void SubtitleManager::destroy(uint16 id, int16 delay) {
+	if (_subsList.contains(id)) {
+    debug(2,"Marking subtitle %d for deletion in %dms", id, delay);	  
+		_subsList[id]->timer = delay;
+		}
+}
+
+void SubtitleManager::timedMessage(const Common::String &str, uint16 milsecs) {
+	uint16 msgid = create(str);
+  debug(1,"initiating timed message: %s to subtitle id %d, time %d", str.c_str(), msgid, milsecs);
+	update(0,msgid);
+	process(0);
+	destroy(msgid, milsecs);
+}
+
+bool SubtitleManager::askQuestion(const Common::String &str) {
+	uint16 msgid = create(str);
+  debug(1,"initiating user question: %s to subtitle id %d", str.c_str(), msgid);
+	update(0,msgid);
+	process(0);
+	_renderManager->renderSceneToScreen(true);
+	_engine->stopClock();
+	int result = 0;
+	while (result == 0) {
+		Common::Event evnt;
+		while (_engine->getEventManager()->pollEvent(evnt)) {
+			if (evnt.type == Common::EVENT_KEYDOWN) {
+				// English: yes/no
+				// German: ja/nein
+				// Spanish: si/no
+				// French Nemesis: F4/any other key  _engine(engine),
+				// French ZGI: oui/non
+				// TODO: Handle this using the keymapper
+				switch (evnt.kbd.keycode) {
+				case Common::KEYCODE_y:
+					if (_engine->getLanguage() == Common::EN_ANY)
+						result = 2;
+					break;
+				case Common::KEYCODE_j:
+					if (_engine->getLanguage() == Common::DE_DEU)
+						result = 2;
+					break;
+				case Common::KEYCODE_s:
+					if (_engine->getLanguage() == Common::ES_ESP)
+						result = 2;
+					break;
+				case Common::KEYCODE_o:
+					if (_engine->getLanguage() == Common::FR_FRA && _engine->getGameId() == GID_GRANDINQUISITOR)
+						result = 2;
+					break;
+				case Common::KEYCODE_F4:
+					if (_engine->getLanguage() == Common::FR_FRA && _engine->getGameId() == GID_NEMESIS)
+						result = 2;
+					break;
+				case Common::KEYCODE_n:
+					result = 1;
+					break;
+				default:
+					if (_engine->getLanguage() == Common::FR_FRA && _engine->getGameId() == GID_NEMESIS)
+						result = 1;
+					break;
+				}
+			}
+		}
+	  _renderManager->renderSceneToScreen(true); 
+		if (_doubleFPS)
+			_system->delayMillis(33);
+		else
+			_system->delayMillis(66);
+	}
+	destroy(msgid);
+	_engine->startClock();
+	return result == 2;
+}
+
+void SubtitleManager::delayedMessage(const Common::String &str, uint16 milsecs) {
+	uint16 msgid = create(str);
+  debug(1,"initiating delayed message: %s to subtitle id %d, delay %dms", str.c_str(), msgid, milsecs);
+	update(0,msgid);
+	process(0);
+	_renderManager->renderSceneToScreen(true);
+	_engine->stopClock();
+
+	uint32 stopTime = _system->getMillis() + milsecs;
+	while (_system->getMillis() < stopTime) {
+		Common::Event evnt;
+		while (_engine->getEventManager()->pollEvent(evnt)) {
+			if (evnt.type == Common::EVENT_KEYDOWN &&
+			        (evnt.kbd.keycode == Common::KEYCODE_SPACE ||
+			         evnt.kbd.keycode == Common::KEYCODE_RETURN ||
+			         evnt.kbd.keycode == Common::KEYCODE_ESCAPE))
+				break;
+		}
+	  _renderManager->renderSceneToScreen(true);
+		if (_doubleFPS)
+			_system->delayMillis(33);
+		else
+			_system->delayMillis(66);
+	}
+	destroy(msgid);
+	_engine->startClock();
+}
+
+void SubtitleManager::showDebugMsg(const Common::String &msg, int16 delay) {
+	uint16 msgid = create(msg);
+  debug(1,"initiating in-game debug message: %s to subtitle id %d, delay %dms", msg.c_str(), msgid, delay);
+	update(0,msgid);
+	process(0);
+	destroy(msgid, delay);
+}
+
+Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool vob) :
+  _engine(engine),
+	lineId(-1),
+	timer(-1),
+	todelete(false),
+	redraw(false) {
+	Common::File subFile;
+  Common::Point _textOffset = _engine->getSubtitleManager()->getTextOffset();
+	if (_engine->getSearchManager()->openFile(subFile, subname)) {
+	  //Parse subtitle parameters from script
+		while (!subFile.eos()) {
+			Common::String str = subFile.readLine();
+			if (str.lastChar() == '~')
+				str.deleteLastChar();
+			if (str.matchString("*Initialization*", true)) {
+				// Not used
+			} 
+			else if (str.matchString("*Rectangle*", true)) {
+				int32 x1, y1, x2, y2;
+				sscanf(str.c_str(), "%*[^:]:%d %d %d %d", &x1, &y1, &x2, &y2);
+				r = Common::Rect(x1, y1, x2, y2);
+				debug(1,"Original subtitle script rectangle coordinates: l%d, t%d, r%d, b%d", x1, y1, x2, y2);				
+	      //Original game subtitle scripts appear to define subtitle rectangles relative to origin of working area.
+	      //To allow arbitrary aspect ratios, we need to instead place these relative to origin of text area.
+	      //This will allow the managed text area to then be arbitrarily placed on the screen to suit different aspect ratios.
+	      r.translate(_textOffset.x, _textOffset.y);  //Convert working area coordinates to text area coordinates
+				debug(1,"Text area coordinates: l%d, t%d, r%d, b%d", r.left, r.top, r.right, r.bottom);	
+			} 
+			else if (str.matchString("*TextFile*", true)) {
+				char filename[64];
+				sscanf(str.c_str(), "%*[^:]:%s", filename);
+				Common::File txtFile;
+				if (_engine->getSearchManager()->openFile(txtFile, Common::Path(filename))) {
+					while (!txtFile.eos()) {
+						Common::String txtline = readWideLine(txtFile).encode();
+						line curLine;
+						curLine.start = -1;
+						curLine.stop = -1;
+						curLine.subStr = txtline;
+						_lines.push_back(curLine);
+					}
+					txtFile.close();
+				}
+			} 
+			else {
+				int32 st; //Line start time
+				int32 en; //Line end time
+				int32 sb; //Line number
+				if (sscanf(str.c_str(), "%*[^:]:(%d,%d)=%d", &st, &en, &sb) == 3) {
+					if (sb <= (int32)_lines.size()) {
+						if (vob) {
+							// Convert frame number from 15FPS (AVI) to 29.97FPS (VOB) to synchronise with video
+							st = st * 2997 / 1500;
+							en = en * 2997 / 1500;
+						}
+						_lines[sb].start = st;
+						_lines[sb].stop = en;
+					}
+				}
+			}
+		}
+    subFile.close();  //NB - this was missing in the original code; suspect a bug, but double check for a reason.
+  }
+  else {
+    //TODO - add error message here
+    todelete = true;
+  }
+}
+
+Subtitle::Subtitle(ZVision *engine, const Common::String &str, const Common::Rect &textArea) :
+  _engine(engine),
+	lineId(-1),
+	timer(-1),
+	todelete(false),
+	redraw(false) {
+	r = textArea;
+	debug(1,"Text area coordinates: l%d, t%d, r%d, b%d", r.left, r.top, r.right, r.bottom);	
+	line curLine;
+	curLine.start = -1;
+	curLine.stop = 0;
+	curLine.subStr = str;
+	_lines.push_back(curLine);
+}
+
+Subtitle::~Subtitle() {
+	_lines.clear();
+}
+
+bool Subtitle::process(int32 deltatime) {
+	if (timer != -1) {
+		timer -= deltatime;
+		if (timer <= 0)
+			todelete = true;
+	}
+	return todelete;
+}
+
+bool Subtitle::update(int32 count) {
+  int16 j = -1;
+  //Search all lines to find first line that encompasses current time/framecount, set j to this
+  for (uint16 i = (lineId >= 0 ? lineId : 0); i < _lines.size(); i++)
+	  if (count >= _lines[i].start && count <= _lines[i].stop) {
+		  j = i;
+		  break;
+	  }
+  if (j == -1) {
+    //No line exists for current time/framecount
+    if(lineId != -1) {
+      //Line is set
+	    lineId = -1; //Unset line
+	    redraw = true;
+    }
+  }
+  else {
+    //Line exists for current time/framecount
+    if (j != lineId && _lines[j].subStr.size()) {
+      //Set line is not equal to current line & current line is not blank
+      lineId = j;  //Set line to current
+      redraw = true;
+    }
+  }
+  return redraw;
+}
+
+} // End of namespace ZVision
diff --git a/engines/zvision/text/subtitle_manager.h b/engines/zvision/text/subtitle_manager.h
new file mode 100644
index 00000000000..cda96e4e872
--- /dev/null
+++ b/engines/zvision/text/subtitle_manager.h
@@ -0,0 +1,110 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef ZVISION_SUBTITLES_H
+#define ZVISION_SUBTITLES_H
+
+#include "zvision/zvision.h"
+#include "zvision/common/focus_list.h"
+
+namespace ZVision {
+
+class ZVision;
+
+class Subtitle {
+friend class SubtitleManager;
+public:
+  Subtitle(ZVision *engine, const Common::Path &subname, bool vob=false);  //For scripted subtitles
+  Subtitle(ZVision *engine, const Common::String &str, const Common::Rect &textArea);  //For other text messages
+  ~Subtitle();
+  
+  bool update(int32 count); //Return true if necessary to redraw
+
+private:
+  bool process(int32 deltatime);  //Return true if to be deleted
+	ZVision *_engine;
+	Common::Rect r;
+	Common::String txt;
+	int16  timer; //Always in milliseconds; countdown to deletion
+	bool todelete;
+	bool redraw;
+	
+	int16 lineId;
+	struct line {
+		int start;
+		int stop;
+		Common::String subStr;
+	};
+	//NB: start & stop do not always use the same units between different instances of this struct!
+	//Sound effect & music subtitles use milliseconds
+	//Video subtitle timings are specified in video frames at 15fps, i.e. in multiples of 66.6' milliseconds!
+    //AVI videos run at 15fps and can have frames counted directly
+    //DVD videos in VOB format run at 29.97 fps and must be converted to work with the subtitle files, which were made for AVI.
+	
+	Common::Array<line> _lines;
+};
+
+class SubtitleManager {
+public:
+  SubtitleManager(ZVision *engine, const ScreenLayout layout, const Graphics::PixelFormat pixelFormat, bool doubleFPS);
+  ~SubtitleManager();  
+private:
+	ZVision *_engine;
+	OSystem *_system;
+	RenderManager *_renderManager;
+	const Graphics::PixelFormat _pixelFormat;
+	const Common::Point _textOffset;  //Position vector of text area origin relative to working window origin
+	const Common::Rect _textArea;
+	bool redraw;
+	bool _doubleFPS;
+	// Internal subtitle ID counter
+	uint16 _subId;
+
+	typedef Common::HashMap<uint16, Subtitle*> SubtitleMap;
+
+	// Subtitle list
+	SubtitleMap _subsList;
+	// Subtitle focus history
+  FocusList<uint16> _subsFocus;
+  
+public:
+  void process(int32 deltatime);  //deltatime is always milliseconds
+	void update(int32 count, uint16 subid);  //Count is milliseconds for sound & music; frames for video playback.
+	
+  Common::Point getTextOffset() {return _textOffset;}
+	
+	// Create subtitle object and return ID
+	uint16 create(const Common::Path &subname, bool vob = false);
+	uint16 create(const Common::String &str);
+
+	// Delete subtitle object by ID
+	void destroy(uint16 id);
+	void destroy(uint16 id, int16 delay);
+	
+	bool askQuestion(const Common::String &str);
+	void delayedMessage(const Common::String &str, uint16 milsecs);
+	void timedMessage(const Common::String &str, uint16 milsecs);
+	void showDebugMsg(const Common::String &msg, int16 delay = 3000);
+};
+
+}
+
+#endif
diff --git a/engines/zvision/text/subtitles.cpp b/engines/zvision/text/subtitles.cpp
deleted file mode 100644
index c3d7b8ae12a..00000000000
--- a/engines/zvision/text/subtitles.cpp
+++ /dev/null
@@ -1,117 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#include "zvision/graphics/render_manager.h"
-#include "zvision/text/subtitles.h"
-#include "zvision/file/search_manager.h"
-#include "zvision/text/text.h"
-
-namespace ZVision {
-
-Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool upscaleToHires) :
-	_engine(engine),
-	_areaId(-1),
-	_subId(-1) {
-	Common::File file;
-	//Parse subtitle parameters from script
-	if (_engine->getSearchManager()->openFile(file, subname)) {
-		while (!file.eos()) {
-			Common::String str = file.readLine();
-			if (str.lastChar() == '~')
-				str.deleteLastChar();
-			if (str.matchString("*Initialization*", true)) {
-				// Not used
-			} 
-			else if (str.matchString("*Rectangle*", true)) {
-				int32 x1, y1, x2, y2;
-				sscanf(str.c_str(), "%*[^:]:%d %d %d %d", &x1, &y1, &x2, &y2);
-				Common::Rect rct = Common::Rect(x1, y1, x2, y2);
-				if (upscaleToHires)
-					_engine->getRenderManager()->upscaleRect(rct);
-				_areaId = _engine->getRenderManager()->registerSubtitle(rct);
-				debug(1,"Original subtitle script rectangle coordinates: l%d, t%d, r%d, b%d", x1, y1, x2, y2);
-			} 
-			else if (str.matchString("*TextFile*", true)) {
-				char filename[64];
-				sscanf(str.c_str(), "%*[^:]:%s", filename);
-				Common::File txt;
-				if (_engine->getSearchManager()->openFile(txt, Common::Path(filename))) {
-					while (!txt.eos()) {
-						Common::String txtline = readWideLine(txt).encode();
-						sub curSubtitle;
-						curSubtitle.start = -1;
-						curSubtitle.stop = -1;
-						curSubtitle.subStr = txtline;
-
-						_subs.push_back(curSubtitle);
-					}
-					txt.close();
-				}
-			} 
-			else {
-				int32 st;
-				int32 en;
-				int32 sb;
-				if (sscanf(str.c_str(), "%*[^:]:(%d,%d)=%d", &st, &en, &sb) == 3) {
-					if (sb <= (int32)_subs.size()) {
-						if (upscaleToHires) {
-							// Convert from 15FPS (AVI) to 29.97FPS (VOB)
-							st = st * 2997 / 1500;
-							en = en * 2997 / 1500;
-						}
-						_subs[sb].start = st;
-						_subs[sb].stop = en;
-					}
-				}
-			}
-		}
-	}
-}
-
-Subtitle::~Subtitle() {
-	if (_areaId != -1)
-		_engine->getRenderManager()->deregisterSubtitle(_areaId);
-	_subs.clear();
-}
-
-void Subtitle::process(int32 time) {
-	int16 j = -1;
-	for (uint16 i = 0; i < _subs.size(); i++)
-		if (time >= _subs[i].start && time <= _subs[i].stop) {
-			j = i;
-			break;
-		}
-
-	if (j == -1 && _subId != -1) {
-		if (_areaId != -1)
-			_engine->getRenderManager()->updateSubtitle(_areaId, "");
-		_subId = -1;
-	}
-
-	if (j != -1 && j != _subId) {
-		if (_subs[j].subStr.size())
-			if (_areaId != -1)
-				_engine->getRenderManager()->updateSubtitle(_areaId, _subs[j].subStr);
-		_subId = j;
-	}
-}
-
-} // End of namespace ZVision
diff --git a/engines/zvision/text/subtitles.h b/engines/zvision/text/subtitles.h
deleted file mode 100644
index 4d2a1751a02..00000000000
--- a/engines/zvision/text/subtitles.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/* ScummVM - Graphic Adventure Engine
- *
- * ScummVM is the legal property of its developers, whose names
- * are too numerous to list here. Please refer to the COPYRIGHT
- * file distributed with this source distribution.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
- */
-
-#ifndef ZVISION_SUBTITLES_H
-#define ZVISION_SUBTITLES_H
-
-#include "zvision/zvision.h"
-
-namespace ZVision {
-
-class ZVision;
-
-class Subtitle {
-public:
-	Subtitle(ZVision *engine, const Common::Path &subname, bool upscaleToHires = false);
-	~Subtitle();
-
-	void process(int32 time);
-private:
-	ZVision *_engine;
-	int32 _areaId;
-	int16 _subId;
-
-	struct sub {
-		int start;
-		int stop;
-		Common::String subStr;
-	};
-
-	Common::Array<sub> _subs;
-};
-
-}
-
-#endif
diff --git a/engines/zvision/video/video.cpp b/engines/zvision/video/video.cpp
index 4a628cf1c51..e8239b21203 100644
--- a/engines/zvision/video/video.cpp
+++ b/engines/zvision/video/video.cpp
@@ -34,7 +34,7 @@
 #include "zvision/core/clock.h"
 #include "zvision/graphics/render_manager.h"
 #include "zvision/scripting/script_manager.h"
-#include "zvision/text/subtitles.h"
+#include "zvision/text/subtitle_manager.h"
 #include "zvision/video/rlf_decoder.h"
 #include "zvision/video/zork_avi_decoder.h"
 
@@ -79,7 +79,7 @@ Video::VideoDecoder *ZVision::loadAnimation(const Common::Path &fileName) {
    * @param sub       Subtitle associated with video
    */	
 	 
-void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, bool skippable, Subtitle *sub) {
+void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, bool skippable, uint16 sub) {
 	Common::Rect dst = dstRect;
 	Common::Rect _workingArea = _renderManager->getWorkingArea();
 	// If dstRect is empty, no specific scaling was requested. However, we may choose to do scaling anyway
@@ -132,17 +132,17 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 
 		if (vid.needsUpdate()) {
 			const Graphics::Surface *frame = vid.decodeNextFrame();
-			if (sub && showSubs)
-				sub->process(vid.getCurFrame());
+			if (showSubs && sub > 0)
+				_subtitleManager->update(vid.getCurFrame(), sub);
 			if (frame) {
 				if (scaled) {
 					_renderManager->scaleBuffer(frame->getPixels(), scaled->getPixels(), frame->w, frame->h, frame->format.bytesPerPixel, scaled->w, scaled->h);
-					frame = scaled; 
+					frame = scaled;
 				}
 				Common::Rect rect = Common::Rect(finalWidth, finalHeight);
-				debug(2,"Blitting from area %d x %d to video output surface at area %d, %d", frame->w, frame->h, dst.left, dst.top);
-				outSurface.simpleBlitFrom(*frame, rect, Common::Point(0,0));
-				_renderManager->processSubtitles(0);
+				debug(8,"Blitting from area %d x %d to video output surface at area %d, %d", frame->w, frame->h, dst.left, dst.top);
+				outSurface.simpleBlitFrom(*frame, rect, Common::Point(0,0));				
+				_subtitleManager->process(0);
 			}
 		}
 		// Always update the screen so the mouse continues to render & video does not skip
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index 4c309a7763c..970033bc3db 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -25,6 +25,7 @@
 #include "zvision/core/console.h"
 #include "zvision/scripting/script_manager.h"
 #include "zvision/graphics/render_manager.h"
+#include "zvision/text/subtitle_manager.h"
 #include "zvision/graphics/cursors/cursor_manager.h"
 #include "zvision/file/save_manager.h"
 #include "zvision/text/string_manager.h"
@@ -98,6 +99,7 @@ ZVision::ZVision(OSystem *syst, const ZVisionGameDescription *gameDesc)
 	  _midiManager(nullptr),
 	  _rnd(nullptr),
 	  _menu(nullptr),
+	  _subtitleManager(nullptr),
 	  _searchManager(nullptr),
 	  _textRenderer(nullptr),
 	  _doubleFPS(false),
@@ -123,6 +125,7 @@ ZVision::~ZVision() {
 	delete _saveManager;
 	delete _scriptManager;
 	delete _renderManager;	// should be deleted after the script manager
+	delete _subtitleManager;	
 	delete _rnd;
 	delete _midiManager;
 	getTimerManager()->removeTimerProc(&fpsTimerCallback);
@@ -204,10 +207,12 @@ void ZVision::initialize() {
     case GID_NEMESIS:
       _renderManager = new RenderManager(this, nemesisLayout, _resourcePixelFormat, _doubleFPS, _widescreen);
 	    _menu = new MenuNemesis(this, _renderManager->getMenuArea());
+      _subtitleManager = new SubtitleManager(this, nemesisLayout, _resourcePixelFormat, _doubleFPS);
 	    break;
     case GID_GRANDINQUISITOR:
       _renderManager = new RenderManager(this, zgiLayout, _resourcePixelFormat, _doubleFPS, _widescreen);
 		  _menu = new MenuZGI(this, _renderManager->getMenuArea());
+      _subtitleManager = new SubtitleManager(this, zgiLayout, _resourcePixelFormat, _doubleFPS);
 		  break;
 	  case GID_NONE:
 	  default:
@@ -336,10 +341,11 @@ Common::Error ZVision::run() {
 		_scriptManager->update(deltaTime);
     debug(5,"Menu");
 		_menu->process(deltaTime);
+    debug(5,"Subtitles");
+		_subtitleManager->process(deltaTime);
 	  debug(5,"Render");
 		// Render the backBuffer to the screen
 		_renderManager->prepareBackground();
-		_renderManager->processSubtitles(deltaTime);
 		if(_renderManager->renderSceneToScreen())
 			_renderedFrameCount++;
 		else
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index a3946298551..1e10070a0d5 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -64,6 +64,7 @@ class StringManager;
 class SaveManager;
 class RLFDecoder;
 class MenuManager;
+class SubtitleManager;
 class TextRenderer;
 class Subtitle;
 class MidiManager;
@@ -165,6 +166,7 @@ private:
 	MidiManager *_midiManager;
 	SaveManager *_saveManager;
 	MenuManager *_menu;
+  SubtitleManager *_subtitleManager;
 
 	// Clock
 	Clock _clock;
@@ -223,6 +225,9 @@ public:
 	MenuManager *getMenuManager() const {
 		return _menu;
 	}
+	SubtitleManager *getSubtitleManager() const {
+		return _subtitleManager;
+	}
 
 	Common::Keymap *getGameKeymap() const {
 		return _gameKeymap;
@@ -258,7 +263,7 @@ public:
 	 * @param destRect        Where to put the video. (In working window coords)
 	 * @param skippable       If true, the video can be skipped at any time using [Spacebar]
 	 */
-	void playVideo(Video::VideoDecoder &videoDecoder, const Common::Rect &destRect = Common::Rect(0, 0, 0, 0), bool skippable = true, Subtitle *sub = NULL);
+	void playVideo(Video::VideoDecoder &videoDecoder, const Common::Rect &destRect = Common::Rect(0, 0, 0, 0), bool skippable = true, uint16 sub = 0);
 	Video::VideoDecoder *loadAnimation(const Common::Path &fileName);
 
 	void setRenderDelay(uint);


Commit: c83aa95a8dc6e95643b304ce3c02d99181eee7d2
    https://github.com/scummvm/scummvm/commit/c83aa95a8dc6e95643b304ce3c02d99181eee7d2
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:55+02:00

Commit Message:
ZVISION: Add support for DVD edition in widescreen & original resolution.
Amend subtitle synchronisation parameters for 29fps playback.
Bugs introduced in ZGI; sarcophagus videos do not play correctly.
Mouse position also not translating correctly between screen & playfield coordinates.

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/text/subtitle_manager.cpp
    engines/zvision/video/video.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 2e0f1cdadfe..66cdb1bb3a7 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -62,23 +62,15 @@ RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const G
 	debug(1,"creating render manager");
   //Define graphics modes & screen subarea geometry
 	Graphics::ModeList modes;
-  if (_widescreen) {
-    _workingArea.moveTo(0,0);
-    _screenArea = _workingArea;
-    _screenCenter = _screenArea.center();
-    _menuArea.moveTo(_workingArea.origin());
-    _menuLetterbox.moveTo(_menuArea.origin());
-    _textArea.moveTo(_workingArea.left, _workingArea.bottom - _textArea.height());
-    _textLetterbox.moveTo(_textArea.origin());
-  }
-  
   _textOffset = _layout.workingArea.origin() - _layout.textArea.origin();
-  debug(2,"working area: %d,%d,%d,%d", _workingArea.left, _workingArea.top, _workingArea.bottom, _workingArea.right);
-  debug(2,"text area: %d,%d,%d,%d", _textArea.left, _textArea.top, _textArea.bottom, _textArea.right);
   modes.push_back(Graphics::Mode(_screenArea.width(), _screenArea.height()));
 #if defined(USE_MPEG2) && defined(USE_A52)
-	if (_engine->getGameId() == GID_GRANDINQUISITOR && (_engine->getFeatures() & ADGF_DVD))
-		modes.push_back(Graphics::Mode(HIRES_WINDOW_WIDTH, HIRES_WINDOW_HEIGHT));
+	if (_engine->getGameId() == GID_GRANDINQUISITOR && (_engine->getFeatures() & ADGF_DVD)) {
+	  if(_widescreen)
+  		modes.push_back(Graphics::Mode(_HDscreenAreaWide.width(), _HDscreenAreaWide.height()));
+		else
+  		modes.push_back(Graphics::Mode(_HDscreenArea.width(), _HDscreenArea.height()));
+  }
 #endif
 	initGraphicsModes(modes);
   //Create backbuffers
@@ -106,28 +98,44 @@ RenderManager::~RenderManager() {
 void RenderManager::initialize(bool hiRes) {
   debug(1,"Initializing render manager");
   _hiRes = hiRes;
+  
+  _screenArea = _layout.screenArea;
+  _workingArea =_layout.workingArea;
+  _textArea = _layout.textArea;
+  _menuArea = _layout.menuArea;
+  
+  if (_widescreen) {
+    _workingArea.moveTo(0,0);
+    _screenArea = _workingArea;
+    _menuArea.moveTo(_workingArea.origin());
+    _menuLetterbox.moveTo(_menuArea.origin());
+    _textArea.moveTo(_workingArea.left, _workingArea.bottom - _textArea.height());
+    _textLetterbox.moveTo(_textArea.origin());
+  }
+  
   //Screen
-  if(_hiRes)
-    _screen.create(HIRES_WINDOW_WIDTH, HIRES_WINDOW_HEIGHT, _pixelFormat);
+#if defined(USE_MPEG2) && defined(USE_A52)
+  if(_hiRes) {
+    debug(1,"Switching to high resolution");
+    upscaleRect(_screenArea);
+    upscaleRect(_workingArea);
+    upscaleRect(_textArea);
+  }
   else
-    _screen.create(_screenArea.width(), _screenArea.height(), _pixelFormat);
+    debug(1,"Switching to standard resolution");
+#endif
+  _screen.create(_screenArea.width(), _screenArea.height(), _pixelFormat);
 	_screen.setTransparentColor(-1);
 	_screen.clear();
+  _screenCenter = _screenArea.center();
+  
 	//Managed screen subsurfaces
-	if(_hiRes) {
-	  Common::Rect hiResWorkingArea = _workingArea;
-  	upscaleRect(hiResWorkingArea);
-  	_workingManagedSurface.create(_screen, hiResWorkingArea);
-	  Common::Rect hiResTextArea = _textArea;
-  	upscaleRect(hiResTextArea);
-  	_textManagedSurface.create(_screen, hiResTextArea);
-	}
-	else {
-    debug("_menuArea %d, %d, %d, %d", _menuArea.left, _menuArea.top, _menuArea.right, _menuArea.bottom);
-  	_workingManagedSurface.create(_screen, _workingArea);
-	  _menuManagedSurface.create(_screen, _menuArea);
-  	_textManagedSurface.create(_screen, _textArea);
-	}
+	_workingManagedSurface.create(_screen, _workingArea);
+  _menuManagedSurface.create(_screen, _menuArea);
+	_textManagedSurface.create(_screen, _textArea);
+  debug(2,"screen area: %d,%d,%d,%d", _screenArea.left, _screenArea.top, _screenArea.bottom, _screenArea.right);
+  debug(2,"working area: %d,%d,%d,%d", _workingArea.left, _workingArea.top, _workingArea.bottom, _workingArea.right);
+  debug(2,"text area: %d,%d,%d,%d", _textArea.left, _textArea.top, _textArea.bottom, _textArea.right);
 	
   //Menu & text area dirty rectangles
   _menuOverlay = _menuArea.findIntersectingRect(_workingArea);
@@ -139,6 +147,7 @@ void RenderManager::initialize(bool hiRes) {
   _menuLetterbox.translate(-_menuArea.left, -_menuArea.top);
   _menuOverlay.translate(-_menuArea.left, -_menuArea.top);
     
+  //TODO - add upscaling for HD mode!
   _textOverlay = _textArea.findIntersectingRect(_workingArea);
   if(!_textOverlay.isEmpty() && _textArea.left >= _workingArea.left && _textArea.right <= _workingArea.right)
     _textLetterbox = Common::Rect(_textArea.left, _workingArea.bottom, _textArea.right, _textArea.bottom);
@@ -148,12 +157,15 @@ void RenderManager::initialize(bool hiRes) {
   _textOverlay.translate(-_textArea.left, -_textArea.top);
   _textLetterbox.translate(-_textArea.left, -_textArea.top);
 	
+  debug(2,"Clearing backbuffers");
 	//Clear backbuffer surfaces
 	clearMenuSurface(true);
   clearTextSurface(true);
+  debug(2,"Backbuffers cleared");
   
   //Set hardware/window resolution
-  initGraphics(_screen.w, _screen.h, &_engine->_screenPixelFormat); 
+  debug(1,"_screen.w = %d, _screen.h = %d", _screen.w, _screen.h);
+  initGraphics(_screen.w, _screen.h, &_engine->_screenPixelFormat);
 	debug(1,"Render manager initialized");
 }
 
@@ -233,7 +245,7 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
 
 Graphics::ManagedSurface &RenderManager::getVidSurface(Common::Rect &dstRect) {
   Common::Rect _dstRect = dstRect;
-  _dstRect.translate(_workingArea.left, _workingArea.top);
+  _dstRect.translate(_workingArea.left, _workingArea.top);  //Error here??
 	_vidManagedSurface.create(_screen, _dstRect);
 	debug(1,"Obtaining managed video surface at %d,%d,%d,%d", _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
 	return _vidManagedSurface;
@@ -547,7 +559,6 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Com
 
 //SIMPLIFIED FUNCTION
 //TODO - find bug that breaks panorama rotation.  Suspect problem with negative arguments of some sort.
-//*
 void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect , Graphics::Surface &dst, int _x, int _y) {
 	Common::Rect srcRect = _srcRect;
 	Common::Point dstPos = Common::Point(_x,_y);
@@ -1134,10 +1145,13 @@ void RenderManager::rotateTo(int16 _toPos, int16 _time) {
 }
 
 void RenderManager::upscaleRect(Common::Rect &rect) {
-	rect.top = rect.top * HIRES_WINDOW_HEIGHT / WINDOW_HEIGHT;
-	rect.left = rect.left * HIRES_WINDOW_WIDTH / WINDOW_WIDTH;
-	rect.bottom = rect.bottom * HIRES_WINDOW_HEIGHT / WINDOW_HEIGHT;
-	rect.right = rect.right * HIRES_WINDOW_WIDTH / WINDOW_WIDTH;
+  Common::Rect _HDscreen = _widescreen ? _HDscreenAreaWide : _HDscreenArea;
+  Common::Rect _SDscreen = _widescreen ? _layout.workingArea : _layout.screenArea;
+  _SDscreen.moveTo(0,0);
+	rect.top = rect.top * _HDscreen.height() / _SDscreen.height();
+	rect.left = rect.left * _HDscreen.width() / _SDscreen.width();
+	rect.bottom = rect.bottom * _HDscreen.height() / _SDscreen.height();
+	rect.right = rect.right * _HDscreen.width() / _SDscreen.width();
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index d7de44b7b99..055a95b2706 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -66,6 +66,9 @@ private:
 	 */	
 	Common::Rect _screenArea;
 	
+	Common::Rect _HDscreenArea = Common::Rect(800,600);
+	Common::Rect _HDscreenAreaWide = Common::Rect(720,377);
+	
 	Common::Point _screenCenter; //Center of the screen at current resolution
 	
 	Common::Point _textOffset;  //Position vector of text area origin relative to working window origin
diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index 78148999bc1..febfaaf7dd7 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -963,8 +963,11 @@ ActionStreamVideo::ActionStreamVideo(ZVision *engine, int32 slotKey, const Commo
 }
 
 bool ActionStreamVideo::execute() {
+  debug(2,"Executing video stream");
 	Video::VideoDecoder *decoder;
 	Common::Rect destRect = Common::Rect(_x1, _y1, _x2 + 1, _y2 + 1);
+	Common::Rect srcRect = Common::Rect(0,0);
+  debug(2,"Streaming video original scripted destination left=%d, top=%d, right=%d, bottom=%d", destRect.left, destRect.top, destRect.right, destRect.bottom);
 	Common::String subname = _fileName.baseName();
 	subname.setChar('s', subname.size() - 3);
 	subname.setChar('u', subname.size() - 2);
@@ -995,15 +998,16 @@ bool ActionStreamVideo::execute() {
 #endif
 
 	decoder = _engine->loadAnimation(_fileName);
-	uint16 sub = (subtitleExists) ? _engine->getSubtitleManager()->create(subpath) : 0;
+	uint16 sub = (subtitleExists) ? _engine->getSubtitleManager()->create(subpath, switchToHires) : 0;
 	
 	_engine->getCursorManager()->showMouse(false);
 
 	if (switchToHires) {
 		_engine->getRenderManager()->initialize(true);
-		destRect = Common::Rect(40, -40, 760, 440); //Placed relative to working window origin, of course.
-		//ZGI hi-res video resolution = 720x480, with baked-in letterboxing around video at 720x387 resolution (at origin 0,77) conforming to playfield aspect ratio 0f 1.86
-		//At 800x600 screen resolution, with original video origin position of (40,-40), the letterboxed are will play at position 40,37.  Weird.
+    srcRect = Common::Rect(Common::Point(0,69),720, 344);
+		//ZGI hi-res video resolution = 720x480, with baked-in letterboxing around video at 720x344 resolution (at origin 0,69) conforming to playfield vertical resolution of 344
+		destRect = _engine->getRenderManager()->getWorkingArea(); //Game scripts only give destRect for normal resolution; we must manually override them for HD videos
+		destRect.moveTo(0,0);
 	}
 
 	// WORKAROUND for what appears to be a script bug. When riding with
@@ -1019,16 +1023,14 @@ bool ActionStreamVideo::execute() {
 	bool pauseBackgroundMusic = _engine->getGameId() == GID_GRANDINQUISITOR && (_fileName == "hp3ea021.avi" || _fileName == "hp4ea051.avi");
 	if (pauseBackgroundMusic)
 		_engine->_mixer->pauseAll(true);
-	_engine->playVideo(*decoder, destRect, _skippable, sub);
+	_engine->playVideo(*decoder, destRect, _skippable, sub, srcRect);
 	if (pauseBackgroundMusic)
 		_engine->_mixer->pauseAll(false);
-
 	if (switchToHires)
 		_engine->getRenderManager()->initialize(false);
 	_engine->getCursorManager()->showMouse(true);
-
   _engine->getSubtitleManager()->destroy(sub);
-
+  debug(2,"Completed executing video stream");
 	return true;
 }
 
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index a0312b8e49b..85a272a38b1 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -89,6 +89,7 @@ void ScriptManager::update(uint deltaTimeMillis) {
 	}
 
 	updateNodes(deltaTimeMillis);
+	debug(5,"Script nodes updated");
 	if (!execScope(nodeview)) {
 		return;
 	}
diff --git a/engines/zvision/text/subtitle_manager.cpp b/engines/zvision/text/subtitle_manager.cpp
index 1b51554faec..551055cef9a 100644
--- a/engines/zvision/text/subtitle_manager.cpp
+++ b/engines/zvision/text/subtitle_manager.cpp
@@ -284,8 +284,10 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool vob) :
 					if (sb <= (int32)_lines.size()) {
 						if (vob) {
 							// Convert frame number from 15FPS (AVI) to 29.97FPS (VOB) to synchronise with video
-							st = st * 2997 / 1500;
-							en = en * 2997 / 1500;
+							//st = st * 2997 / 1500;
+							//en = en * 2997 / 1500;
+							st = st * 2900 / 1500;  //TODO: Subtitles only synchronise correctly at 29fps, but vob files should be 29.97fps; check if video codec is rounding this value down!
+							en = en * 2900 / 1500;
 						}
 						_lines[sb].start = st;
 						_lines[sb].stop = en;
@@ -293,7 +295,7 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool vob) :
 				}
 			}
 		}
-    subFile.close();  //NB - this was missing in the original code; suspect a bug, but double check for a reason.
+    subFile.close();
   }
   else {
     //TODO - add error message here
diff --git a/engines/zvision/video/video.cpp b/engines/zvision/video/video.cpp
index e8239b21203..2eb9c8e3606 100644
--- a/engines/zvision/video/video.cpp
+++ b/engines/zvision/video/video.cpp
@@ -77,33 +77,39 @@ Video::VideoDecoder *ZVision::loadAnimation(const Common::Path &fileName) {
    * @param dstRect   Rectangle to play video into, defined relative to working window origin; video will scale to rectangle automatically.
  	 * @param skippable Allow video to be skipped
    * @param sub       Subtitle associated with video
+   * @param srcRect   Rectangle within video frame, defined relative to frame origin, to blit to output.  Only used for removing baked-in letterboxing in ZGI DVD HD videos
    */	
 	 
-void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, bool skippable, uint16 sub) {
-	Common::Rect dst = dstRect;
+void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, bool skippable, uint16 sub, const Common::Rect &srcRect) {
+	Common::Rect _dstRect = dstRect;
+	Common::Rect _srcRect = srcRect;
+	Common::Rect _frameArea = Common::Rect(vid.getWidth(), vid.getHeight());
 	Common::Rect _workingArea = _renderManager->getWorkingArea();
 	// If dstRect is empty, no specific scaling was requested. However, we may choose to do scaling anyway
-	if (dst.isEmpty())
-		dst = Common::Rect(vid.getWidth(), vid.getHeight());
-
-	Graphics::ManagedSurface &outSurface = _renderManager->getVidSurface(dst);
-  debug(1, "Playing video, size %d x %d, at working window offset %d, %d", outSurface.w, outSurface.h, dst.left, dst.top);
-
-	Graphics::Surface *scaled = NULL;
+	bool scaled=false;
+	_workingArea.moveTo(0,0); //Set local origin system in this scope to origin of working area
+	if (_dstRect.isEmpty())
+		_dstRect = _frameArea;
+	_dstRect.clip(_workingArea);
+  Common::Point _dstPos = _dstRect.origin();
+	
+	if (_srcRect.isEmpty())
+		_srcRect = _frameArea;
+	else
+	  _srcRect.clip(_frameArea);
 
-	if (vid.getWidth() != dst.width() || vid.getHeight() != dst.height()) {
-		scaled = new Graphics::Surface;
-		scaled->create(dst.width(), dst.height(), vid.getPixelFormat());
+	Graphics::ManagedSurface &outSurface = _renderManager->getVidSurface(_dstRect);
+	_dstRect.clip(Common::Rect(outSurface.w, outSurface.h));
+	
+  debug(1, "Playing video, size %d x %d, at working window offset %d, %d", _srcRect.width(), _srcRect.height(), _dstRect.left, _dstRect.top);
+	if (_srcRect.width() != _dstRect.width() || _srcRect.height() != _dstRect.height()) {
+	  debug(1,"Video will be scaled from %dx%d to %dx%d", _srcRect.width(), _srcRect.height(), _dstRect.width(), _dstRect.height());
+	  scaled = true;
 	}
-
-	uint16 finalWidth = dst.width() < _workingArea.width() ? dst.width() : _workingArea.width();
-	uint16 finalHeight = dst.height() < _workingArea.height() ? dst.height() : _workingArea.height();
 	bool showSubs = (_scriptManager->getStateValue(StateKey_Subtitles) == 1);
-
 	_clock.stop();
 	vid.start();
 	_videoIsPlaying = true;
-
 	_cutscenesKeymap->setEnabled(true);
 	_gameKeymap->setEnabled(false);
 
@@ -136,12 +142,13 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 				_subtitleManager->update(vid.getCurFrame(), sub);
 			if (frame) {
 				if (scaled) {
-					_renderManager->scaleBuffer(frame->getPixels(), scaled->getPixels(), frame->w, frame->h, frame->format.bytesPerPixel, scaled->w, scaled->h);
-					frame = scaled;
-				}
-				Common::Rect rect = Common::Rect(finalWidth, finalHeight);
-				debug(8,"Blitting from area %d x %d to video output surface at area %d, %d", frame->w, frame->h, dst.left, dst.top);
-				outSurface.simpleBlitFrom(*frame, rect, Common::Point(0,0));				
+				  debug(8,"Scaled blit from area %d x %d to video output surface at position %d, %d", _srcRect.width(), _srcRect.height(), _dstPos.x, _dstPos.y);
+					outSurface.blitFrom(*frame, _srcRect, _dstRect);
+					}
+        else {
+				  debug(8,"Simple blit from area %d x %d to video output surface at position %d, %d", _srcRect.width(), _srcRect.height(), _dstPos.x, _dstPos.y);
+				  outSurface.simpleBlitFrom(*frame, _srcRect, _dstRect.origin());
+			  }
 				_subtitleManager->process(0);
 			}
 		}
@@ -149,17 +156,11 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 		_renderManager->renderSceneToScreen(true,true);
 		_system->delayMillis(vid.getTimeToNextFrame() / 2); //Exponentially decaying delay
 	}
-
 	_cutscenesKeymap->setEnabled(false);
 	_gameKeymap->setEnabled(true);
-
 	_videoIsPlaying = false;
 	_clock.start();
-
-	if (scaled) {
-		scaled->free();
-		delete scaled;
-	}
+  debug(1, "Video playback complete");
 }
 
 double ZVision::getVobAmplification(Common::String fileName) const {
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index 1e10070a0d5..f7008a6a3da 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -81,25 +81,38 @@ struct ScreenLayout {
 //TODO Need to make a decision how to handle this.  Should be irrelevant for widescreen mode anyway, & purists will want original appearance for 4:3 ratio.
 //Figures below currently have playfield offset to fit subtitles entirely in lower bar
 
+/*/
+//Vertically offset values
 static const ScreenLayout nemesisLayout {
   Common::Rect(640,480),  //Screen
   Common::Rect(Common::Point(64,0), 512, 32), //Menu
   Common::Rect(Common::Point(64,40), 512, 320), //Working; aspect ratio 1.6
   Common::Rect(Common::Point(64,380), 512, 100) //Text
 };
-
 static const ScreenLayout zgiLayout {
   Common::Rect(640,480),  //Screen
   Common::Rect(Common::Point(0,0), 640, 32), //Menu
   Common::Rect(Common::Point(0,40), 640, 344), //Working; aspect ratio 1.86
   Common::Rect(Common::Point(0,400), 640, 80) //Text
 };
+//*/
+//*/
+//Central values
+static const ScreenLayout nemesisLayout {
+  Common::Rect(640,480),  //Screen
+  Common::Rect(Common::Point(64,0), 512, 32), //Menu
+  Common::Rect(Common::Point(64,80), 512, 320), //Working; aspect ratio 1.6
+  Common::Rect(Common::Point(64,420), 512, 60) //Text
+};
 
+static const ScreenLayout zgiLayout {
+  Common::Rect(640,480),  //Screen
+  Common::Rect(Common::Point(0,0), 640, 32), //Menu
+  Common::Rect(Common::Point(0,68), 640, 344), //Working; aspect ratio 1.86
+  Common::Rect(Common::Point(0,412), 640, 68) //Text
+};
+//*/
 enum {
-	WINDOW_WIDTH = 640,//Original 640,
-	WINDOW_HEIGHT = 480,//Original 480,
-	HIRES_WINDOW_WIDTH = 800, //Original 800
-	HIRES_WINDOW_HEIGHT = 600,  //Original 600
 	ROTATION_SCREEN_EDGE_OFFSET = 60,
 	MAX_ROTATION_SPEED = 400, // Pixels per second
 	KEYBUF_SIZE = 20
@@ -261,9 +274,10 @@ public:
 	 *
 	 * @param videoDecoder    The video to play
 	 * @param destRect        Where to put the video. (In working window coords)
+	 * @param clipRect        What subset of video to blit to destRect (In video frame coords)  //TODO implement
 	 * @param skippable       If true, the video can be skipped at any time using [Spacebar]
 	 */
-	void playVideo(Video::VideoDecoder &videoDecoder, const Common::Rect &destRect = Common::Rect(0, 0, 0, 0), bool skippable = true, uint16 sub = 0);
+	void playVideo(Video::VideoDecoder &videoDecoder, const Common::Rect &destRect = Common::Rect(0, 0, 0, 0), bool skippable = true, uint16 sub = 0, const Common::Rect &srcRect = Common::Rect(0, 0, 0, 0));
 	Video::VideoDecoder *loadAnimation(const Common::Path &fileName);
 
 	void setRenderDelay(uint);


Commit: fd68aaaf66e057f3755fc094b383e0cf27e65414
    https://github.com/scummvm/scummvm/commit/fd68aaaf66e057f3755fc094b383e0cf27e65414
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:55+02:00

Commit Message:
ZVISION: Fix menu hotspot bug in Nemesis.
Fix panorama alignment bug; rename _screenCenter to _workingAreaCenter for clarity.
Comment amendment clarifying coordinate systems.

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/graphics/render_table.h
    engines/zvision/scripting/menu.cpp
    engines/zvision/scripting/menu.h


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 66cdb1bb3a7..dba59d32168 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -48,8 +48,8 @@ RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const G
 	  _system(engine->_system),
 	  _layout(layout),
 	  _screenArea(_layout.screenArea),
-	  _screenCenter(_screenArea.center()),
 	  _workingArea(_layout.workingArea),
+	  _workingAreaCenter(Common::Point(_workingArea.width()/2, _workingArea.height()/2)),
 	  _textArea(_layout.textArea),
 	  _menuArea(_layout.menuArea),
 	  _pixelFormat(pixelFormat),
@@ -80,6 +80,7 @@ RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const G
 	_menuSurface.create(_menuArea.width(), _menuArea.height(), _pixelFormat);
 	_textSurface.create(_textArea.width(), _textArea.height(), _pixelFormat);
 	debug(1,"render manager created");
+  initialize(false);
 }
 
 RenderManager::~RenderManager() {
@@ -127,8 +128,9 @@ void RenderManager::initialize(bool hiRes) {
   _screen.create(_screenArea.width(), _screenArea.height(), _pixelFormat);
 	_screen.setTransparentColor(-1);
 	_screen.clear();
-  _screenCenter = _screenArea.center();
   
+  debug(1,"_workingAreaCenter = %d,%d", _workingAreaCenter.x, _workingAreaCenter.y);
+
 	//Managed screen subsurfaces
 	_workingManagedSurface.create(_screen, _workingArea);
   _menuManagedSurface.create(_screen, _menuArea);
@@ -375,8 +377,7 @@ const Common::Point RenderManager::screenSpaceToImageSpace(const Common::Point &
   debug(9,"screenSpaceToImageSpace()");
 	if (_workingArea.contains(point)) {
 		// Convert from screen space to working window space
-		//TODO - find & fix bug that causes frame not to be aligned with movement direction in Nemesis when not in widescreen mode.
-		Common::Point newPoint(point - Common::Point(_workingArea.left, _workingArea.top));
+		Common::Point newPoint(point - _workingArea.origin());
 
 		RenderTable::RenderState state = _renderTable.getRenderState();
 		if (state == RenderTable::PANORAMA || state == RenderTable::TILT) {
@@ -384,9 +385,9 @@ const Common::Point RenderManager::screenSpaceToImageSpace(const Common::Point &
 		}
 
 		if (state == RenderTable::PANORAMA) {
-			newPoint += (Common::Point(_backgroundOffset - _screenCenter.x, 0));
+			newPoint += (Common::Point(_backgroundOffset - _workingAreaCenter.x, 0));
 		} else if (state == RenderTable::TILT) {
-			newPoint += (Common::Point(0, _backgroundOffset - _screenCenter.y));
+			newPoint += (Common::Point(0, _backgroundOffset - _workingAreaCenter.y));
 		}
 
 		if (_backgroundWidth)
@@ -747,44 +748,44 @@ void RenderManager::prepareBackground() {
 	if (state == RenderTable::PANORAMA) {
 		// Calculate the visible portion of the background
 		Common::Rect viewPort(_workingArea.width(), _workingArea.height());
-		viewPort.translate(-(_screenCenter.x - _backgroundOffset), 0);
+		viewPort.translate(-(_workingAreaCenter.x - _backgroundOffset), 0);
 		Common::Rect drawRect = _backgroundDirtyRect;
 		drawRect.clip(viewPort);
 
 		// Render the visible portion
 		if (!drawRect.isEmpty()) {
-			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _screenCenter.x - _backgroundOffset + drawRect.left, drawRect.top);
+			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _workingAreaCenter.x - _backgroundOffset + drawRect.left, drawRect.top);
 		}
 
 		// Mark the dirty portion of the surface
 		_backgroundSurfaceDirtyRect = _backgroundDirtyRect;
-		_backgroundSurfaceDirtyRect.translate(_screenCenter.x - _backgroundOffset, 0);
+		_backgroundSurfaceDirtyRect.translate(_workingAreaCenter.x - _backgroundOffset, 0);
 
 		// Panorama mode allows the user to spin in circles. Therefore, we need to render
 		// the portion of the image that wrapped to the other side of the screen
-		if (_backgroundOffset < _screenCenter.x) {
-			viewPort.moveTo(-(_screenCenter.x - (_backgroundOffset + _backgroundWidth)), 0);
+		if (_backgroundOffset < _workingAreaCenter.x) {
+			viewPort.moveTo(-(_workingAreaCenter.x - (_backgroundOffset + _backgroundWidth)), 0);
 			drawRect = _backgroundDirtyRect;
 			drawRect.clip(viewPort);
 
 			if (!drawRect.isEmpty())
-				blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _screenCenter.x - (_backgroundOffset + _backgroundWidth) + drawRect.left, drawRect.top);
+				blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _workingAreaCenter.x - (_backgroundOffset + _backgroundWidth) + drawRect.left, drawRect.top);
 
 			Common::Rect tmp = _backgroundDirtyRect;
-			tmp.translate(_screenCenter.x - (_backgroundOffset + _backgroundWidth), 0);
+			tmp.translate(_workingAreaCenter.x - (_backgroundOffset + _backgroundWidth), 0);
 			if (!tmp.isEmpty())
 				_backgroundSurfaceDirtyRect.extend(tmp);
 
-		} else if (_backgroundWidth - _backgroundOffset < _screenCenter.x) {
-			viewPort.moveTo(-(_screenCenter.x + _backgroundWidth - _backgroundOffset), 0);
+		} else if (_backgroundWidth - _backgroundOffset < _workingAreaCenter.x) {
+			viewPort.moveTo(-(_workingAreaCenter.x + _backgroundWidth - _backgroundOffset), 0);
 			drawRect = _backgroundDirtyRect;
 			drawRect.clip(viewPort);
 
 			if (!drawRect.isEmpty())
-				blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _screenCenter.x + _backgroundWidth - _backgroundOffset + drawRect.left, drawRect.top);
+				blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _workingAreaCenter.x + _backgroundWidth - _backgroundOffset + drawRect.left, drawRect.top);
 
 			Common::Rect tmp = _backgroundDirtyRect;
-			tmp.translate(_screenCenter.x + _backgroundWidth - _backgroundOffset, 0);
+			tmp.translate(_workingAreaCenter.x + _backgroundWidth - _backgroundOffset, 0);
 			if (!tmp.isEmpty())
 				_backgroundSurfaceDirtyRect.extend(tmp);
 
@@ -792,15 +793,15 @@ void RenderManager::prepareBackground() {
 	} else if (state == RenderTable::TILT) {
 		// Tilt doesn't allow wrapping, so we just do a simple clip
 		Common::Rect viewPort(_workingArea.width(), _workingArea.height());
-		viewPort.translate(0, -(_screenCenter.y - _backgroundOffset));
+		viewPort.translate(0, -(_workingAreaCenter.y - _backgroundOffset));
 		Common::Rect drawRect = _backgroundDirtyRect;
 		drawRect.clip(viewPort);
 		if (!drawRect.isEmpty())
-			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, drawRect.left, _screenCenter.y - _backgroundOffset + drawRect.top);
+			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, drawRect.left, _workingAreaCenter.y - _backgroundOffset + drawRect.top);
 
 		// Mark the dirty portion of the surface
 		_backgroundSurfaceDirtyRect = _backgroundDirtyRect;
-		_backgroundSurfaceDirtyRect.translate(0, _screenCenter.y - _backgroundOffset);
+		_backgroundSurfaceDirtyRect.translate(0, _workingAreaCenter.y - _backgroundOffset);
 
 	} else {
 		if (!_backgroundDirtyRect.isEmpty())
@@ -839,33 +840,33 @@ Common::Rect RenderManager::transformBackgroundSpaceRectToScreenSpace(const Comm
 	RenderTable::RenderState state = _renderTable.getRenderState();
 
 	if (state == RenderTable::PANORAMA) {
-		if (_backgroundOffset < _screenCenter.x) {
-			Common::Rect rScreen(_screenCenter.x + _backgroundOffset, _workingArea.height());
+		if (_backgroundOffset < _workingAreaCenter.x) {
+			Common::Rect rScreen(_workingAreaCenter.x + _backgroundOffset, _workingArea.height());
 			Common::Rect lScreen(_workingArea.width() - rScreen.width(), _workingArea.height());
 			lScreen.translate(_backgroundWidth - lScreen.width(), 0);
 			lScreen.clip(src);
 			rScreen.clip(src);
 			if (rScreen.width() < lScreen.width()) {
-				tmp.translate(_screenCenter.x - _backgroundOffset - _backgroundWidth, 0);
+				tmp.translate(_workingAreaCenter.x - _backgroundOffset - _backgroundWidth, 0);
 			} else {
-				tmp.translate(_screenCenter.x - _backgroundOffset, 0);
+				tmp.translate(_workingAreaCenter.x - _backgroundOffset, 0);
 			}
-		} else if (_backgroundWidth - _backgroundOffset < _screenCenter.x) {
-			Common::Rect rScreen(_screenCenter.x - (_backgroundWidth - _backgroundOffset), _workingArea.height());
+		} else if (_backgroundWidth - _backgroundOffset < _workingAreaCenter.x) {
+			Common::Rect rScreen(_workingAreaCenter.x - (_backgroundWidth - _backgroundOffset), _workingArea.height());
 			Common::Rect lScreen(_workingArea.width() - rScreen.width(), _workingArea.height());
 			lScreen.translate(_backgroundWidth - lScreen.width(), 0);
 			lScreen.clip(src);
 			rScreen.clip(src);
 			if (lScreen.width() < rScreen.width()) {
-				tmp.translate(_screenCenter.x + (_backgroundWidth - _backgroundOffset), 0);
+				tmp.translate(_workingAreaCenter.x + (_backgroundWidth - _backgroundOffset), 0);
 			} else {
-				tmp.translate(_screenCenter.x - _backgroundOffset, 0);
+				tmp.translate(_workingAreaCenter.x - _backgroundOffset, 0);
 			}
 		} else {
-			tmp.translate(_screenCenter.x - _backgroundOffset, 0);
+			tmp.translate(_workingAreaCenter.x - _backgroundOffset, 0);
 		}
 	} else if (state == RenderTable::TILT) {
-		tmp.translate(0, (_screenCenter.y - _backgroundOffset));
+		tmp.translate(0, (_workingAreaCenter.y - _backgroundOffset));
 	}
 
 	return tmp;
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index 055a95b2706..ca91e053468 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -69,8 +69,6 @@ private:
 	Common::Rect _HDscreenArea = Common::Rect(800,600);
 	Common::Rect _HDscreenAreaWide = Common::Rect(720,377);
 	
-	Common::Point _screenCenter; //Center of the screen at current resolution
-	
 	Common::Point _textOffset;  //Position vector of text area origin relative to working window origin
 
 	/**
@@ -80,6 +78,8 @@ private:
 	 */
 	Common::Rect _workingArea;
 	
+	Common::Point _workingAreaCenter; //Center of the working area in working area coordinates
+	
 	/**
 	Managed surface representing physical screen; dirty rectangles will be handled automatically by this from now on
     */
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index 4e8e3f42ac0..f8a1b8b87fa 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -65,7 +65,7 @@ public:
 	}
 	void setRenderState(RenderState newState);
 
-	const Common::Point convertWarpedCoordToFlatCoord(const Common::Point &point);
+	const Common::Point convertWarpedCoordToFlatCoord(const Common::Point &point);  //input point in working area coordinates
 
 	void mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 destWidth, const Common::Rect &subRect);
 	void mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf);
diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index 8488dfbf752..09170b1c2a2 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -39,7 +39,7 @@ MenuManager::MenuManager(ZVision *engine, const Common::Rect menuArea, const Men
   _params(params),
 	menuBarFlag(0xFFFF),
 	_menuArea(menuArea),
-  menuOrigin(menuArea.left,menuArea.top),
+  menuOrigin(menuArea.origin()),
   menuTriggerArea(menuOrigin,_menuArea.width(),_params.triggerHeight),
   mainScroller(params.activePos, params.idlePos, params.period) {
 	
@@ -168,7 +168,7 @@ void MenuManager::process(uint32 deltatime) {
 	if(mainScroller.update(deltatime)) {
 	  mainArea.moveTo(menuOrigin+mainScroller.Pos);
     for (int i = 0; i < 4; i++)
-      menuHotspots[i].moveTo(_menuArea.left + _params.wxButs[i][1], _menuArea.top + mainScroller.Pos.y);
+      menuHotspots[i].moveTo(menuOrigin + Common::Point(_params.wxButs[i][1], mainScroller.Pos.y));
 		redraw = true;
 	}
   //Update button highlight animation frame
@@ -204,7 +204,6 @@ void MenuManager::redrawMain() {
   clean = false;
 }
 
-
 void MenuManager::setFocus(int8 currentFocus) {
   menuFocus.set(currentFocus);
   assert(menuFocus.size() <= 4);
diff --git a/engines/zvision/scripting/menu.h b/engines/zvision/scripting/menu.h
index f203bd4988e..6e4c96bbb41 100644
--- a/engines/zvision/scripting/menu.h
+++ b/engines/zvision/scripting/menu.h
@@ -141,7 +141,7 @@ class MenuZGI: public MenuManager {
 public:
 	MenuZGI(ZVision *engine, Common::Rect menuArea);
 	~MenuZGI() override;
-	void onMouseMove(const Common::Point &Pos) override;
+	void onMouseMove(const Common::Point &Pos) override;  //NB Pos is in screen coordinates
 	void onMouseUp(const Common::Point &Pos) override;
 	void process(uint32 deltaTimeInMillis) override;
   bool inMenu(const Common::Point &Pos) override;


Commit: 4f80c8c90491373ced247567fa708486ca16ab21
    https://github.com/scummvm/scummvm/commit/4f80c8c90491373ced247567fa708486ca16ab21
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:55+02:00

Commit Message:
ZVISION: Code cleanup.

Changed paths:
    engines/zvision/graphics/render_manager.cpp


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index dba59d32168..d80c86623e0 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -378,23 +378,22 @@ const Common::Point RenderManager::screenSpaceToImageSpace(const Common::Point &
 	if (_workingArea.contains(point)) {
 		// Convert from screen space to working window space
 		Common::Point newPoint(point - _workingArea.origin());
-
-		RenderTable::RenderState state = _renderTable.getRenderState();
-		if (state == RenderTable::PANORAMA || state == RenderTable::TILT) {
-			newPoint = _renderTable.convertWarpedCoordToFlatCoord(newPoint);
-		}
-
-		if (state == RenderTable::PANORAMA) {
-			newPoint += (Common::Point(_backgroundOffset - _workingAreaCenter.x, 0));
-		} else if (state == RenderTable::TILT) {
-			newPoint += (Common::Point(0, _backgroundOffset - _workingAreaCenter.y));
-		}
-
+		switch(_renderTable.getRenderState()) {
+		  case RenderTable::PANORAMA:
+			  newPoint = _renderTable.convertWarpedCoordToFlatCoord(newPoint);		  
+			  newPoint += (Common::Point(_backgroundOffset - _workingAreaCenter.x, 0));
+			  break;
+		  case RenderTable::TILT:
+			  newPoint = _renderTable.convertWarpedCoordToFlatCoord(newPoint);
+			  newPoint += (Common::Point(0, _backgroundOffset - _workingAreaCenter.y));
+			  break;
+		  default:
+		    break;
+	  }
 		if (_backgroundWidth)
 			newPoint.x %= _backgroundWidth;
 		if (_backgroundHeight)
 			newPoint.y %= _backgroundHeight;
-
 		if (newPoint.x < 0)
 			newPoint.x += _backgroundWidth;
 		if (newPoint.y < 0)
@@ -419,23 +418,26 @@ void RenderManager::setBackgroundImage(const Common::Path &fileName) {
 }
 
 void RenderManager::setBackgroundPosition(int offset) {
-	RenderTable::RenderState state = _renderTable.getRenderState();
-	if (state == RenderTable::TILT || state == RenderTable::PANORAMA)
-		if (_backgroundOffset != offset)
-			_backgroundDirtyRect = Common::Rect(_backgroundWidth, _backgroundHeight);
-	_backgroundOffset = offset;
-	_engine->getScriptManager()->setStateValue(StateKey_ViewPos, offset);
+	switch(_renderTable.getRenderState()) {
+	  case RenderTable::PANORAMA :	
+	  case RenderTable::TILT :
+		  if (_backgroundOffset != offset)
+			  _backgroundDirtyRect = Common::Rect(_backgroundWidth, _backgroundHeight);
+		  break;
+	  default :
+	    break;
+	}
+ 	_backgroundOffset = offset;
+	_engine->getScriptManager()->setStateValue(StateKey_ViewPos, offset); 
 }
 
 uint32 RenderManager::getCurrentBackgroundOffset() {
-	RenderTable::RenderState state = _renderTable.getRenderState();
-
-	if (state == RenderTable::PANORAMA) {
-		return _backgroundOffset;
-	} else if (state == RenderTable::TILT) {
-		return _backgroundOffset;
-	} else {
-		return 0;
+	switch(_renderTable.getRenderState()) {
+	  case RenderTable::PANORAMA :
+	  case RenderTable::TILT :
+  		return _backgroundOffset;
+		default :
+		  return 0;
 	}
 }
 
@@ -448,12 +450,10 @@ Graphics::Surface *RenderManager::tranposeSurface(const Graphics::Surface *surfa
 
 	for (int y = 0; y < tranposedSurface->h; ++y) {
 		int columnIndex = y * tranposedSurface->w;
-
 		for (int x = 0; x < tranposedSurface->w; ++x) {
 			dest[columnIndex + x] = source[x * surface->w + y];
 		}
 	}
-
 	return tranposedSurface;
 }
 


Commit: c47e29b1a9c3cc38029ca97cfbc55823d4423041
    https://github.com/scummvm/scummvm/commit/c47e29b1a9c3cc38029ca97cfbc55823d4423041
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:55+02:00

Commit Message:
ZVISION: Fix sarcophagus video playback in Nemesis.

Changed paths:
    engines/zvision/video/video.cpp


diff --git a/engines/zvision/video/video.cpp b/engines/zvision/video/video.cpp
index 2eb9c8e3606..78f59cafbb6 100644
--- a/engines/zvision/video/video.cpp
+++ b/engines/zvision/video/video.cpp
@@ -88,20 +88,29 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 	// If dstRect is empty, no specific scaling was requested. However, we may choose to do scaling anyway
 	bool scaled=false;
 	_workingArea.moveTo(0,0); //Set local origin system in this scope to origin of working area
+	
+  debug(1, "Playing video, source %d,%d,%d,%d, at destination %d,%d,%d,%d", _srcRect.left, _srcRect.top, _srcRect.right, _srcRect.bottom, _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
+	
 	if (_dstRect.isEmpty())
 		_dstRect = _frameArea;
 	_dstRect.clip(_workingArea);
-  Common::Point _dstPos = _dstRect.origin();
+  
+  debug(2, "Clipped dstRect = %d,%d,%d,%d", _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
 	
 	if (_srcRect.isEmpty())
 		_srcRect = _frameArea;
 	else
 	  _srcRect.clip(_frameArea);
+	  
+  debug(2, "Clipped srcRect = %d,%d,%d,%d", _srcRect.left, _srcRect.top, _srcRect.right, _srcRect.bottom);
 
 	Graphics::ManagedSurface &outSurface = _renderManager->getVidSurface(_dstRect);
+	_dstRect.moveTo(0,0);
 	_dstRect.clip(Common::Rect(outSurface.w, outSurface.h));
+
+  debug(2, "dstRect clipped with outSurface = %d,%d,%d,%d", _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
 	
-  debug(1, "Playing video, size %d x %d, at working window offset %d, %d", _srcRect.width(), _srcRect.height(), _dstRect.left, _dstRect.top);
+  debug(1, "Final size %d x %d, at working window coordinates %d, %d", _srcRect.width(), _srcRect.height(), _dstRect.left, _dstRect.top);
 	if (_srcRect.width() != _dstRect.width() || _srcRect.height() != _dstRect.height()) {
 	  debug(1,"Video will be scaled from %dx%d to %dx%d", _srcRect.width(), _srcRect.height(), _dstRect.width(), _dstRect.height());
 	  scaled = true;
@@ -142,11 +151,11 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 				_subtitleManager->update(vid.getCurFrame(), sub);
 			if (frame) {
 				if (scaled) {
-				  debug(8,"Scaled blit from area %d x %d to video output surface at position %d, %d", _srcRect.width(), _srcRect.height(), _dstPos.x, _dstPos.y);
+				  debug(8,"Scaled blit from area %d x %d to video output surface at output surface position %d, %d", _srcRect.width(), _srcRect.height(), _dstRect.left, _dstRect.top);
 					outSurface.blitFrom(*frame, _srcRect, _dstRect);
 					}
         else {
-				  debug(8,"Simple blit from area %d x %d to video output surface at position %d, %d", _srcRect.width(), _srcRect.height(), _dstPos.x, _dstPos.y);
+				  debug(8,"Simple blit from area %d x %d to video output surface at output surface position %d, %d", _srcRect.width(), _srcRect.height(), _dstRect.left, _dstRect.top);
 				  outSurface.simpleBlitFrom(*frame, _srcRect, _dstRect.origin());
 			  }
 				_subtitleManager->process(0);


Commit: 3a4de15fdedb999b92dba94dd48069745dcda2f8
    https://github.com/scummvm/scummvm/commit/3a4de15fdedb999b92dba94dd48069745dcda2f8
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:55+02:00

Commit Message:
ZVISION: Code cleanup, additional comments, debugging messages.

Changed paths:
    engines/zvision/file/save_manager.cpp
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_table.cpp
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/actions.h
    engines/zvision/scripting/control.cpp
    engines/zvision/scripting/effects/distort_effect.cpp
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/text/subtitle_manager.cpp
    engines/zvision/video/video.cpp


diff --git a/engines/zvision/file/save_manager.cpp b/engines/zvision/file/save_manager.cpp
index a21a5d540ab..21b84017f49 100644
--- a/engines/zvision/file/save_manager.cpp
+++ b/engines/zvision/file/save_manager.cpp
@@ -43,30 +43,23 @@ bool SaveManager::scummVMSaveLoadDialog(bool isSave) {
 	GUI::SaveLoadChooser *dialog;
 	Common::String desc;
 	int slot;
-
 	if (isSave) {
 		dialog = new GUI::SaveLoadChooser(_("Save game:"), _("Save"), true);
-
 		slot = dialog->runModalWithCurrentTarget();
 		desc = dialog->getResultString();
-
 		if (desc.empty()) {
 			// create our own description for the saved game, the user didn't enter it
 			desc = dialog->createDefaultSaveDescription(slot);
 		}
-
 		if (desc.size() > 28)
 			desc = Common::String(desc.c_str(), 28);
 	} else {
 		dialog = new GUI::SaveLoadChooser(_("Restore game:"), _("Restore"), false);
 		slot = dialog->runModalWithCurrentTarget();
 	}
-
 	delete dialog;
-
 	if (slot < 0)
 		return false;
-
 	if (isSave) {
 		saveGame(slot, desc, false);
 		return true;
@@ -79,42 +72,32 @@ bool SaveManager::scummVMSaveLoadDialog(bool isSave) {
 void SaveManager::saveGame(uint slot, const Common::String &saveName, bool useSaveBuffer) {
 	if (!_tempSave && useSaveBuffer)
 		return;
-
 	Common::SaveFileManager *saveFileManager = g_system->getSavefileManager();
 	Common::OutSaveFile *file = saveFileManager->openForSaving(_engine->getSaveStateName(slot));
-
 	writeSaveGameHeader(file, saveName, useSaveBuffer);
-
 	if (useSaveBuffer)
 		file->write(_tempSave->getData(), _tempSave->size());
 	else
 		_engine->getScriptManager()->serialize(file);
-
 	file->finalize();
 	delete file;
-
 	if (useSaveBuffer)
 		flushSaveBuffer();
-
 	_lastSaveTime = g_system->getMillis();
 }
 
 void SaveManager::writeSaveGameHeader(Common::OutSaveFile *file, const Common::String &saveName, bool useSaveBuffer) {
 	file->writeUint32BE(SAVEGAME_ID);
-
 	// Write version
 	file->writeByte(SAVE_VERSION);
-
 	// Write savegame name
 	file->writeString(saveName);
 	file->writeByte(0);
-
 	// Save the game thumbnail
 	if (useSaveBuffer)
 		file->write(_tempThumbnail->getData(), _tempThumbnail->size());
 	else
 		Graphics::saveThumbnail(*file);
-
 	// Write out the save date/time
 	TimeDate td;
 	g_system->getTimeAndDate(td);
@@ -123,13 +106,11 @@ void SaveManager::writeSaveGameHeader(Common::OutSaveFile *file, const Common::S
 	file->writeSint16LE(td.tm_mday);
 	file->writeSint16LE(td.tm_hour);
 	file->writeSint16LE(td.tm_min);
-
 	file->writeUint32LE(g_engine->getTotalPlayTime() / 1000);
 }
 
 Common::Error SaveManager::loadGame(int slot) {
 	Common::SeekableReadStream *saveFile = NULL;
-
 	if (slot >= 0) {
 		saveFile = getSlotFile(slot);
 	} else {
@@ -140,26 +121,20 @@ Common::Error SaveManager::loadGame(int slot) {
 				delete restoreFile;
 				return Common::kPathDoesNotExist;
 			}
-
 			saveFile = restoreFile;
 		}
 	}
-
 	if (!saveFile)
 		return Common::kPathDoesNotExist;
-
 	// Read the header
 	SaveGameHeader header;
 	if (!readSaveGameHeader(saveFile, header)) {
 		return Common::kUnknownError;
 	}
-
 	ScriptManager *scriptManager = _engine->getScriptManager();
 	// Update the state table values
 	scriptManager->deserialize(saveFile);
-
 	delete saveFile;
-
 	if (_engine->getGameId() == GID_NEMESIS && scriptManager->getCurrentLocation() == "tv2f") {
 		// WORKAROUND for script bug #6793: location tv2f (stairs) has two states:
 		// one at the top of the stairs, and one at the bottom. When the player
@@ -180,9 +155,7 @@ Common::Error SaveManager::loadGame(int slot) {
 			scriptManager->unsetStateFlag(4652, Puzzle::DISABLED);
 		}
 	}
-
 	g_engine->setTotalPlayTime(header.playTime * 1000);
-
 	return Common::kNoError;
 }
 
@@ -246,7 +219,6 @@ bool SaveManager::readSaveGameHeader(Common::InSaveFile *in, SaveGameHeader &hea
 	if (header.version >= 2) {
 		header.playTime  = in->readUint32LE();
 	}
-
 	return true;
 }
 
@@ -259,7 +231,6 @@ Common::SeekableReadStream *SaveManager::getSlotFile(uint slot) {
 			filename = Common::Path(Common::String::format("inqsav%u.sav", slot));
 		else if (_engine->getGameId() == GID_NEMESIS)
 			filename = Common::Path(Common::String::format("nemsav%u.sav", slot));
-
 		saveFile = _engine->getSearchManager()->openFile(filename);
 		if (saveFile == NULL) {
 			Common::File *tmpFile = new Common::File;
@@ -269,9 +240,7 @@ Common::SeekableReadStream *SaveManager::getSlotFile(uint slot) {
 				saveFile = tmpFile;
 			}
 		}
-
 	}
-
 	return saveFile;
 }
 
@@ -279,7 +248,6 @@ void SaveManager::prepareSaveBuffer() {
 	delete _tempThumbnail;
 	_tempThumbnail = new Common::MemoryWriteStreamDynamic(DisposeAfterUse::YES);
 	Graphics::saveThumbnail(*_tempThumbnail);
-
 	delete _tempSave;
 	_tempSave = new Common::MemoryWriteStreamDynamic(DisposeAfterUse::YES);
 	_engine->getScriptManager()->serialize(_tempSave);
@@ -288,7 +256,6 @@ void SaveManager::prepareSaveBuffer() {
 void SaveManager::flushSaveBuffer() {
 	delete _tempThumbnail;
 	_tempThumbnail = NULL;
-
 	delete _tempSave;
 	_tempSave = NULL;
 }
diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index d80c86623e0..aff8d0b3851 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -177,19 +177,15 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
 	  Graphics::Surface *out = &_warpedSceneSurface;
 	  Graphics::Surface *in = &_backgroundSurface;
 	  Common::Rect outWndDirtyRect;
-
 	  //Apply graphical effects to temporary effects buffer and/or directly to current background image, as appropriate
 	  if (!_effects.empty()) {
 		  bool copied = false;
 		  const Common::Rect windowRect(_workingArea.width(), _workingArea.height());
-
 		  for (EffectsList::iterator it = _effects.begin(); it != _effects.end(); it++) {
 			  Common::Rect rect = (*it)->getRegion();
 			  Common::Rect screenSpaceLocation = rect;
-
 			  if ((*it)->isPort())
 				  screenSpaceLocation = transformBackgroundSpaceRectToScreenSpace(screenSpaceLocation);
-
 			  if (windowRect.intersects(screenSpaceLocation)) {
 				  if (!copied) {
 					  copied = true;
@@ -205,41 +201,39 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
 				  blitSurfaceToSurface(*post, empty, _effectSurface, screenSpaceLocation.left, screenSpaceLocation.top);
 				  debug(1,"windowRect %d,%d,%d,%d, screenSpaceLocation %d,%d,%d,%d", windowRect.left, windowRect.top, windowRect.bottom, windowRect.right, screenSpaceLocation.left, screenSpaceLocation.top, screenSpaceLocation.bottom, screenSpaceLocation.right);
 				  screenSpaceLocation.clip(windowRect);
-				  if (_backgroundSurfaceDirtyRect .isEmpty()) {
+				  if (_backgroundSurfaceDirtyRect .isEmpty())
 					  _backgroundSurfaceDirtyRect = screenSpaceLocation;
-				  } else {
+				  else
 					  _backgroundSurfaceDirtyRect.extend(screenSpaceLocation);
-				  }
 			  }
 		  }
 	  }
-
     //Apply panorama/tilt warp to background image
-	  RenderTable::RenderState state = _renderTable.getRenderState();
-	  if (state == RenderTable::PANORAMA || state == RenderTable::TILT) {
-		  if (!_backgroundSurfaceDirtyRect.isEmpty()) {
-			  _renderTable.mutateImage(&_warpedSceneSurface, in);
-			  out = &_warpedSceneSurface;
-			  outWndDirtyRect = Common::Rect(_workingArea.width(), _workingArea.height());
-		  }
-	  } 
-	  else {
-		  out = in;
-		  outWndDirtyRect = _backgroundSurfaceDirtyRect;
-	  }	  
+	  switch(_renderTable.getRenderState()) {
+	    case RenderTable::PANORAMA:
+	    case RenderTable::TILT:
+		    if (!_backgroundSurfaceDirtyRect.isEmpty()) {
+			    _renderTable.mutateImage(&_warpedSceneSurface, in);
+			    out = &_warpedSceneSurface;
+			    outWndDirtyRect = Common::Rect(_workingArea.width(), _workingArea.height());
+		    }
+	      break;
+	    default:
+		    out = in;
+		    outWndDirtyRect = _backgroundSurfaceDirtyRect;
+		    break;
+    }
 	  _workingManagedSurface.simpleBlitFrom(*out); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
 	}
-	
 	_menuManagedSurface.transBlitFrom(_menuSurface, -1);
   _textManagedSurface.transBlitFrom(_textSurface, -1);
-
   if(_engine->canRender() || immediate) {
     _screen.update();
     debug(10,"~renderSceneToScreen");
     return true;
   }
   else {
-    debug(1,"Skipping screen update; engine forbids rendering at this time.");
+    debug(4,"Skipping screen update; engine forbids rendering at this time.");
     debug(10,"~renderSceneToScreen");
     return false;
   }
@@ -247,7 +241,7 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
 
 Graphics::ManagedSurface &RenderManager::getVidSurface(Common::Rect &dstRect) {
   Common::Rect _dstRect = dstRect;
-  _dstRect.translate(_workingArea.left, _workingArea.top);  //Error here??
+  _dstRect.translate(_workingArea.left, _workingArea.top);  //Convert to working area coordinates
 	_vidManagedSurface.create(_screen, _dstRect);
 	debug(1,"Obtaining managed video surface at %d,%d,%d,%d", _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
 	return _vidManagedSurface;
@@ -270,9 +264,7 @@ void RenderManager::renderImageToBackground(const Common::Path &fileName, int16
 void RenderManager::renderImageToBackground(const Common::Path &fileName, int16 destX, int16 destY, int16  keyX, int16 keyY) {
 	Graphics::Surface surface;
 	readImageToSurface(fileName, surface);
-
 	uint16 keycolor = *(uint16 *)surface.getBasePtr(keyX, keyY);
-
 	blitSurfaceToBkg(surface, destX, destY, keycolor);
 	surface.free();
 }
@@ -284,29 +276,23 @@ void RenderManager::readImageToSurface(const Common::Path &fileName, Graphics::S
 
 void RenderManager::readImageToSurface(const Common::Path &fileName, Graphics::Surface &destination, bool transposed) {
 	Common::File file;
-
 	if (!_engine->getSearchManager()->openFile(file, fileName)) {
 		warning("Could not open file %s", fileName.toString().c_str());
 		return;
 	}
-
 	// Read the magic number
 	// Some files are true TGA, while others are TGZ
 	uint32 fileType = file.readUint32BE();
-
 	int imageWidth;
 	int imageHeight;
 	Image::TGADecoder tga;
 	uint16 *buffer;
 	// All Z-Vision images are in RGB 555
 	destination.format = _engine->_resourcePixelFormat;
-
 	bool isTGZ;
-
 	// Check for TGZ files
 	if (fileType == MKTAG('T', 'G', 'Z', '\0')) {
 		isTGZ = true;
-
 		// TGZ files have a header and then Bitmap data that is compressed with LZSS
 		uint32 decompressedSize = file.readSint32LE() / 2;
 		imageWidth = file.readSint32LE();
@@ -319,64 +305,53 @@ void RenderManager::readImageToSurface(const Common::Path &fileName, Graphics::S
 		for (uint32 i = 0; i < decompressedSize; ++i)
 			buffer[i] = FROM_LE_16(buffer[i]);
 #endif
-	} else {
+	} 
+	else {
 		isTGZ = false;
-
 		// Reset the cursor
 		file.seek(0);
-
 		// Decode
 		if (!tga.loadStream(file)) {
 			warning("Error while reading TGA image");
 			return;
 		}
-
 		Graphics::Surface tgaSurface = *(tga.getSurface());
 		imageWidth = tgaSurface.w;
 		imageHeight = tgaSurface.h;
-
 		buffer = (uint16 *)tgaSurface.getPixels();
 	}
 
 	// Flip the width and height if transposed
-	if (transposed) {
+	if (transposed)
 		SWAP(imageWidth, imageHeight);
-	}
-
 	// If the destination internal buffer is the same size as what we're copying into it,
 	// there is no need to free() and re-create
-	if (imageWidth != destination.w || imageHeight != destination.h) {
+	if (imageWidth != destination.w || imageHeight != destination.h)
 		destination.create(imageWidth, imageHeight, _engine->_resourcePixelFormat);
-	}
-
 	// If transposed, 'un-transpose' the data while copying it to the destination
 	// Otherwise, just do a simple copy
 	if (transposed) {
 		uint16 *dest = (uint16 *)destination.getPixels();
-
 		for (int y = 0; y < imageHeight; ++y) {
 			uint32 columnIndex = y * imageWidth;
-
 			for (int x = 0; x < imageWidth; ++x) {
 				dest[columnIndex + x] = buffer[x * imageHeight + y];
 			}
 		}
-	} else {
+	} 
+	else
 		memcpy(destination.getPixels(), buffer, imageWidth * imageHeight * destination.format.bytesPerPixel);
-	}
-
 	// Cleanup
-	if (isTGZ) {
+	if (isTGZ)
 		delete[] buffer;
-	} else {
+  else
 		tga.destroy();
-	}
 }
 
 const Common::Point RenderManager::screenSpaceToImageSpace(const Common::Point &point) {
   debug(9,"screenSpaceToImageSpace()");
 	if (_workingArea.contains(point)) {
-		// Convert from screen space to working window space
+		// Convert from screen space to working image space, i.e. panoramic background image or static image
 		Common::Point newPoint(point - _workingArea.origin());
 		switch(_renderTable.getRenderState()) {
 		  case RenderTable::PANORAMA:
@@ -400,7 +375,8 @@ const Common::Point RenderManager::screenSpaceToImageSpace(const Common::Point &
 			newPoint.y += _backgroundHeight;
     debug(9,"~screenSpaceToImageSpace()");
 		return newPoint;
-	} else {
+	} 
+	else {
     debug(9,"~screenSpaceToImageSpace()");
 		return Common::Point(0, 0);
 	}
@@ -428,7 +404,7 @@ void RenderManager::setBackgroundPosition(int offset) {
 	    break;
 	}
  	_backgroundOffset = offset;
-	_engine->getScriptManager()->setStateValue(StateKey_ViewPos, offset); 
+	_engine->getScriptManager()->setStateValue(StateKey_ViewPos, offset);
 }
 
 uint32 RenderManager::getCurrentBackgroundOffset() {
@@ -444,25 +420,20 @@ uint32 RenderManager::getCurrentBackgroundOffset() {
 Graphics::Surface *RenderManager::tranposeSurface(const Graphics::Surface *surface) {
 	Graphics::Surface *tranposedSurface = new Graphics::Surface();
 	tranposedSurface->create(surface->h, surface->w, surface->format);
-
 	const uint16 *source = (const uint16 *)surface->getPixels();
 	uint16 *dest = (uint16 *)tranposedSurface->getPixels();
-
 	for (int y = 0; y < tranposedSurface->h; ++y) {
 		int columnIndex = y * tranposedSurface->w;
-		for (int x = 0; x < tranposedSurface->w; ++x) {
+		for (int x = 0; x < tranposedSurface->w; ++x)
 			dest[columnIndex + x] = source[x * surface->w + y];
-		}
 	}
 	return tranposedSurface;
 }
 
 void RenderManager::scaleBuffer(const void *src, void *dst, uint32 srcWidth, uint32 srcHeight, byte bytesPerPixel, uint32 dstWidth, uint32 dstHeight) {
 	assert(bytesPerPixel == 1 || bytesPerPixel == 2);
-
 	const float  xscale = (float)srcWidth / (float)dstWidth;
 	const float  yscale = (float)srcHeight / (float)dstHeight;
-
 	if (bytesPerPixel == 1) {
 		const byte *srcPtr = (const byte *)src;
 		byte *dstPtr = (byte *)dst;
@@ -472,7 +443,8 @@ void RenderManager::scaleBuffer(const void *src, void *dst, uint32 srcWidth, uin
 				dstPtr++;
 			}
 		}
-	} else if (bytesPerPixel == 2) {
+	} 
+	else if (bytesPerPixel == 2) {
 		const uint16 *srcPtr = (const uint16 *)src;
 		uint16 *dstPtr = (uint16 *)dst;
 		for (uint32 y = 0; y < dstHeight; ++y) {
@@ -623,10 +595,9 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Com
 		yy = 0;
 
 	if (_x < dst.w && _y < dst.h) {
-	byte *dstBuffer = (byte *)dst.getBasePtr(xx, yy);
-  Graphics::keyBlit(dstBuffer,srcBuffer,dst.pitch,srcAdapted->pitch,srcRect.width(),srcRect.height(),srcAdapted->format.bytesPerPixel,keycolor);
+	  byte *dstBuffer = (byte *)dst.getBasePtr(xx, yy);
+    Graphics::keyBlit(dstBuffer,srcBuffer,dst.pitch,srcAdapted->pitch,srcRect.width(),srcRect.height(),srcAdapted->format.bytesPerPixel,keycolor);
   }
-  
 	srcAdapted->free();
 	delete srcAdapted;
 }
@@ -646,9 +617,9 @@ void RenderManager::blitSurfaceToBkg(const Graphics::Surface &src, int x, int y,
 }
 
 void RenderManager::blitSurfaceToBkgScaled(const Graphics::Surface &src, const Common::Rect &_dstRect, int32 colorkey) {
-	if (src.w == _dstRect.width() && src.h == _dstRect.height()) {
+	if (src.w == _dstRect.width() && src.h == _dstRect.height())
 		blitSurfaceToBkg(src, _dstRect.left, _dstRect.top, colorkey);
-	} else {
+	else {
 		Graphics::Surface *tmp = new Graphics::Surface;
 		tmp->create(_dstRect.width(), _dstRect.height(), src.format);
 		scaleBuffer(src.getPixels(), tmp->getPixels(), src.w, src.h, src.format.bytesPerPixel, _dstRect.width(), _dstRect.height());
@@ -716,15 +687,11 @@ Graphics::Surface *RenderManager::getBkgRect(Common::Rect &rect) {
   debug(11,"getBkgRect()");
 	Common::Rect dst = rect;
 	dst.clip(_backgroundWidth, _backgroundHeight);
-
 	if (dst.isEmpty() || !dst.isValidRect())
 		return NULL;
-
 	Graphics::Surface *srf = new Graphics::Surface;
 	srf->create(dst.width(), dst.height(), _currentBackgroundImage.format);
-
 	srf->copyRectToSurface(_currentBackgroundImage, 0, 0, Common::Rect(dst));
-
 	return srf;
 }
 
@@ -743,77 +710,76 @@ Graphics::Surface *RenderManager::loadImage(const Common::Path &file, bool trans
 void RenderManager::prepareBackground() {
   debug(11,"prepareBackground()");
 	_backgroundDirtyRect.clip(_backgroundWidth, _backgroundHeight);
-	RenderTable::RenderState state = _renderTable.getRenderState();
-
-	if (state == RenderTable::PANORAMA) {
-		// Calculate the visible portion of the background
-		Common::Rect viewPort(_workingArea.width(), _workingArea.height());
-		viewPort.translate(-(_workingAreaCenter.x - _backgroundOffset), 0);
-		Common::Rect drawRect = _backgroundDirtyRect;
-		drawRect.clip(viewPort);
-
-		// Render the visible portion
-		if (!drawRect.isEmpty()) {
-			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _workingAreaCenter.x - _backgroundOffset + drawRect.left, drawRect.top);
-		}
-
-		// Mark the dirty portion of the surface
-		_backgroundSurfaceDirtyRect = _backgroundDirtyRect;
-		_backgroundSurfaceDirtyRect.translate(_workingAreaCenter.x - _backgroundOffset, 0);
-
-		// Panorama mode allows the user to spin in circles. Therefore, we need to render
-		// the portion of the image that wrapped to the other side of the screen
-		if (_backgroundOffset < _workingAreaCenter.x) {
-			viewPort.moveTo(-(_workingAreaCenter.x - (_backgroundOffset + _backgroundWidth)), 0);
-			drawRect = _backgroundDirtyRect;
-			drawRect.clip(viewPort);
-
-			if (!drawRect.isEmpty())
-				blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _workingAreaCenter.x - (_backgroundOffset + _backgroundWidth) + drawRect.left, drawRect.top);
-
-			Common::Rect tmp = _backgroundDirtyRect;
-			tmp.translate(_workingAreaCenter.x - (_backgroundOffset + _backgroundWidth), 0);
-			if (!tmp.isEmpty())
-				_backgroundSurfaceDirtyRect.extend(tmp);
-
-		} else if (_backgroundWidth - _backgroundOffset < _workingAreaCenter.x) {
-			viewPort.moveTo(-(_workingAreaCenter.x + _backgroundWidth - _backgroundOffset), 0);
-			drawRect = _backgroundDirtyRect;
-			drawRect.clip(viewPort);
-
-			if (!drawRect.isEmpty())
-				blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _workingAreaCenter.x + _backgroundWidth - _backgroundOffset + drawRect.left, drawRect.top);
-
-			Common::Rect tmp = _backgroundDirtyRect;
-			tmp.translate(_workingAreaCenter.x + _backgroundWidth - _backgroundOffset, 0);
-			if (!tmp.isEmpty())
-				_backgroundSurfaceDirtyRect.extend(tmp);
-
-		}
-	} else if (state == RenderTable::TILT) {
-		// Tilt doesn't allow wrapping, so we just do a simple clip
-		Common::Rect viewPort(_workingArea.width(), _workingArea.height());
-		viewPort.translate(0, -(_workingAreaCenter.y - _backgroundOffset));
-		Common::Rect drawRect = _backgroundDirtyRect;
-		drawRect.clip(viewPort);
-		if (!drawRect.isEmpty())
-			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, drawRect.left, _workingAreaCenter.y - _backgroundOffset + drawRect.top);
-
-		// Mark the dirty portion of the surface
-		_backgroundSurfaceDirtyRect = _backgroundDirtyRect;
-		_backgroundSurfaceDirtyRect.translate(0, _workingAreaCenter.y - _backgroundOffset);
-
-	} else {
-		if (!_backgroundDirtyRect.isEmpty())
-			blitSurfaceToSurface(_currentBackgroundImage, _backgroundDirtyRect, _backgroundSurface, _backgroundDirtyRect.left, _backgroundDirtyRect.top);
-		_backgroundSurfaceDirtyRect = _backgroundDirtyRect;
+  switch(_renderTable.getRenderState()) {
+	  case RenderTable::PANORAMA: {
+		  // Calculate the visible portion of the background
+		  Common::Rect viewPort(_workingArea.width(), _workingArea.height());
+		  viewPort.translate(-(_workingAreaCenter.x - _backgroundOffset), 0);
+		  Common::Rect drawRect = _backgroundDirtyRect;
+		  drawRect.clip(viewPort);
+
+		  // Render the visible portion
+		  if (!drawRect.isEmpty())
+			  blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _workingAreaCenter.x - _backgroundOffset + drawRect.left, drawRect.top);
+
+		  // Mark the dirty portion of the surface
+		  _backgroundSurfaceDirtyRect = _backgroundDirtyRect;
+		  _backgroundSurfaceDirtyRect.translate(_workingAreaCenter.x - _backgroundOffset, 0);
+
+		  // Panorama mode allows the user to spin in circles. Therefore, we need to render
+		  // the portion of the image that wrapped to the other side of the screen
+		  if (_backgroundOffset < _workingAreaCenter.x) {
+			  viewPort.moveTo(-(_workingAreaCenter.x - (_backgroundOffset + _backgroundWidth)), 0);
+			  drawRect = _backgroundDirtyRect;
+			  drawRect.clip(viewPort);
+
+			  if (!drawRect.isEmpty())
+				  blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _workingAreaCenter.x - (_backgroundOffset + _backgroundWidth) + drawRect.left, drawRect.top);
+
+			  Common::Rect tmp = _backgroundDirtyRect;
+			  tmp.translate(_workingAreaCenter.x - (_backgroundOffset + _backgroundWidth), 0);
+			  if (!tmp.isEmpty())
+				  _backgroundSurfaceDirtyRect.extend(tmp);
+
+		  } 
+		  else if (_backgroundWidth - _backgroundOffset < _workingAreaCenter.x) {
+			  viewPort.moveTo(-(_workingAreaCenter.x + _backgroundWidth - _backgroundOffset), 0);
+			  drawRect = _backgroundDirtyRect;
+			  drawRect.clip(viewPort);
+
+			  if (!drawRect.isEmpty())
+				  blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _workingAreaCenter.x + _backgroundWidth - _backgroundOffset + drawRect.left, drawRect.top);
+
+			  Common::Rect tmp = _backgroundDirtyRect;
+			  tmp.translate(_workingAreaCenter.x + _backgroundWidth - _backgroundOffset, 0);
+			  if (!tmp.isEmpty())
+				  _backgroundSurfaceDirtyRect.extend(tmp);
+		  }
+	    break;
+	  }
+	  case RenderTable::TILT: {
+		  // Tilt doesn't allow wrapping, so we just do a simple clip
+		  Common::Rect viewPort(_workingArea.width(), _workingArea.height());
+		  viewPort.translate(0, -(_workingAreaCenter.y - _backgroundOffset));
+		  Common::Rect drawRect = _backgroundDirtyRect;
+		  drawRect.clip(viewPort);
+		  if (!drawRect.isEmpty())
+			  blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, drawRect.left, _workingAreaCenter.y - _backgroundOffset + drawRect.top);
+		  // Mark the dirty portion of the surface
+		  _backgroundSurfaceDirtyRect = _backgroundDirtyRect;
+		  _backgroundSurfaceDirtyRect.translate(0, _workingAreaCenter.y - _backgroundOffset);
+		  break;
+	  } 
+	  default: {
+		  if (!_backgroundDirtyRect.isEmpty())
+			  blitSurfaceToSurface(_currentBackgroundImage, _backgroundDirtyRect, _backgroundSurface, _backgroundDirtyRect.left, _backgroundDirtyRect.top);
+		  _backgroundSurfaceDirtyRect = _backgroundDirtyRect;
+		  break;
+	  }
 	}
-
 	// Clear the dirty rect since everything is clean now
 	_backgroundDirtyRect = Common::Rect();
-
 	_backgroundSurfaceDirtyRect.clip(_workingArea.width(), _workingArea.height());
-	
   debug(11,"~prepareBackground()");
 }
 
@@ -837,38 +803,40 @@ void RenderManager::deleteEffect(uint32 ID) {
 Common::Rect RenderManager::transformBackgroundSpaceRectToScreenSpace(const Common::Rect &src) {
   debug(10,"transformBackgroundSpaceRectToScreenSpace");
 	Common::Rect tmp = src;
-	RenderTable::RenderState state = _renderTable.getRenderState();
-
-	if (state == RenderTable::PANORAMA) {
-		if (_backgroundOffset < _workingAreaCenter.x) {
-			Common::Rect rScreen(_workingAreaCenter.x + _backgroundOffset, _workingArea.height());
-			Common::Rect lScreen(_workingArea.width() - rScreen.width(), _workingArea.height());
-			lScreen.translate(_backgroundWidth - lScreen.width(), 0);
-			lScreen.clip(src);
-			rScreen.clip(src);
-			if (rScreen.width() < lScreen.width()) {
-				tmp.translate(_workingAreaCenter.x - _backgroundOffset - _backgroundWidth, 0);
-			} else {
-				tmp.translate(_workingAreaCenter.x - _backgroundOffset, 0);
-			}
-		} else if (_backgroundWidth - _backgroundOffset < _workingAreaCenter.x) {
-			Common::Rect rScreen(_workingAreaCenter.x - (_backgroundWidth - _backgroundOffset), _workingArea.height());
-			Common::Rect lScreen(_workingArea.width() - rScreen.width(), _workingArea.height());
-			lScreen.translate(_backgroundWidth - lScreen.width(), 0);
-			lScreen.clip(src);
-			rScreen.clip(src);
-			if (lScreen.width() < rScreen.width()) {
-				tmp.translate(_workingAreaCenter.x + (_backgroundWidth - _backgroundOffset), 0);
-			} else {
-				tmp.translate(_workingAreaCenter.x - _backgroundOffset, 0);
-			}
-		} else {
-			tmp.translate(_workingAreaCenter.x - _backgroundOffset, 0);
-		}
-	} else if (state == RenderTable::TILT) {
-		tmp.translate(0, (_workingAreaCenter.y - _backgroundOffset));
+  switch(_renderTable.getRenderState()) {
+	  case RenderTable::PANORAMA: {
+		  if (_backgroundOffset < _workingAreaCenter.x) {
+			  Common::Rect rScreen(_workingAreaCenter.x + _backgroundOffset, _workingArea.height());
+			  Common::Rect lScreen(_workingArea.width() - rScreen.width(), _workingArea.height());
+			  lScreen.translate(_backgroundWidth - lScreen.width(), 0);
+			  lScreen.clip(src);
+			  rScreen.clip(src);
+			  if (rScreen.width() < lScreen.width())
+				  tmp.translate(_workingAreaCenter.x - _backgroundOffset - _backgroundWidth, 0);
+			  else
+				  tmp.translate(_workingAreaCenter.x - _backgroundOffset, 0);
+		  } 
+		  else if (_backgroundWidth - _backgroundOffset < _workingAreaCenter.x) {
+			  Common::Rect rScreen(_workingAreaCenter.x - (_backgroundWidth - _backgroundOffset), _workingArea.height());
+			  Common::Rect lScreen(_workingArea.width() - rScreen.width(), _workingArea.height());
+			  lScreen.translate(_backgroundWidth - lScreen.width(), 0);
+			  lScreen.clip(src);
+			  rScreen.clip(src);
+			  if (lScreen.width() < rScreen.width())
+				  tmp.translate(_workingAreaCenter.x + (_backgroundWidth - _backgroundOffset), 0);
+			  else
+				  tmp.translate(_workingAreaCenter.x - _backgroundOffset, 0);
+		  } 
+		  else
+			  tmp.translate(_workingAreaCenter.x - _backgroundOffset, 0);
+	    break;
+	  }
+    case RenderTable::TILT:
+		  tmp.translate(0, (_workingAreaCenter.y - _backgroundOffset));
+		  break;
+	  default:
+	    break;
 	}
-
 	return tmp;
 }
 
@@ -876,10 +844,8 @@ EffectMap *RenderManager::makeEffectMap(const Common::Point &xy, int16 depth, co
 	Common::Rect bkgRect(_backgroundWidth, _backgroundHeight);
 	if (!bkgRect.contains(xy))
 		return NULL;
-
 	if (!bkgRect.intersects(rect))
 		return NULL;
-
 	uint16 color = *(uint16 *)_currentBackgroundImage.getBasePtr(xy.x, xy.y);
 	uint8 stC1, stC2, stC3;
 	_currentBackgroundImage.format.colorToRGB(color, stC1, stC2, stC3);
@@ -915,18 +881,17 @@ EffectMap *RenderManager::makeEffectMap(const Common::Point &xy, int16 depth, co
 				        (cC2 - stC2 < depth8) &&
 				        (cC3 - stC3 < depth8))
 					use = true;
-			} else { /* if (curClr < color) */
+			} 
+			else { /* if (curClr < color) */
 				if ((stC1 - cC1 < depth8) &&
 				        (stC2 - cC2 < depth8) &&
 				        (stC3 - cC3 < depth8))
 					use = true;
 			}
-
 			if (first) {
 				unit.inEffect = use;
 				first = false;
 			}
-
 			if (use) {
 				uint8 cMinComp = MIN(MIN(cC1, cC2), cC3);
 				uint8 cMaxComp = MAX(MAX(cC1, cC2), cC3);
@@ -935,7 +900,6 @@ EffectMap *RenderManager::makeEffectMap(const Common::Point &xy, int16 depth, co
 				if (cMaxComp > maxComp)
 					maxComp = cMaxComp;
 			}
-
 			if (unit.inEffect == use)
 				unit.count++;
 			else {
@@ -946,7 +910,6 @@ EffectMap *RenderManager::makeEffectMap(const Common::Point &xy, int16 depth, co
 		}
 	}
 	newMap->push_back(unit);
-
 	if (_minComp) {
 		if (minComp - depth8 < 0)
 			*_minComp = -(minComp >> 3);
@@ -959,7 +922,6 @@ EffectMap *RenderManager::makeEffectMap(const Common::Point &xy, int16 depth, co
 		else
 			*_maxComp = depth;
 	}
-
 	return newMap;
 }
 
@@ -967,26 +929,20 @@ EffectMap *RenderManager::makeEffectMap(const Graphics::Surface &surf, uint16 tr
 	EffectMapUnit unit;
 	unit.count = 0;
 	unit.inEffect = false;
-
 	int16 w = surf.w;
 	int16 h = surf.h;
-
 	EffectMap *newMap = new EffectMap;
-
 	bool first = true;
-
 	for (int16 j = 0; j < h; j++) {
 		const uint16 *pix = (const uint16 *)surf.getBasePtr(0, j);
 		for (int16 i = 0; i < w; i++) {
 			bool use = false;
 			if (pix[i] != transp)
 				use = true;
-
 			if (first) {
 				unit.inEffect = use;
 				first = false;
 			}
-
 			if (unit.inEffect == use)
 				unit.count++;
 			else {
@@ -997,7 +953,6 @@ EffectMap *RenderManager::makeEffectMap(const Graphics::Surface &surf, uint16 tr
 		}
 	}
 	newMap->push_back(unit);
-
 	return newMap;
 }
 
@@ -1015,133 +970,114 @@ void RenderManager::bkgFill(uint8 r, uint8 g, uint8 b) {
 void RenderManager::updateRotation() {
 	int16 _velocity = _engine->getMouseVelocity() + _engine->getKeyboardVelocity();
 	ScriptManager *scriptManager = _engine->getScriptManager();
-
 	if (_doubleFPS)
 		_velocity /= 2;
-
 	if (_velocity) {
-		RenderTable::RenderState renderState = _renderTable.getRenderState();
-		if (renderState == RenderTable::PANORAMA) {
-			int16 startPosition = scriptManager->getStateValue(StateKey_ViewPos);
-
-			int16 newPosition = startPosition + (_renderTable.getPanoramaReverse() ? -_velocity : _velocity);
-
-			int16 zeroPoint = _renderTable.getPanoramaZeroPoint();
-			if (startPosition >= zeroPoint && newPosition < zeroPoint)
-				scriptManager->setStateValue(StateKey_Rounds, scriptManager->getStateValue(StateKey_Rounds) - 1);
-			if (startPosition <= zeroPoint && newPosition > zeroPoint)
-				scriptManager->setStateValue(StateKey_Rounds, scriptManager->getStateValue(StateKey_Rounds) + 1);
-
-			int16 screenWidth = getBkgSize().x;
-			if (screenWidth)
-				newPosition %= screenWidth;
-
-			if (newPosition < 0)
-				newPosition += screenWidth;
-
-			setBackgroundPosition(newPosition);
-		} else if (renderState == RenderTable::TILT) {
-			int16 startPosition = scriptManager->getStateValue(StateKey_ViewPos);
-
-			int16 newPosition = startPosition + _velocity;
-
-			int16 screenHeight = getBkgSize().y;
-			int16 tiltGap = (int16)_renderTable.getTiltGap();
-
-			if (newPosition >= (screenHeight - tiltGap))
-				newPosition = screenHeight - tiltGap;
-			if (newPosition <= tiltGap)
-				newPosition = tiltGap;
-
-			setBackgroundPosition(newPosition);
+		switch(_renderTable.getRenderState()) {
+		  case RenderTable::PANORAMA : {
+  			int16 startPosition = scriptManager->getStateValue(StateKey_ViewPos);
+		    int16 newPosition = startPosition + (_renderTable.getPanoramaReverse() ? -_velocity : _velocity);
+		    int16 zeroPoint = _renderTable.getPanoramaZeroPoint();
+		    if (startPosition >= zeroPoint && newPosition < zeroPoint)
+			    scriptManager->setStateValue(StateKey_Rounds, scriptManager->getStateValue(StateKey_Rounds) - 1);
+		    if (startPosition <= zeroPoint && newPosition > zeroPoint)
+			    scriptManager->setStateValue(StateKey_Rounds, scriptManager->getStateValue(StateKey_Rounds) + 1);
+		    int16 screenWidth = getBkgSize().x;
+		    if (screenWidth)
+			    newPosition %= screenWidth;
+		    if (newPosition < 0)
+			    newPosition += screenWidth;
+		    setBackgroundPosition(newPosition);
+		    break;
+	    }
+	    case RenderTable::TILT : {
+  			int16 startPosition = scriptManager->getStateValue(StateKey_ViewPos);
+			  int16 newPosition = startPosition + _velocity;
+			  int16 screenHeight = getBkgSize().y;
+			  int16 tiltGap = (int16)_renderTable.getTiltGap();
+			  if (newPosition >= (screenHeight - tiltGap))
+				  newPosition = screenHeight - tiltGap;
+			  if (newPosition <= tiltGap)
+				  newPosition = tiltGap;
+			  setBackgroundPosition(newPosition);
+			  break;
+		  }
+		  default:
+		    break;
 		}
 	}
 }
 
 void RenderManager::checkBorders() {
-	RenderTable::RenderState renderState = _renderTable.getRenderState();
-	if (renderState == RenderTable::PANORAMA) {
-		int16 startPosition = _engine->getScriptManager()->getStateValue(StateKey_ViewPos);
-
-		int16 newPosition = startPosition;
-
-		int16 screenWidth = getBkgSize().x;
-
-		if (screenWidth)
-			newPosition %= screenWidth;
-
-		if (newPosition < 0)
-			newPosition += screenWidth;
-
-		if (startPosition != newPosition)
-			setBackgroundPosition(newPosition);
-	} else if (renderState == RenderTable::TILT) {
-		int16 startPosition = _engine->getScriptManager()->getStateValue(StateKey_ViewPos);
-
-		int16 newPosition = startPosition;
-
-		int16 screenHeight = getBkgSize().y;
-		int16 tiltGap = (int16)_renderTable.getTiltGap();
-
-		if (newPosition >= (screenHeight - tiltGap))
-			newPosition = screenHeight - tiltGap;
-		if (newPosition <= tiltGap)
-			newPosition = tiltGap;
-
-		if (startPosition != newPosition)
-			setBackgroundPosition(newPosition);
+	switch(_renderTable.getRenderState()) {
+	  case RenderTable::PANORAMA: {
+		  int16 startPosition = _engine->getScriptManager()->getStateValue(StateKey_ViewPos);
+		  int16 newPosition = startPosition;
+		  int16 screenWidth = getBkgSize().x;
+		  if (screenWidth)
+			  newPosition %= screenWidth;
+		  if (newPosition < 0)
+			  newPosition += screenWidth;
+		  if (startPosition != newPosition)
+			  setBackgroundPosition(newPosition);
+	    break;
+	  } 
+	  case RenderTable::TILT: {
+		  int16 startPosition = _engine->getScriptManager()->getStateValue(StateKey_ViewPos);
+		  int16 newPosition = startPosition;
+		  int16 screenHeight = getBkgSize().y;
+		  int16 tiltGap = (int16)_renderTable.getTiltGap();
+		  if (newPosition >= (screenHeight - tiltGap))
+			  newPosition = screenHeight - tiltGap;
+		  if (newPosition <= tiltGap)
+			  newPosition = tiltGap;
+		  if (startPosition != newPosition)
+			  setBackgroundPosition(newPosition);
+		  break;
+	  }
+	  default: 
+	    break;
 	}
 }
 
 void RenderManager::rotateTo(int16 _toPos, int16 _time) {
 	if (_renderTable.getRenderState() != RenderTable::PANORAMA)
 		return;
-
   debug(1,"Rotating panorama to %d", _toPos);
-
 	if (_time == 0)
 		_time = 1;
-
 	int32 maxX = getBkgSize().x;
 	int32 curX = getCurrentBackgroundOffset();
 	int32 dx = 0;
-
 	if (curX == _toPos)
 		return;
-
 	if (curX > _toPos) {
 		if (curX - _toPos > maxX / 2)
 			dx = (_toPos + (maxX - curX)) / _time;
 		else
 			dx = -(curX - _toPos) / _time;
-	} else {
+	} 
+	else {
 		if (_toPos - curX > maxX / 2)
 			dx = -((maxX - _toPos) + curX) / _time;
 		else
 			dx = (_toPos - curX) / _time;
 	}
-
 	_engine->stopClock();
-
 	for (int16 i = 0; i <= _time; i++) {
 		if (i == _time)
 			curX = _toPos;
 		else
 			curX += dx;
-
 		if (curX < 0)
 			curX = maxX - curX;
 		else if (curX >= maxX)
-			curX %= maxX;
-
+			curX %= maxX;	
 		setBackgroundPosition(curX);
-
 		prepareBackground();
 		renderSceneToScreen();
-
 		_system->delayMillis(500 / _time);
 	}
-
 	_engine->startClock();
 }
 
diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index 93cef5f7e9a..bcb86168e29 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -32,9 +32,7 @@ RenderTable::RenderTable(uint numColumns, uint numRows)
 	  _numColumns(numColumns),
 	  _renderState(FLAT) {
 	assert(numRows != 0 && numColumns != 0);
-
 	_internalBuffer = new Common::Point[numRows * numColumns];
-
 	memset(&_panoramaOptions, 0, sizeof(_panoramaOptions));
 	memset(&_tiltOptions, 0, sizeof(_tiltOptions));
 }
@@ -45,24 +43,23 @@ RenderTable::~RenderTable() {
 
 void RenderTable::setRenderState(RenderState newState) {
 	_renderState = newState;
-
 	switch (newState) {
-	case PANORAMA:
-		_panoramaOptions.fieldOfView = 27.0f;
-		_panoramaOptions.linearScale = 0.55f;
-		_panoramaOptions.reverse = false;
-		_panoramaOptions.zeroPoint = 0;
-		break;
-	case TILT:
-		_tiltOptions.fieldOfView = 27.0f;
-		_tiltOptions.linearScale = 0.65f;
-		_tiltOptions.reverse = false;
-		break;
-	case FLAT:
-		// Intentionally left empty
-		break;
-	default:
-		break;
+	  case PANORAMA:
+		  _panoramaOptions.fieldOfView = 27.0f;
+		  _panoramaOptions.linearScale = 0.55f;
+		  _panoramaOptions.reverse = false;
+		  _panoramaOptions.zeroPoint = 0;
+		  break;
+	  case TILT:
+		  _tiltOptions.fieldOfView = 27.0f;
+		  _tiltOptions.linearScale = 0.65f;
+		  _tiltOptions.reverse = false;
+		  break;
+	  case FLAT:
+		  // Intentionally left empty
+		  break;
+	  default:
+		  break;
 	}
 }
 
@@ -73,53 +70,40 @@ const Common::Point RenderTable::convertWarpedCoordToFlatCoord(const Common::Poi
 		int16 y = CLIP<int16>(point.y, 0, (int16)_numRows);
 		return Common::Point(x, y);
 	}
-
 	uint32 index = point.y * _numColumns + point.x;
-
 	Common::Point newPoint(point);
 	newPoint.x += _internalBuffer[index].x;
 	newPoint.y += _internalBuffer[index].y;
-
 	return newPoint;
 }
 
 void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 destWidth, const Common::Rect &subRect) {
 	uint32 destOffset = 0;
-
 	for (int16 y = subRect.top; y < subRect.bottom; ++y) {
 		uint32 sourceOffset = y * _numColumns;
-
 		for (int16 x = subRect.left; x < subRect.right; ++x) {
 			uint32 normalizedX = x - subRect.left;
 			uint32 index = sourceOffset + x;
-
 			// RenderTable only stores offsets from the original coordinates
 			uint32 sourceYIndex = y + _internalBuffer[index].y;
 			uint32 sourceXIndex = x + _internalBuffer[index].x;
-
 			destBuffer[destOffset + normalizedX] = sourceBuffer[sourceYIndex * _numColumns + sourceXIndex];
 		}
-
 		destOffset += destWidth;
 	}
 }
 
 void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf) {
 	uint32 destOffset = 0;
-
 	uint16 *sourceBuffer = (uint16 *)srcBuf->getPixels();
 	uint16 *destBuffer = (uint16 *)dstBuf->getPixels();
-
 	for (int16 y = 0; y < srcBuf->h; ++y) {
 		uint32 sourceOffset = y * _numColumns;
-
 		for (int16 x = 0; x < srcBuf->w; ++x) {
 			uint32 index = sourceOffset + x;
-
 			// RenderTable only stores offsets from the original coordinates
 			uint32 sourceYIndex = y + _internalBuffer[index].y;
 			uint32 sourceXIndex = x + _internalBuffer[index].x;
-
 			destBuffer[destOffset] = sourceBuffer[sourceYIndex * _numColumns + sourceXIndex];
 			destOffset++;
 		}
@@ -128,17 +112,17 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 
 void RenderTable::generateRenderTable() {
 	switch (_renderState) {
-	case ZVision::RenderTable::PANORAMA:
-		generatePanoramaLookupTable();
-		break;
-	case ZVision::RenderTable::TILT:
-		generateTiltLookupTable();
-		break;
-	case ZVision::RenderTable::FLAT:
-		// Intentionally left empty
-		break;
-	default:
-		break;
+	  case ZVision::RenderTable::PANORAMA:
+		  generatePanoramaLookupTable();
+		  break;
+	  case ZVision::RenderTable::TILT:
+		  generateTiltLookupTable();
+		  break;
+	  case ZVision::RenderTable::FLAT:
+		  // Intentionally left empty
+		  break;
+	  default:
+		  break;
 	}
 }
 
@@ -150,13 +134,10 @@ void RenderTable::generatePanoramaLookupTable() {
 			_internalBuffer[index].y = 0;
 		}
 	}
-
 	float halfWidth = (float)_numColumns / 2.0f;
 	float halfHeight = (float)_numRows / 2.0f;
-
 	float fovInRadians = Math::deg2rad<float>(_panoramaOptions.fieldOfView);
 	float cylinderRadius = halfHeight / tan(fovInRadians);
-
 	for (uint x = 0; x < _numColumns; ++x) {
 		// Add an offset of 0.01 to overcome zero tan/atan issue (vertical line on half of screen)
 		// Alpha represents the horizontal angle between the viewer at the center of a cylinder and x
@@ -185,13 +166,10 @@ void RenderTable::generatePanoramaLookupTable() {
 void RenderTable::generateTiltLookupTable() {
 	float halfWidth = (float)_numColumns / 2.0f;
 	float halfHeight = (float)_numRows / 2.0f;
-
 	float fovInRadians = Math::deg2rad<float>(_tiltOptions.fieldOfView);
 	float cylinderRadius = halfWidth / tan(fovInRadians);
 	_tiltOptions.gap = cylinderRadius * atan2((float)(halfHeight / cylinderRadius), 1.0f) * _tiltOptions.linearScale;
-
 	for (uint y = 0; y < _numRows; ++y) {
-
 		// Add an offset of 0.01 to overcome zero tan/atan issue (horizontal line on half of screen)
 		// Alpha represents the vertical angle between the viewer at the center of a cylinder and y
 		float alpha = atan(((float)y - halfHeight + 0.01f) / cylinderRadius);
@@ -219,13 +197,11 @@ void RenderTable::generateTiltLookupTable() {
 
 void RenderTable::setPanoramaFoV(float fov) {
 	assert(fov > 0.0f);
-
 	_panoramaOptions.fieldOfView = fov;
 }
 
 void RenderTable::setPanoramaScale(float scale) {
 	assert(scale > 0.0f);
-
 	_panoramaOptions.linearScale = scale;
 }
 
@@ -247,13 +223,11 @@ uint16 RenderTable::getPanoramaZeroPoint() {
 
 void RenderTable::setTiltFoV(float fov) {
 	assert(fov > 0.0f);
-
 	_tiltOptions.fieldOfView = fov;
 }
 
 void RenderTable::setTiltScale(float scale) {
 	assert(scale > 0.0f);
-
 	_tiltOptions.linearScale = scale;
 }
 
@@ -266,21 +240,25 @@ float RenderTable::getTiltGap() {
 }
 
 float RenderTable::getAngle() {
-	if (_renderState == TILT)
-		return _tiltOptions.fieldOfView;
-	else if (_renderState == PANORAMA)
-		return _panoramaOptions.fieldOfView;
-	else
-		return 1.0;
+	switch(_renderState) {
+	  case TILT:
+  		return _tiltOptions.fieldOfView;
+		case PANORAMA:
+		  return _panoramaOptions.fieldOfView;
+	  default:
+  		return 1.0;
+	}
 }
 
 float RenderTable::getLinscale() {
-	if (_renderState == TILT)
-		return _tiltOptions.linearScale;
-	else if (_renderState == PANORAMA)
-		return _panoramaOptions.linearScale;
-	else
-		return 1.0;
+	switch(_renderState) {
+	  case TILT:
+  		return _tiltOptions.linearScale;
+	  case PANORAMA:
+  		return _panoramaOptions.linearScale;
+	  default:
+  		return 1.0;
+	}
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index febfaaf7dd7..4814c714a8a 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -111,6 +111,7 @@ ActionAttenuate::ActionAttenuate(ZVision *engine, int32 slotKey, const Common::S
 }
 
 bool ActionAttenuate::execute() {
+  debug(2,"Executing Action: Attenuate");
 	ScriptingEffect *fx = _scriptManager->getSideFX(_key);
 	if (fx && fx->getType() == ScriptingEffect::SCRIPTING_EFFECT_AUDIO) {
 		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
@@ -157,27 +158,27 @@ ActionCrossfade::ActionCrossfade(ZVision *engine, int32 slotKey, const Common::S
 	sscanf(line.c_str(),
 	       "%u %u %d %d %d %d %d",
 	       &_keyOne, &_keyTwo, &_oneStartVolume, &_twoStartVolume, &_oneEndVolume, &_twoEndVolume, &_timeInMillis);
+  debug(2,"Created Action: CrossFade, slotKey %d", slotKey);
+  debug(2,"Crossfade script: %s", line.c_str());
 }
 
 bool ActionCrossfade::execute() {
+  debug(2,"Executing Action: CrossFade");
 	if (_keyOne) {
 		ScriptingEffect *fx = _scriptManager->getSideFX(_keyOne);
 		if (fx && fx->getType() == ScriptingEffect::SCRIPTING_EFFECT_AUDIO) {
 			MusicNodeBASE *mus = (MusicNodeBASE *)fx;
 			if (_oneStartVolume >= 0)
 				mus->setVolume((_oneStartVolume * 255) / 100);
-
 			mus->setFade(_timeInMillis, (_oneEndVolume * 255) / 100);
 		}
 	}
-
 	if (_keyTwo) {
 		ScriptingEffect *fx = _scriptManager->getSideFX(_keyTwo);
 		if (fx && fx->getType() == ScriptingEffect::SCRIPTING_EFFECT_AUDIO) {
 			MusicNodeBASE *mus = (MusicNodeBASE *)fx;
 			if (_twoStartVolume >= 0)
 				mus->setVolume((_twoStartVolume * 255) / 100);
-
 			mus->setFade(_timeInMillis, (_twoEndVolume * 255) / 100);
 		}
 	}
@@ -306,6 +307,7 @@ ActionDistort::~ActionDistort() {
 }
 
 bool ActionDistort::execute() {
+  debug(2,"Executing Action: Distort");
 	if (_scriptManager->getSideFX(_distSlot))
 		return true;
 
@@ -473,34 +475,39 @@ ActionMusic::ActionMusic(ZVision *engine, int32 slotKey, const Common::String &l
 	// Type 4 actions are MIDI commands, not files. These are only used by
 	// Zork: Nemesis, for the flute and piano puzzles (tj4e and ve6f, as well
 	// as vr)
-	if (type == 4) {
-		_midi = true;
-		int note;
-		int prog;
-		sscanf(line.c_str(), "%u %d %d %14s", &type, &prog, &note, volumeBuffer);
-		_volume = new ValueSlot(_scriptManager, volumeBuffer);
-		_note = note;
-		_prog = prog;
-	} else {
-		_midi = false;
-		_fileName = Common::String(fileNameBuffer);
-		_loop = loop == 1 ? true : false;
-		if (volumeBuffer[0] != '[' && atoi(volumeBuffer) > 100) {
-			// I thought I saw a case like this in Zork Nemesis, so
-			// let's guard against it.
-			warning("ActionMusic: Adjusting volume for %s from %s to 100", _fileName.toString().c_str(), volumeBuffer);
-			Common::strcpy_s(volumeBuffer, "100");
-		}
-		_volume = new ValueSlot(_scriptManager, volumeBuffer);
-	}
-
+	switch(type) {
+    case 4: {
+		  _midi = true;
+		  int note;
+		  int prog;
+		  sscanf(line.c_str(), "%u %d %d %14s", &type, &prog, &note, volumeBuffer);
+		  _volume = new ValueSlot(_scriptManager, volumeBuffer);
+		  _note = note;
+		  _prog = prog;
+		  break;
+	  }
+	  default: {
+		  _midi = false;
+		  _fileName = Common::String(fileNameBuffer);
+		  _loop = loop == 1 ? true : false;
+		  if (volumeBuffer[0] != '[' && atoi(volumeBuffer) > 100) {
+			  // I thought I saw a case like this in Zork Nemesis, so
+			  // let's guard against it.
+			  warning("ActionMusic: Adjusting volume for %s from %s to 100", _fileName.toString().c_str(), volumeBuffer);
+			  Common::strcpy_s(volumeBuffer, "100");
+		  }
+		  _volume = new ValueSlot(_scriptManager, volumeBuffer);
+		  break;
+	  }
+  }
 	// WORKAROUND for a script bug in Zork Nemesis, rooms mq70/mq80.
 	// Fixes an edge case where the player goes to the dark room with the grue
 	// without holding a torch, and then quickly runs away before the grue's
 	// sound effect finishes. Fixes script bug #6794.
 	if (engine->getGameId() == GID_NEMESIS && _slotKey == 14822 && _scriptManager->getStateValue(_slotKey) == 2)
 		_scriptManager->setStateValue(_slotKey, 0);
-
+  //debug(2,"Created Action: Music, slotKey %d, type %u, file %24s, note %u, volume %14s", _slotKey, type, fileNameBuffer);
+  debug(2,"Music script: %s", line.c_str());
 }
 
 ActionMusic::~ActionMusic() {
@@ -510,23 +517,20 @@ ActionMusic::~ActionMusic() {
 }
 
 bool ActionMusic::execute() {
+  debug(2,"Executing Action: Music, slotKey %d", _slotKey);
 	if (_scriptManager->getSideFX(_slotKey)) {
 		_scriptManager->killSideFx(_slotKey);
 		_scriptManager->setStateValue(_slotKey, 2);
 	}
-
 	uint volume = _volume->getValue();
-
 	if (_midi) {
 		_scriptManager->addSideFX(new MusicMidiNode(_engine, _slotKey, _prog, _note, volume));
 	} else {
 		if (!_engine->getSearchManager()->hasFile(_fileName))
 			return true;
-
 		// Volume in the script files is mapped to [0, 100], but the ScummVM mixer uses [0, 255]
 		_scriptManager->addSideFX(new MusicNode(_engine, _slotKey, _fileName, _loop, volume * 255 / 100));
 	}
-
 	return true;
 }
 
@@ -538,8 +542,8 @@ ActionPanTrack::ActionPanTrack(ZVision *engine, int32 slotKey, const Common::Str
 	ResultAction(engine, slotKey),
 	_pos(0),
 	_musicSlot(0) {
-
 	sscanf(line.c_str(), "%u %d", &_musicSlot, &_pos);
+  debug(2,"Created Action: PanTrack, musicSlot %u, pos %d", _musicSlot, _pos);
 }
 
 ActionPanTrack::~ActionPanTrack() {
@@ -547,11 +551,10 @@ ActionPanTrack::~ActionPanTrack() {
 }
 
 bool ActionPanTrack::execute() {
+  debug(2,"Executing Action: PanTrack, musicSlot %u, pos %d", _musicSlot, _pos);
 	if (_scriptManager->getSideFX(_slotKey))
 		return true;
-
 	_scriptManager->addSideFX(new PanTrackNode(_engine, _slotKey, _musicSlot, _pos));
-
 	return true;
 }
 
@@ -572,7 +575,6 @@ bool ActionPreferences::execute() {
 		_engine->saveSettings();
 	else
 		_engine->loadSettings();
-
 	return true;
 }
 
@@ -622,16 +624,13 @@ bool ActionPreloadAnimation::execute() {
 ActionUnloadAnimation::ActionUnloadAnimation(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
 	_key = 0;
-
 	sscanf(line.c_str(), "%u", &_key);
 }
 
 bool ActionUnloadAnimation::execute() {
 	AnimationEffect *nod = (AnimationEffect *)_scriptManager->getSideFX(_key);
-
 	if (nod && nod->getType() == ScriptingEffect::SCRIPTING_EFFECT_ANIM)
 		_scriptManager->deleteSideFx(_key);
-
 	return true;
 }
 
@@ -650,7 +649,6 @@ ActionPlayAnimation::ActionPlayAnimation(ZVision *engine, int32 slotKey, const C
 	_loopCount = 0;
 	_mask = 0;
 	_framerate = 0;
-
 	char fileName[25];
 
 	// The two %*u are always 0 and dont seem to have a use
@@ -663,7 +661,6 @@ ActionPlayAnimation::ActionPlayAnimation(ZVision *engine, int32 slotKey, const C
 	// color 0, which is used as a mask in some images
 	if (_mask == 0)
 		_mask = -1;
-
 	_fileName = Common::String(fileName);
 
 	// WORKAROUND for bug #6769, location me1g.scr (the "Alchemical debacle"
@@ -680,16 +677,14 @@ ActionPlayAnimation::~ActionPlayAnimation() {
 
 bool ActionPlayAnimation::execute() {
 	AnimationEffect *nod = (AnimationEffect *)_scriptManager->getSideFX(_slotKey);
-
 	if (!nod) {
 		nod = new AnimationEffect(_engine, _slotKey, _fileName, _mask, _framerate);
 		_scriptManager->addSideFX(nod);
-	} else
+	} 
+	else
 		nod->stop();
-
 	if (nod)
 		nod->addPlayNode(_slotKey, _x, _y, _x2, _y2, _start, _end, _loopCount);
-
 	return true;
 }
 
@@ -707,7 +702,6 @@ ActionPlayPreloadAnimation::ActionPlayPreloadAnimation(ZVision *engine, int32 sl
 	_startFrame = 0;
 	_endFrame = 0;
 	_loopCount = 0;
-
 	sscanf(line.c_str(),
 	       "%u %u %u %u %u %u %u %u",
 	       &_controlKey, &_x1, &_y1, &_x2, &_y2, &_startFrame, &_endFrame, &_loopCount);
@@ -715,10 +709,8 @@ ActionPlayPreloadAnimation::ActionPlayPreloadAnimation(ZVision *engine, int32 sl
 
 bool ActionPlayPreloadAnimation::execute() {
 	AnimationEffect *nod = (AnimationEffect *)_scriptManager->getSideFX(_controlKey);
-
 	if (nod)
 		nod->addPlayNode(_slotKey, _x1, _y1, _x2, _y2, _startFrame, _endFrame, _loopCount);
-
 	return true;
 }
 
@@ -728,7 +720,6 @@ bool ActionPlayPreloadAnimation::execute() {
 
 bool ActionQuit::execute() {
 	_engine->quitGame();
-
 	return true;
 }
 
@@ -742,12 +733,9 @@ ActionRegion::ActionRegion(ZVision *engine, int32 slotKey, const Common::String
 	_type = 0;
 	_unk1 = 0;
 	_unk2 = 0;
-
 	char art[64];
 	char custom[64];
-
 	int32 x1 = 0, x2 = 0, y1 = 0, y2 = 0;
-
 	sscanf(line.c_str(), "%s %d %d %d %d %hu %hu %hu %hu %s", art, &x1, &y1, &x2, &y2, &_delay, &_type, &_unk1, &_unk2, custom);
 	_art = Common::String(art);
 	_custom = Common::String(custom);
@@ -759,9 +747,9 @@ ActionRegion::~ActionRegion() {
 }
 
 bool ActionRegion::execute() {
+  debug(2,"Executing Action: Region");
 	if (_scriptManager->getSideFX(_slotKey))
 		return true;
-
 	GraphicsEffect *effect = NULL;
 	switch (_type) {
 	case 0: {
@@ -794,7 +782,6 @@ bool ActionRegion::execute() {
 			_rect.setWidth(tempMask.w);
 		if (_rect.height() != tempMask.h)
 			_rect.setHeight(tempMask.h);
-
 		EffectMap *_map = _engine->getRenderManager()->makeEffectMap(tempMask, 0);
 		effect = new FogFx(_engine, _slotKey, _rect, _unk1, _map, buf);
 		tempMask.free();
@@ -803,12 +790,10 @@ bool ActionRegion::execute() {
 	default:
 		break;
 	}
-
 	if (effect) {
 		_scriptManager->addSideFX(new RegionNode(_engine, _slotKey, effect, _delay));
 		_engine->getRenderManager()->addEffect(effect);
 	}
-
 	return true;
 }
 
@@ -858,13 +843,11 @@ ActionRotateTo::ActionRotateTo(ZVision *engine, int32 slotKey, const Common::Str
 	ResultAction(engine, slotKey) {
 	_time = 0;
 	_toPos = 0;
-
 	sscanf(line.c_str(), "%d, %d", &_toPos, &_time);
 }
 
 bool ActionRotateTo::execute() {
 	_engine->getRenderManager()->rotateTo(_toPos, _time);
-
 	return true;
 }
 
@@ -876,13 +859,9 @@ ActionSetPartialScreen::ActionSetPartialScreen(ZVision *engine, int32 slotKey, c
 	ResultAction(engine, slotKey) {
 	_x = 0;
 	_y = 0;
-
 	char fileName[25];
-
 	sscanf(line.c_str(), "%u %u %24s %*u %d", &_x, &_y, fileName, &_backgroundColor);
-
 	_fileName = Common::String(fileName);
-
 	if (_backgroundColor > 65535) {
 		warning("Background color for ActionSetPartialScreen is bigger than a uint16");
 	}
@@ -890,7 +869,6 @@ ActionSetPartialScreen::ActionSetPartialScreen(ZVision *engine, int32 slotKey, c
 
 bool ActionSetPartialScreen::execute() {
 	RenderManager *renderManager = _engine->getRenderManager();
-
 	if (_engine->getGameId() == GID_NEMESIS) {
 		if (_backgroundColor)
 			renderManager->renderImageToBackground(_fileName, _x, _y, 0, 0);
@@ -904,7 +882,6 @@ bool ActionSetPartialScreen::execute() {
 		else
 			renderManager->renderImageToBackground(_fileName, _x, _y);
 	}
-
 	return true;
 }
 
@@ -916,13 +893,11 @@ ActionSetScreen::ActionSetScreen(ZVision *engine, int32 slotKey, const Common::S
 	ResultAction(engine, slotKey) {
 	char fileName[25];
 	sscanf(line.c_str(), "%24s", fileName);
-
 	_fileName = Common::String(fileName);
 }
 
 bool ActionSetScreen::execute() {
 	_engine->getRenderManager()->setBackgroundImage(_fileName);
-
 	return true;
 }
 
@@ -937,6 +912,7 @@ ActionStop::ActionStop(ZVision *engine, int32 slotKey, const Common::String &lin
 }
 
 bool ActionStop::execute() {
+  debug(2,"Executing Action: Stop");
 	_scriptManager->stopSideFx(_key);
 	return true;
 }
@@ -952,12 +928,9 @@ ActionStreamVideo::ActionStreamVideo(ZVision *engine, int32 slotKey, const Commo
 	_y1 = 0;
 	_y2 = 0;
 	_flags = 0;
-
 	char fileName[25];
 	uint skipline = 0;    //skipline - render video with skip every second line, not skippable.
-
 	sscanf(line.c_str(), "%24s %u %u %u %u %u %u", fileName, &_x1, &_y1, &_x2, &_y2, &_flags, &skipline);
-
 	_fileName = Common::String(fileName);
 	_skippable = true;
 }
@@ -1005,7 +978,7 @@ bool ActionStreamVideo::execute() {
 	if (switchToHires) {
 		_engine->getRenderManager()->initialize(true);
     srcRect = Common::Rect(Common::Point(0,69),720, 344);
-		//ZGI hi-res video resolution = 720x480, with baked-in letterboxing around video at 720x344 resolution (at origin 0,69) conforming to playfield vertical resolution of 344
+		//ZGI hi-res video resolution = 720x480, with baked-in letterboxing around content at 720x344 (origin 0,69), interestingly conforming to playfield vertical resolution of 344
 		destRect = _engine->getRenderManager()->getWorkingArea(); //Game scripts only give destRect for normal resolution; we must manually override them for HD videos
 		destRect.moveTo(0,0);
 	}
@@ -1041,23 +1014,19 @@ bool ActionStreamVideo::execute() {
 ActionSyncSound::ActionSyncSound(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
 	_syncto = 0;
-
 	char fileName[25];
 	int notUsed = 0;
-
 	sscanf(line.c_str(), "%d %d %24s", &_syncto, &notUsed, fileName);
-
 	_fileName = Common::String(fileName);
 }
 
 bool ActionSyncSound::execute() {
+  debug(2,"Executing Action: SyncSound");
 	ScriptingEffect *fx = _scriptManager->getSideFX(_syncto);
 	if (!fx)
 		return true;
-
 	if (!(fx->getType() & ScriptingEffect::SCRIPTING_EFFECT_ANIM))
 		return true;
-
 	_scriptManager->addSideFX(new SyncSoundNode(_engine, _slotKey, _fileName, _syncto));
 	return true;
 }
diff --git a/engines/zvision/scripting/actions.h b/engines/zvision/scripting/actions.h
index 343c17620ec..4b552d23310 100644
--- a/engines/zvision/scripting/actions.h
+++ b/engines/zvision/scripting/actions.h
@@ -239,7 +239,7 @@ public:
 	bool execute() override;
 
 private:
-	int32 _pos;
+	int32 _pos; //Sound source position in panorama
 	uint32 _musicSlot;
 };
 
diff --git a/engines/zvision/scripting/control.cpp b/engines/zvision/scripting/control.cpp
index 12f126027f9..6db933df450 100644
--- a/engines/zvision/scripting/control.cpp
+++ b/engines/zvision/scripting/control.cpp
@@ -63,11 +63,9 @@ void Control::parsePanoramaControl(ZVision *engine, Common::SeekableReadStream &
 			sscanf(line.c_str(), "zeropoint(%u)", &point);
 			renderTable->setPanoramaZeroPoint(point);
 		}
-
 		line = stream.readLine();
 		engine->getScriptManager()->trimCommentsAndWhiteSpace(&line);
 	}
-
 	renderTable->generateRenderTable();
 }
 
@@ -96,34 +94,26 @@ void Control::parseTiltControl(ZVision *engine, Common::SeekableReadStream &stre
 				renderTable->setTiltReverse(true);
 			}
 		}
-
 		line = stream.readLine();
 		engine->getScriptManager()->trimCommentsAndWhiteSpace(&line);
 	}
-
 	renderTable->generateRenderTable();
 }
 
 void Control::getParams(const Common::String &inputStr, Common::String &parameter, Common::String &values) {
 	const char *chrs = inputStr.c_str();
 	uint lbr;
-
 	for (lbr = 0; lbr < inputStr.size(); lbr++)
 		if (chrs[lbr] == '(')
 			break;
-
 	if (lbr >= inputStr.size())
 		return;
-
 	uint rbr;
-
 	for (rbr = lbr + 1; rbr < inputStr.size(); rbr++)
 		if (chrs[rbr] == ')')
 			break;
-
 	if (rbr >= inputStr.size())
 		return;
-
 	parameter = Common::String(chrs, chrs + lbr);
 	values = Common::String(chrs + lbr + 1, chrs + rbr);
 }
diff --git a/engines/zvision/scripting/effects/distort_effect.cpp b/engines/zvision/scripting/effects/distort_effect.cpp
index 14fa6def577..b9d6579de31 100644
--- a/engines/zvision/scripting/effects/distort_effect.cpp
+++ b/engines/zvision/scripting/effects/distort_effect.cpp
@@ -34,27 +34,21 @@ namespace ZVision {
 
 DistortNode::DistortNode(ZVision *engine, uint32 key, int16 speed, float startAngle, float endAngle, float startLineScale, float endLineScale)
 	: ScriptingEffect(engine, key, SCRIPTING_EFFECT_DISTORT) {
-
 	_angle = _engine->getRenderManager()->getRenderTable()->getAngle();
 	_linScale = _engine->getRenderManager()->getRenderTable()->getLinscale();
-
 	_speed = speed;
 	_incr = true;
 	_startAngle = startAngle;
 	_endAngle = endAngle;
 	_startLineScale = startLineScale;
 	_endLineScale = endLineScale;
-
 	_curFrame = 1.0;
-
 	_diffAngle = endAngle - startAngle;
 	_diffLinScale = endLineScale - startLineScale;
-
 	_frmSpeed = (float)speed / 15.0;
 	_frames = (int)ceil((5.0 - _frmSpeed * 2.0) / _frmSpeed);
 	if (_frames <= 0)
 		_frames = 1;
-
 	if (_key != StateKey_NotSet)
 		_engine->getScriptManager()->setStateValue(_key, 1);
 }
@@ -65,12 +59,10 @@ DistortNode::~DistortNode() {
 
 bool DistortNode::process(uint32 deltaTimeInMillis) {
 	float updTime = deltaTimeInMillis / (1000.0 / 60.0);
-
 	if (_incr)
 		_curFrame += updTime;
 	else
 		_curFrame -= updTime;
-
 	if (_curFrame < 1.0) {
 		_curFrame = 1.0;
 		_incr = true;
@@ -78,26 +70,31 @@ bool DistortNode::process(uint32 deltaTimeInMillis) {
 		_curFrame = _frames;
 		_incr = false;
 	}
-
 	float diff = (1.0 / (5.0 - (_curFrame * _frmSpeed))) / (5.0 - _frmSpeed);
 	setParams(_startAngle + diff * _diffAngle, _startLineScale + diff * _diffLinScale);
-
 	return false;
 }
 
 void DistortNode::setParams(float angl, float linScale) {
 	RenderTable *table = _engine->getRenderManager()->getRenderTable();
-	if (table->getRenderState() == RenderTable::PANORAMA) {
-		table->setPanoramaFoV(angl);
-		table->setPanoramaScale(linScale);
-		table->generateRenderTable();
-		_engine->getRenderManager()->markDirty();
-	} else if (table->getRenderState() == RenderTable::TILT) {
-		table->setTiltFoV(angl);
-		table->setTiltScale(linScale);
-		table->generateRenderTable();
-		_engine->getRenderManager()->markDirty();
-	}
+	switch(table->getRenderState()) {
+	  case RenderTable::PANORAMA: {
+		  table->setPanoramaFoV(angl);
+		  table->setPanoramaScale(linScale);
+		  table->generateRenderTable();
+		  _engine->getRenderManager()->markDirty();
+		  break;
+	  }
+	  case RenderTable::TILT: {
+		  table->setTiltFoV(angl);
+		  table->setTiltScale(linScale);
+		  table->generateRenderTable();
+		  _engine->getRenderManager()->markDirty();
+		  break;
+	  }
+	  default:
+	    break;
+	}    
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 61a76c7d982..a8fc79e3a4a 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -202,12 +202,9 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 			tmp = _position - curPos;
 		else
 			tmp = _position - curPos + _width;
-
 		int balance = 0;
-
 		if (tmp > _halfWidth)
 			tmp -= _width;
-
 		if (tmp > _quarterWidth) {
 			balance = 1;
 			tmp = _halfWidth - tmp;
@@ -218,9 +215,7 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 
 		// Originally it's value -90...90 but we use -127...127 and therefore 360 replaced by 508
 		mus->setBalance( (508 * tmp) / _width );
-
 		tmp = (360 * tmp) / _width;
-
 		int deltaVol = balance;
 
 		// This value sets how fast volume goes off than sound source back of you
@@ -231,12 +226,10 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 			if (scriptManager->getCurrentLocation() == "dc10")
 				volumeCorrection = 5;
 		}
-
 		if (deltaVol != 0)
 			deltaVol = (mus->getVolume() * volumeCorrection) * (90 - tmp * balance) / 90;
 		if (deltaVol > 255)
 			deltaVol = 255;
-
 		mus->setDeltaVolume(deltaVol);
 	}
 	return false;
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index 85a272a38b1..132e6c0f123 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -276,7 +276,7 @@ bool ScriptManager::checkPuzzleCriteria(Puzzle *puzzle, uint counter) {
 
 	// criteriaList can be empty. Aka, the puzzle should be executed immediately
 	if (puzzle->criteriaList.empty() || criteriaMet) {
-		debug(2, "Puzzle %u criteria passed. Executing its ResultActions", puzzle->key);
+		debug(3, "Puzzle %u criteria passed. Executing its ResultActions", puzzle->key);
 
 		// Set the puzzle as completed
 		setStateValue(puzzle->key, 1);
@@ -578,7 +578,7 @@ void ScriptManager::changeLocation(char _world, char _room, char _node, char _vi
 
 void ScriptManager::ChangeLocationReal(bool isLoading) {
 	assert(_nextLocation.world != 0);
-	debug(1, "Changing location to: %c %c %c %c %u", _nextLocation.world, _nextLocation.room, _nextLocation.node, _nextLocation.view, _nextLocation.offset);
+	debug(1, "\tChanging location to: %c %c %c %c %u", _nextLocation.world, _nextLocation.room, _nextLocation.node, _nextLocation.view, _nextLocation.offset);
 
 	const bool enteringMenu = (_nextLocation.world == 'g' && _nextLocation.room == 'j');
 	const bool leavingMenu = (_currentLocation.world == 'g' && _currentLocation.room == 'j');
@@ -596,7 +596,6 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 				_nextLocation.node = _currentLocation.node;
 				_nextLocation.view = _currentLocation.view;
 				_nextLocation.offset = _currentLocation.offset;
-
 				return;
 			} else {
 				_currentLocation.world = 'g';
@@ -607,9 +606,7 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 			}
 		}
 	}
-
 	_engine->setRenderDelay(2);
-
 	if (!leavingMenu) {
 		if (!isLoading && !enteringMenu) {
 			setStateValue(StateKey_LastWorld, getStateValue(StateKey_World));
diff --git a/engines/zvision/text/subtitle_manager.cpp b/engines/zvision/text/subtitle_manager.cpp
index 551055cef9a..a648d04277e 100644
--- a/engines/zvision/text/subtitle_manager.cpp
+++ b/engines/zvision/text/subtitle_manager.cpp
@@ -53,7 +53,7 @@ void SubtitleManager::process(int32 deltatime) {
 	//Update all subtitles' respective deletion timers
   for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
 		if (it->_value->process(deltatime)) {
-      debug(2,"Deleting subtitle, subId=%d", it->_key);
+      debug(4,"Deleting subtitle, subId=%d", it->_key);
 			_subsFocus.remove(it->_key);			
 		  delete it->_value;
 			_subsList.erase(it);
@@ -62,18 +62,18 @@ void SubtitleManager::process(int32 deltatime) {
   }
 	if(_subsList.size() == 0)
 	  if(_subId != 0) {
-      debug(1,"Resetting subId to 0");
+      debug(4,"Resetting subId to 0");
 	    _subId = 0;
       _subsFocus.clear();
     }
 	if (redraw) {
-    debug(2,"Redrawing subtitles");
+    debug(4,"Redrawing subtitles");
 	  //Blank subtitle buffer
 	  _renderManager->clearTextSurface();
     //Render just the most recent subtitle
   	if(_subsFocus.size()) {
   	  uint16 curSub = _subsFocus.get();
-      debug(2,"Rendering subtitle %d", curSub);     
+      debug(4,"Rendering subtitle %d", curSub);     
       Subtitle *sub = _subsList[curSub];
 		  if (sub->lineId >= 0) { 
 			  Graphics::Surface textSurface;
diff --git a/engines/zvision/video/video.cpp b/engines/zvision/video/video.cpp
index 78f59cafbb6..7f214e5ab88 100644
--- a/engines/zvision/video/video.cpp
+++ b/engines/zvision/video/video.cpp
@@ -133,9 +133,8 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 					quitGame();
 					break;
 				case kZVisionActionSkipCutscene:
-					if (skippable) {
+					if (skippable)
 						vid.stop();
-					}
 					break;
 				default:
 					break;


Commit: 2de70968aacad381ddbeef1f7c891694064e4b64
    https://github.com/scummvm/scummvm/commit/2de70968aacad381ddbeef1f7c891694064e4b64
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:55+02:00

Commit Message:
ZVISION: Restructure render table generation code to improve efficiency.

Changed paths:
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h


diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index bcb86168e29..f16409541e4 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -45,13 +45,13 @@ void RenderTable::setRenderState(RenderState newState) {
 	_renderState = newState;
 	switch (newState) {
 	  case PANORAMA:
-		  _panoramaOptions.fieldOfView = 27.0f;
+		  _panoramaOptions.verticalFOV = Math::deg2rad<float>(27.0f);
 		  _panoramaOptions.linearScale = 0.55f;
 		  _panoramaOptions.reverse = false;
 		  _panoramaOptions.zeroPoint = 0;
 		  break;
 	  case TILT:
-		  _tiltOptions.fieldOfView = 27.0f;
+		  _tiltOptions.verticalFOV = Math::deg2rad<float>(27.0f);
 		  _tiltOptions.linearScale = 0.65f;
 		  _tiltOptions.reverse = false;
 		  break;
@@ -126,78 +126,118 @@ void RenderTable::generateRenderTable() {
 	}
 }
 
+/*/
+Common::Point generatePanoramaLookupPoint() {
+
+  }
+//*/
+
 void RenderTable::generatePanoramaLookupTable() {
-	for (uint y = 0; y < _numRows; y++) {
-		for (uint x = 0; x < _numColumns; x++) {
-			uint32 index = y * _numColumns + x;
-			_internalBuffer[index].x = 0;
-			_internalBuffer[index].y = 0;
-		}
-	}
+	uint halfRows = ceil(_numRows/2);
+	uint halfColumns = ceil(_numColumns/2);
 	float halfWidth = (float)_numColumns / 2.0f;
 	float halfHeight = (float)_numRows / 2.0f;
-	float fovInRadians = Math::deg2rad<float>(_panoramaOptions.fieldOfView);
-	float cylinderRadius = halfHeight / tan(fovInRadians);
-	for (uint x = 0; x < _numColumns; ++x) {
+	float cylinderRadius = halfHeight / tan(_panoramaOptions.verticalFOV);
+	
+	//Transformation is both horizontally and vertically symmetrical about the camera axis,
+	//We can thus save on trigonometric calculations by computing one quarter of the transformation matrix and then mirroring it in both X & Y
+	for (uint x = 0; x < halfColumns; ++x) {
 		// Add an offset of 0.01 to overcome zero tan/atan issue (vertical line on half of screen)
 		// Alpha represents the horizontal angle between the viewer at the center of a cylinder and x
 		float alpha = atan(((float)x - halfWidth + 0.01f) / cylinderRadius);
 
 		// To get x in cylinder coordinates, we just need to calculate the arc length
 		// We also scale it by _panoramaOptions.linearScale
-		int32 xInCylinderCoords = int32(floor((cylinderRadius * _panoramaOptions.linearScale * alpha) + halfWidth));
+		int32 xInCylinderCoords = int32(round((cylinderRadius * _panoramaOptions.linearScale * alpha) + halfWidth));
 
 		float cosAlpha = cos(alpha);
+		uint32 columnIndexL = x;
+		uint32 columnIndexR = (_numColumns - 1) - x;
+		uint32 rowIndexT = 0;
+		uint32 rowIndexB = _numColumns * (_numRows - 1);
 
-		for (uint y = 0; y < _numRows; ++y) {
+		for (uint y = 0; y < halfRows; ++y) {
 			// To calculate y in cylinder coordinates, we can do similar triangles comparison,
 			// comparing the triangle from the center to the screen and from the center to the edge of the cylinder
-			int32 yInCylinderCoords = int32(floor(halfHeight + ((float)y - halfHeight) * cosAlpha));
-
-			uint32 index = y * _numColumns + x;
+			int32 yInCylinderCoords = int32(round(halfHeight + ((float)y - halfHeight) * cosAlpha));
+			
+			uint32 indexTL = rowIndexT + columnIndexL;
+			uint32 indexBL = rowIndexB + columnIndexL;
+			uint32 indexTR = rowIndexT + columnIndexR;
+			uint32 indexBR = rowIndexB + columnIndexR;
 
 			// Only store the (x,y) offsets instead of the absolute positions
-			_internalBuffer[index].x = xInCylinderCoords - x;
-			_internalBuffer[index].y = yInCylinderCoords - y;
+			_internalBuffer[indexTL].x = xInCylinderCoords - x;
+			_internalBuffer[indexTL].y = yInCylinderCoords - y;
+			
+			//Store mirrored offset values
+			_internalBuffer[indexBL].x = _internalBuffer[indexTL].x;
+			_internalBuffer[indexBL].y = -_internalBuffer[indexTL].y;
+			_internalBuffer[indexTR].x = -_internalBuffer[indexTL].x;
+			_internalBuffer[indexTR].y = _internalBuffer[indexTL].y;
+			_internalBuffer[indexBR].x = -_internalBuffer[indexTL].x;
+			_internalBuffer[indexBR].y = -_internalBuffer[indexTL].y;
+			
+			//Increment indices
+			rowIndexT += _numColumns;
+			rowIndexB -= _numColumns;
 		}
 	}
 }
 
 void RenderTable::generateTiltLookupTable() {
+	uint halfRows = ceil(_numRows/2);
+	uint halfColumns = ceil(_numColumns/2);
 	float halfWidth = (float)_numColumns / 2.0f;
 	float halfHeight = (float)_numRows / 2.0f;
-	float fovInRadians = Math::deg2rad<float>(_tiltOptions.fieldOfView);
-	float cylinderRadius = halfWidth / tan(fovInRadians);
+	float cylinderRadius = halfWidth / tan(_tiltOptions.verticalFOV);
 	_tiltOptions.gap = cylinderRadius * atan2((float)(halfHeight / cylinderRadius), 1.0f) * _tiltOptions.linearScale;
-	for (uint y = 0; y < _numRows; ++y) {
+	
+	//Transformation is both horizontally and vertically symmetrical about the camera axis,
+	//We can thus save on trigonometric calculations by computing one quarter of the transformation matrix and then mirroring it in both X & Y
+	for (uint y = 0; y < halfRows; ++y) {
 		// Add an offset of 0.01 to overcome zero tan/atan issue (horizontal line on half of screen)
 		// Alpha represents the vertical angle between the viewer at the center of a cylinder and y
 		float alpha = atan(((float)y - halfHeight + 0.01f) / cylinderRadius);
 
 		// To get y in cylinder coordinates, we just need to calculate the arc length
 		// We also scale it by _tiltOptions.linearScale
-		int32 yInCylinderCoords = int32(floor((cylinderRadius * _tiltOptions.linearScale * alpha) + halfHeight));
+		int32 yInCylinderCoords = int32(round((cylinderRadius * _tiltOptions.linearScale * alpha) + halfHeight));
 
 		float cosAlpha = cos(alpha);
-		uint32 columnIndex = y * _numColumns;
+		uint32 columnIndexTL = y * _numColumns;
+		uint32 columnIndexBL = (_numRows-(y+1)) * _numColumns;
+		uint32 columnIndexTR = columnIndexTL + (_numColumns - 1);
+		uint32 columnIndexBR = columnIndexBL + (_numColumns - 1);
 
-		for (uint x = 0; x < _numColumns; ++x) {
+		for (uint x = 0; x < halfColumns; ++x) {
 			// To calculate x in cylinder coordinates, we can do similar triangles comparison,
 			// comparing the triangle from the center to the screen and from the center to the edge of the cylinder
-			int32 xInCylinderCoords = int32(floor(halfWidth + ((float)x - halfWidth) * cosAlpha));
+			int32 xInCylinderCoords = int32(round(halfWidth + ((float)x - halfWidth) * cosAlpha));
 
-			uint32 index = columnIndex + x;
+			uint32 indexTL = columnIndexTL + x;
+			uint32 indexBL = columnIndexBL + x;
+			uint32 indexTR = columnIndexTR - x;
+			uint32 indexBR = columnIndexBR - x;
 
 			// Only store the (x,y) offsets instead of the absolute positions
-			_internalBuffer[index].x = xInCylinderCoords - x;
-			_internalBuffer[index].y = yInCylinderCoords - y;
+			_internalBuffer[indexTL].x = xInCylinderCoords - x;
+			_internalBuffer[indexTL].y = yInCylinderCoords - y;
+			
+			//Store mirrored offset values
+			_internalBuffer[indexBL].x = _internalBuffer[indexTL].x;
+			_internalBuffer[indexBL].y = -_internalBuffer[indexTL].y;
+			_internalBuffer[indexTR].x = -_internalBuffer[indexTL].x;
+			_internalBuffer[indexTR].y = _internalBuffer[indexTL].y;
+			_internalBuffer[indexBR].x = -_internalBuffer[indexTL].x;
+			_internalBuffer[indexBR].y = -_internalBuffer[indexTL].y;
 		}
 	}
 }
 
 void RenderTable::setPanoramaFoV(float fov) {
 	assert(fov > 0.0f);
-	_panoramaOptions.fieldOfView = fov;
+	_panoramaOptions.verticalFOV = Math::deg2rad<float>(fov);
 }
 
 void RenderTable::setPanoramaScale(float scale) {
@@ -223,7 +263,7 @@ uint16 RenderTable::getPanoramaZeroPoint() {
 
 void RenderTable::setTiltFoV(float fov) {
 	assert(fov > 0.0f);
-	_tiltOptions.fieldOfView = fov;
+	_tiltOptions.verticalFOV = Math::deg2rad<float>(fov);
 }
 
 void RenderTable::setTiltScale(float scale) {
@@ -242,9 +282,9 @@ float RenderTable::getTiltGap() {
 float RenderTable::getAngle() {
 	switch(_renderState) {
 	  case TILT:
-  		return _tiltOptions.fieldOfView;
+  		return Math::rad2deg<float>(_tiltOptions.verticalFOV);
 		case PANORAMA:
-		  return _panoramaOptions.fieldOfView;
+		  return Math::rad2deg<float>(_panoramaOptions.verticalFOV);
 	  default:
   		return 1.0;
 	}
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index f8a1b8b87fa..90f1a6eebc6 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -27,6 +27,12 @@
 
 namespace ZVision {
 
+struct MutationPoint {
+  uint8 Xweight = 0;
+  uint8 Yweight = 0;
+  Common::Rect PixelBlock = Common::Rect(0,0);
+};
+
 class RenderTable {
 public:
 	RenderTable(uint numRows, uint numColumns);
@@ -40,12 +46,14 @@ public:
 	};
 
 private:
-	uint _numColumns, _numRows;
+	uint _numColumns, _numRows; //Working area width, height
 	Common::Point *_internalBuffer;
+//  MutationPoint *_internalBuffer;
 	RenderState _renderState;
+	bool highQuality = false;
 
 	struct {
-		float fieldOfView;
+		float verticalFOV;  //Radians
 		float linearScale;
 		bool reverse;
 		uint16 zeroPoint;
@@ -53,7 +61,7 @@ private:
 
 	// TODO: See if tilt and panorama need to have separate options
 	struct {
-		float fieldOfView;
+		float verticalFOV;  //Radians
 		float linearScale;
 		bool reverse;
 		float gap;
@@ -71,14 +79,14 @@ public:
 	void mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf);
 	void generateRenderTable();
 
-	void setPanoramaFoV(float fov);
+	void setPanoramaFoV(float fov); //Degrees
 	void setPanoramaScale(float scale);
 	void setPanoramaReverse(bool reverse);
 	void setPanoramaZeroPoint(uint16 point);
 	uint16 getPanoramaZeroPoint();
 	bool getPanoramaReverse();
 
-	void setTiltFoV(float fov);
+	void setTiltFoV(float fov); //Degrees
 	void setTiltScale(float scale);
 	void setTiltReverse(bool reverse);
 
@@ -88,6 +96,7 @@ public:
 
 private:
 	void generatePanoramaLookupTable();
+//	Common::Point generatePanoramaLookupPoint();
 	void generateTiltLookupTable();
 };
 


Commit: e003159d26521d8ce16623d73f87ae18ba75331f
    https://github.com/scummvm/scummvm/commit/e003159d26521d8ce16623d73f87ae18ba75331f
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:55+02:00

Commit Message:
ZVISION: Add workaround for bug in MT-32 emulation.
Bug makes MIDI music puzzles in Nemesis impossible.
TODO: Inform MT-32 emulator maintainer about this bug.

Changed paths:
    engines/zvision/sound/midi.cpp
    engines/zvision/sound/midi.h


diff --git a/engines/zvision/sound/midi.cpp b/engines/zvision/sound/midi.cpp
index 8647dabb030..0b26ec329af 100644
--- a/engines/zvision/sound/midi.cpp
+++ b/engines/zvision/sound/midi.cpp
@@ -24,18 +24,27 @@
 #include "audio/mididrv.h"
 
 #include "zvision/sound/midi.h"
+#include "common/debug.h"
 
 namespace ZVision {
 
 MidiManager::MidiManager() {
-	MidiDriver::DeviceHandle dev = MidiDriver::detectDevice(MDT_MIDI | MDT_ADLIB);
+	MidiDriver::DeviceHandle dev = MidiDriver::detectDevice(MDT_MIDI | MDT_ADLIB);  //NB Bug current in MT-32 emulation: MIDI channel 0 does not play anything!
 	_driver = MidiDriver::createMidi(dev);
-	if (_driver->open()) {
-		warning("Can't open MIDI, no MIDI output!");
-		available = false;
-		}
-	else
+  if (_driver->open()) {
+	  warning("Can't open MIDI, no MIDI output!");
+	  available = false;
+	  }
+	else {
+	  Common::String driverName = MidiDriver::getDeviceString(dev,MidiDriver::DeviceStringType::kDriverName);
+	  Common::String deviceName = MidiDriver::getDeviceString(dev,MidiDriver::DeviceStringType::kDeviceName);
+	  mt32workaround = driverName.contains("MT-32");
+    debug(1,"MIDI opened, driver type: %s, device name: %s", driverName.c_str(), deviceName.c_str());
+    if(mt32workaround)
+      debug(1,"Blocking use of MIDI channel 0 to work around bug in MT-32 emulation.");
 	  available = true;
+	  maxChannels = _driver->MIDI_CHANNEL_COUNT;
+  }
 }
 
 MidiManager::~MidiManager() {
@@ -46,49 +55,47 @@ MidiManager::~MidiManager() {
 
 void MidiManager::stop() {
 	for (int8 i = 0; i < 16; i++)
-		if (_playChannels[i].playing)
+		if (activeChannels[i].playing)
 			noteOff(i);
 }
 
 void MidiManager::noteOn(int8 channel, int8 note, int8 velocity) {
 	assert(channel <= 15);
-
-	_playChannels[channel].playing = true;
-	_playChannels[channel].note = note;
+	activeChannels[channel].playing = true;
+	activeChannels[channel].note = note;
 	_driver->send(channel | (velocity << 16) | (note << 8) | 0x90);
+	debug(1,"MIDI note on, channel %d, note %d, velocity %d", channel, note, velocity);
 }
 
 void MidiManager::noteOff(int8 channel) {
 	assert(channel <= 15);
 
-	if (_playChannels[channel].playing) {
-		_playChannels[channel].playing = false;
-		_driver->send(channel | (_playChannels[channel].note << 8) | 0x80);
+	if (activeChannels[channel].playing) {
+		activeChannels[channel].playing = false;
+		_driver->send(channel | (activeChannels[channel].note << 8) | 0x80);
 	}
 }
 
 int8 MidiManager::getFreeChannel() {
-	for (int8 i = 0; i < 16; i++)
-		if (!_playChannels[i].playing)
+  uint8 start = mt32workaround ? 1 : 0; //MT-32 emulator driver currently fails to play anything when sent notes on channel 0.  Quick & dirty fix, since we only need a few notes for Nemesis music puzzles.  Inform maintainer of MT-32 emulator code of bug for proper fix in the future & then remove this nasty hack once that's sorted out.
+	for (int8 i = start; i < 16; i++)
+		if (!activeChannels[i].playing)
 			return i;
 	return -1;
 }
 
 void MidiManager::setPan(int8 channel, int8 pan) {
 	assert(channel <= 15);
-
 	_driver->send(channel | (pan << 16) | 0xAB0);
 }
 
 void MidiManager::setVolume(int8 channel, int8 volume) {
 	assert(channel <= 15);
-
 	_driver->send(channel | (volume << 16) | 0x7B0);
 }
 
 void MidiManager::setProgram(int8 channel, int8 prog) {
 	assert(channel <= 15);
-
 	_driver->send(channel | (prog << 8) | 0xC0);
 }
 
diff --git a/engines/zvision/sound/midi.h b/engines/zvision/sound/midi.h
index b9022baf387..25dd55bbc05 100644
--- a/engines/zvision/sound/midi.h
+++ b/engines/zvision/sound/midi.h
@@ -45,14 +45,16 @@ public:
 
 protected:
   bool available = false;
+  bool mt32workaround = false;
 	struct chan {
 		bool playing;
 		int8 note;
 		chan() : playing(false), note(0) {};
 	};
-
+  uint8 startChannel = 0;
+  uint8 maxChannels = 16;
 	MidiDriver *_driver;
-	chan _playChannels[16];
+	chan activeChannels[16];
 };
 
 }


Commit: 1fa6ebd8d374b279043c533e52f014010f7982ff
    https://github.com/scummvm/scummvm/commit/1fa6ebd8d374b279043c533e52f014010f7982ff
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:55+02:00

Commit Message:
ZVISION: Add VolumeManager class with various volume scaling profiles.
Clean up & improve PanTrackNode functionality.
Add estimated directional psychoacoustic data to VolumeManager.
Allow different volume profiles to be used for different games;
ZGI scripts seem to use logarithmic power scaling for audio amplitude;
Nemesis scripts seem to use nearly linear values with a much less pronounced curve.
TODO - rework code such that directional attenuation is applied AFTER volume scaling curve.
This should allow a single psychoacoustic panning profile without having to match this curve to whatever amplitude curve the game uses.

Changed paths:
  A engines/zvision/sound/volume_manager.cpp
  A engines/zvision/sound/volume_manager.h
    engines/zvision/module.mk
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/effects/music_effect.h
    engines/zvision/zvision.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/module.mk b/engines/zvision/module.mk
index 87ed0033f19..cc7d392e0ee 100644
--- a/engines/zvision/module.mk
+++ b/engines/zvision/module.mk
@@ -42,6 +42,7 @@ MODULE_OBJS := \
 	scripting/effects/ttytext_effect.o \
 	sound/midi.o \
 	sound/zork_raw.o \
+	sound/volume_manager.o \
 	text/string_manager.o \
 	text/subtitle_manager.o \
 	text/text.o \
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index a8fc79e3a4a..08907ef7446 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -29,31 +29,16 @@
 #include "zvision/sound/midi.h"
 #include "zvision/sound/zork_raw.h"
 
+#include "zvision/sound/volume_manager.h"
+
 #include "common/stream.h"
 #include "common/file.h"
 #include "audio/decoders/wave.h"
 
-namespace ZVision {
+#include "math/utils.h"
+#include "math/angle.h"
 
-// FIXME: This is wrong, and not what the original is doing.
-// Using actual linear volume values fixes bug #7176.
-/*static const uint8 dbMapLinear[256] =
-{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
-1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2,
-2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4,
-4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7,
-8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14,
-14, 15, 15, 16, 16, 17, 18, 18, 19, 20, 21, 21, 22, 23, 24, 25,
-26, 27, 28, 29, 30, 31, 32, 33, 34, 36, 37, 38, 40, 41, 43, 45,
-46, 48, 50, 52, 53, 55, 57, 60, 62, 64, 67, 69, 72, 74, 77, 80,
-83, 86, 89, 92, 96, 99, 103, 107, 111, 115, 119, 123, 128, 133, 137, 143,
-148, 153, 159, 165, 171, 177, 184, 191, 198, 205, 212, 220, 228, 237, 245, 255};*/
+namespace ZVision {
 
 MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool loop, uint8 volume)
 	: MusicNodeBASE(engine, key, SCRIPTING_EFFECT_AUDIO) {
@@ -84,9 +69,11 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 
 		if (_loop) {
 			Audio::LoopingAudioStream *loopingAudioStream = new Audio::LoopingAudioStream(audioStream, 0, DisposeAfterUse::YES);
-			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, loopingAudioStream, -1, _volume /*dbMapLinear[_volume]*/);
+//			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, loopingAudioStream, -1, _volume /*dbMapLinear[_volume]*/);
+			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, loopingAudioStream, -1, _engine->getVolumeManager()->convert(_volume));
 		} else {
-			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, audioStream, -1, _volume /*dbMapLinear[_volume]*/);
+//			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, audioStream, -1, _volume /*dbMapLinear[_volume]*/);
+			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, audioStream, -1, _engine->getVolumeManager()->convert(_volume));
 		}
 
 		if (_key != StateKey_NotSet)
@@ -167,7 +154,8 @@ void MusicNode::setVolume(uint8 newVolume) {
 	if (_deltaVolume >= _volume)
 		_engine->_mixer->setChannelVolume(_handle, 0);
 	else
-		_engine->_mixer->setChannelVolume(_handle, _volume - _deltaVolume /*dbMapLinear[_volume - _deltaVolume]*/);
+//		_engine->_mixer->setChannelVolume(_handle, _volume - _deltaVolume /*dbMapLinear[_volume - _deltaVolume]*/);
+    _engine->_mixer->setChannelVolume(_handle, _engine->getVolumeManager()->convert(_volume - _deltaVolume));
 }
 
 uint8 MusicNode::getVolume() {
@@ -177,7 +165,7 @@ uint8 MusicNode::getVolume() {
 PanTrackNode::PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos)
 	: ScriptingEffect(engine, key, SCRIPTING_EFFECT_PANTRACK) {
 	_slot = slot;
-	_position = pos;
+	sourcePos = pos;
 
 	// Try to set pan value for music node immediately
 	process(0);
@@ -192,31 +180,50 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 	if (fx && fx->getType() == SCRIPTING_EFFECT_AUDIO) {
 		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
 
-		int curPos = scriptManager->getStateValue(StateKey_ViewPos);
+		int viewPos = scriptManager->getStateValue(StateKey_ViewPos);
 		int16 _width = _engine->getRenderManager()->getBkgSize().x;
 		int16 _halfWidth = _width / 2;
 		int16 _quarterWidth = _width / 4;
 
-		int tmp = 0;
-		if (curPos <= _position)
-			tmp = _position - curPos;
+		int deltaPos = 0;
+		if (viewPos <= sourcePos)
+			deltaPos = sourcePos - viewPos;
 		else
-			tmp = _position - curPos + _width;
+			deltaPos = sourcePos - viewPos + _width;
+		debug(1,"soundPos: %d, viewPos: %d, deltaPos: %d, width: %d", sourcePos, viewPos, deltaPos, _width);
+    //deltaPos is sound source position relative to player, clockwise from centre of camera axis to front when viewed top-down
+//*/
+    //NEW SYSTEM
+    Math::Angle azimuth = 360*deltaPos/_width;
+    int8 balance = (int)127*azimuth.getSine();
+    uint8 volume = mus->getVolume();
+    uint8 deltaVol = volume - _engine->getVolumeManager()->convert(volume, kVolumeLinear, azimuth);
+		mus->setBalance(balance);  
+		mus->setDeltaVolume(deltaVol);
+		debug(1,"Balance %d, volume %d, deltaVol %d", balance, volume-deltaVol, deltaVol);
+      
+/*/
+    //OLD SYSTEM;		
 		int balance = 0;
-		if (tmp > _halfWidth)
-			tmp -= _width;
-		if (tmp > _quarterWidth) {
+		if (deltaPos > _halfWidth)  //Source to left
+			deltaPos -= _width; //Make angle negative relative to datum
+		if (deltaPos > _quarterWidth) {
 			balance = 1;
-			tmp = _halfWidth - tmp;
-		} else if (tmp < -_quarterWidth) {
+			deltaPos = _halfWidth - deltaPos; //Make relative to right centre?
+		} else if (deltaPos < -_quarterWidth) {
 			balance = -1;
-			tmp = -_halfWidth - tmp;
+			deltaPos = -_halfWidth - deltaPos;  //Make relative to left centre?
 		}
 
+    //TODO - rework this so that balance correctly shifts back to centre when in rear, and ensure that attenuation in rear is also correct.
+    //Correlate this effort with adjusting the volume curves in VolumeManager.
+
 		// Originally it's value -90...90 but we use -127...127 and therefore 360 replaced by 508
-		mus->setBalance( (508 * tmp) / _width );
-		tmp = (360 * tmp) / _width;
+		// Left = -127, centre = 0, right = +127
+		mus->setBalance( (508 * deltaPos) / _width );
+		deltaPos = (360 * deltaPos) / _width;
 		int deltaVol = balance;
+		debug(1,"Balance %d", balance);
 
 		// This value sets how fast volume goes off than sound source back of you
 		// By this value we can hack some "bugs" have place in original game engine like beat sound in ZGI-dc10
@@ -227,10 +234,11 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 				volumeCorrection = 5;
 		}
 		if (deltaVol != 0)
-			deltaVol = (mus->getVolume() * volumeCorrection) * (90 - tmp * balance) / 90;
+			deltaVol = (mus->getVolume() * volumeCorrection) * (90 - deltaPos * balance) / 90;
 		if (deltaVol > 255)
 			deltaVol = 255;
 		mus->setDeltaVolume(deltaVol);
+//*/
 	}
 	return false;
 }
diff --git a/engines/zvision/scripting/effects/music_effect.h b/engines/zvision/scripting/effects/music_effect.h
index 06be4f14729..d535d029d13 100644
--- a/engines/zvision/scripting/effects/music_effect.h
+++ b/engines/zvision/scripting/effects/music_effect.h
@@ -26,6 +26,7 @@
 #include "zvision/scripting/scripting_effect.h"
 #include "zvision/text/subtitle_manager.h"
 
+
 namespace Common {
 class String;
 }
@@ -50,7 +51,6 @@ public:
 	virtual uint8 getVolume() = 0;
 	virtual void setDeltaVolume(uint8 volume) = 0;
 	virtual void setBalance(int8 balance) = 0;
-
 	virtual void setFade(int32 time, uint8 target) = 0;
 };
 
@@ -128,7 +128,7 @@ public:
 
 private:
 	uint32 _slot;
-	int16 _position;
+	int16 sourcePos;
 };
 
 } // End of namespace ZVision
diff --git a/engines/zvision/sound/volume_manager.cpp b/engines/zvision/sound/volume_manager.cpp
new file mode 100644
index 00000000000..ebb3bdddb1a
--- /dev/null
+++ b/engines/zvision/sound/volume_manager.cpp
@@ -0,0 +1,193 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "zvision/sound/volume_manager.h"
+#include "common/debug.h"
+
+namespace ZVision {
+
+//Power law with exponent 1.5.
+static constexpr uint8 powerLaw[256] = {
+    0,  0,  0,  0,  1,  1,  1,  1,  1,  2,  2,  2,  3,  3,  3,  4, 
+    4,  4,  5,  5,  6,  6,  6,  7,  7,  8,  8,  9,  9, 10, 10, 11,
+   11, 12, 12, 13, 14, 14, 15, 15, 16, 16, 17, 18, 18, 19, 20, 20,
+   21, 21, 22, 23, 23, 24, 25, 26, 26, 27, 28, 28, 29, 30, 31, 31,
+   32, 33, 34, 34, 35, 36, 37, 37, 38, 39, 40, 41, 41, 42, 43, 44,
+   45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 53, 54, 55, 56, 57, 58,
+   59, 60, 61, 62, 63, 64, 65, 65, 66, 67, 68, 69, 70, 71, 72, 73,
+   74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 88, 89, 90,
+   91, 92, 93, 94, 95, 96, 97, 98, 99,100,102,103,104,105,106,107,
+  108,109,110,112,113,114,115,116,117,119,120,121,122,123,124,126,
+  127,128,129,130,132,133,134,135,136,138,139,140,141,142,144,145,
+  146,147,149,150,151,152,154,155,156,158,159,160,161,163,164,165,
+  167,168,169,171,172,173,174,176,177,178,180,181,182,184,185,187,
+  188,189,191,192,193,195,196,197,199,200,202,203,204,206,207,209,
+  210,211,213,214,216,217,218,220,221,223,224,226,227,228,230,231,
+  233,234,236,237,239,240,242,243,245,246,248,249,251,252,254,255
+  };
+  
+static constexpr uint8 logPower[256] = {
+    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 
+    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,
+    1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
+    1,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  3,  3,  3,  3,  3,
+    3,  4,  4,  4,  4,  5,  5,  5,  5,  6,  6,  6,  7,  7,  7,  8,
+    8,  9,  9, 10, 10, 11, 11, 12, 13, 13, 14, 15, 16, 17, 18, 19,
+   20, 21, 22, 23, 24, 26, 27, 29, 30, 32, 34, 36, 38, 40, 42, 45,
+   47, 50, 52, 55, 58, 62, 65, 69, 73, 77, 81, 86, 90, 96,101,107,
+  113,119,126,133,140,148,156,165,174,184,194,205,217,229,241,255
+  };
+  
+//*/
+static constexpr uint8 logAmplitude[256] = {
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1,  
+  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
+  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  
+  1,  1,  1,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2, 
+  2,  2,  2,  2,  2,  2,  3,  3,  3,  3,  3,  3,  3,  3,  3,  3, 
+  3,  3,  4,  4,  4,  4,  4,  4,  4,  4,  4,  5,  5,  5,  5,  5,  
+  5,  5,  5,  6,  6,  6,  6,  6,  6,  7,  7,  7,  7,  7,  8,  8,  
+  8,  8,  8,  9,  9,  9,  9, 10, 10, 10, 10, 11, 11, 11, 12, 12, 
+  2, 13, 13, 13, 14, 14, 15, 15, 15, 16, 16, 17, 17, 18, 18, 19, 
+ 19, 20, 20, 21, 21, 22, 23, 23, 24, 24, 25, 26, 27, 27, 28, 29, 
+ 30, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45, 
+ 46, 47, 48, 50, 51, 52, 54, 55, 57, 58, 60, 62, 63, 65, 67, 69, 
+ 71, 73, 75, 77, 79, 81, 83, 86, 88, 90, 93, 96, 98,101,104,107,
+110,113,116,119,122,126,129,133,136,140,144,148,152,156,160,165,
+169,174,179,184,189,194,200,205,211,217,222,229,235,241,248,255
+};
+/*/
+// Old system; this is wrong, caused bug #7176; cloister fountain (value 50 in-game, 127/255) inaudible
+// Using linear volume served as a temporary fix, but causes other sounds not to play at correct amplitudes (e.g. beehive, door singing in ZGI)
+static constexpr uint8 logAmplitude[256] = {
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
+  1,  1,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,  2,  2,
+  2,  2,  2,  2,  3,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,
+  4,  4,  4,  5,  5,  5,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,
+  8,  8,  8,  9,  9,  9, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14,
+ 14, 15, 15, 16, 16, 17, 18, 18, 19, 20, 21, 21, 22, 23, 24, 25,
+ 26, 27, 28, 29, 30, 31, 32, 33, 34, 36, 37, 38, 40, 41, 43, 45,
+ 46, 48, 50, 52, 53, 55, 57, 60, 62, 64, 67, 69, 72, 74, 77, 80,
+ 83, 86, 89, 92, 96, 99,103,107,111,115,119,123,128,133,137,143,
+148,153,159,165,171,177,184,191,198,205,212,220,228,237,245,255
+};
+//*/
+
+//Relative absolute amplitude (to 255) of a sound source as it circles the listener's head from front to rear, due to ear pinna shape.
+//Maximum attenuation -5dB when fully to rear.
+//Ideally should be applied AFTER volume profile is applied to script files.
+static constexpr uint8 directionalAmplitude[181] = {
+255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
+255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
+255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
+255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
+255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
+255,255,255,255,255,255,255,255,255,255,255,255,255,254,254,253,
+252,251,249,248,246,245,243,241,238,236,234,231,228,226,223,220,
+217,214,211,208,204,201,198,195,191,188,185,181,178,175,171,168,
+165,162,158,155,152,149,146,143,141,138,135,132,130,127,125,122,
+120,118,116,113,111,109,108,106,104,102,101, 99, 98, 96, 95, 93,
+ 92, 91, 90, 89, 88, 87, 86, 85, 85, 84, 83, 83, 82, 82, 82, 81,
+ 81, 81, 81, 81, 81
+};
+
+VolumeManager::VolumeManager(volumeScaling mode) :
+  _mode(mode) {
+};
+  
+uint8 VolumeManager::convert(uint8 inputValue) {
+  return convert(inputValue, _mode);
+};
+  
+uint8 VolumeManager::convert(uint8 inputValue, Math::Angle azimuth) {
+  return convert(inputValue, _mode, azimuth);
+};
+
+uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode, Math::Angle azimuth) {
+  Math::Angle _azimuth = azimuth;
+  uint8 index = abs(round(_azimuth.getDegrees(-180)));
+  switch(mode) {
+    case kVolumeLogPower:
+      break;
+    case kVolumeLogAmplitude:
+      break;
+    case kVolumePowerLaw:
+      break;
+    case kVolumeParabolic:
+      break;
+    case kVolumeCubic:
+      break;
+    case kVolumeQuartic:
+      break;
+    case kVolumeLinear:
+    default:
+      break;
+  }
+  uint8 deltaVolume = (255 - directionalAmplitude[index])/directionalDivisor;
+  return convert(inputValue*(255-deltaVolume)/255, mode);
+};
+
+uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode) {
+  uint8 scaledInput = inputValue * 255 / internalScale;
+  uint8 output = 0;
+  switch(mode) {
+    case kVolumeLogPower:
+      output = logPower[scaledInput];
+      break;
+    case kVolumeLogAmplitude:
+      output = logAmplitude[scaledInput];
+      break;
+    case kVolumePowerLaw:
+      output = powerLaw[scaledInput];
+      break;
+    case kVolumeParabolic:
+      output = pow(scaledInput,2)/255;
+      break;
+    case kVolumeCubic:
+      output = pow(scaledInput,3)/pow(255,2);
+      break;
+    case kVolumeQuartic:
+      output = pow(scaledInput,4)/pow(255,3);
+      break;
+    case kVolumeLinear:
+    default:
+      output = scaledInput;
+      break;
+  }
+  debug(1,"Script volume %d, converted output %d", scaledInput, output);
+  return output;
+};
+
+} // End of namespace ZVision
diff --git a/engines/zvision/sound/volume_manager.h b/engines/zvision/sound/volume_manager.h
new file mode 100644
index 00000000000..8631039ef3d
--- /dev/null
+++ b/engines/zvision/sound/volume_manager.h
@@ -0,0 +1,58 @@
+/* ScummVM - Graphic Adventure Engine
+ *
+ * ScummVM is the legal property of its developers, whose names
+ * are too numerous to list here. Please refer to the COPYRIGHT
+ * file distributed with this source distribution.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "common/scummsys.h"
+#include "math/angle.h"
+
+#ifndef ZVISION_VOLUME_MANAGER
+#define ZVISION_VOLUME_MANAGER
+
+namespace ZVision {
+
+enum volumeScaling {
+  kVolumeLinear,
+  kVolumePowerLaw,
+  kVolumeParabolic,
+  kVolumeCubic,
+  kVolumeQuartic,
+  kVolumeLogPower,
+  kVolumeLogAmplitude
+};
+
+class VolumeManager {
+public:
+  VolumeManager(volumeScaling mode);
+  ~VolumeManager() {};
+  volumeScaling getMode() {return _mode;};
+  void setMode(volumeScaling mode) {_mode = mode;};
+  uint8 convert(uint8 inputValue);
+  uint8 convert(uint8 inputValue, volumeScaling mode);
+  uint8 convert(uint8 inputValue, Math::Angle azimuth);
+  uint8 convert(uint8 inputValue, volumeScaling mode, Math::Angle azimuth);
+private:
+  uint8 directionalDivisor = 1; //Used to lessen effect of directional audio to match directional effect strength to different volume scaling profiles.
+  uint internalScale = 255;
+  volumeScaling _mode = kVolumeLinear;
+};
+
+} // End of namespace ZVision
+
+#endif
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index 970033bc3db..a3fabbb61c5 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -34,6 +34,7 @@
 #include "zvision/text/text.h"
 #include "zvision/text/truetype_font.h"
 #include "zvision/sound/midi.h"
+#include "zvision/sound/volume_manager.h"
 
 #include "backends/keymapper/keymap.h"
 #include "backends/keymapper/keymapper.h"
@@ -53,6 +54,7 @@
 #include "engines/util.h"
 #include "audio/mixer.h"
 
+
 namespace ZVision {
 
 #define ZVISION_SETTINGS_KEYS_COUNT 12
@@ -100,6 +102,7 @@ ZVision::ZVision(OSystem *syst, const ZVisionGameDescription *gameDesc)
 	  _rnd(nullptr),
 	  _menu(nullptr),
 	  _subtitleManager(nullptr),
+	  _volumeManager(nullptr),
 	  _searchManager(nullptr),
 	  _textRenderer(nullptr),
 	  _doubleFPS(false),
@@ -128,6 +131,7 @@ ZVision::~ZVision() {
 	delete _subtitleManager;	
 	delete _rnd;
 	delete _midiManager;
+	delete _volumeManager;
 	getTimerManager()->removeTimerProc(&fpsTimerCallback);
 }
 
@@ -208,11 +212,13 @@ void ZVision::initialize() {
       _renderManager = new RenderManager(this, nemesisLayout, _resourcePixelFormat, _doubleFPS, _widescreen);
 	    _menu = new MenuNemesis(this, _renderManager->getMenuArea());
       _subtitleManager = new SubtitleManager(this, nemesisLayout, _resourcePixelFormat, _doubleFPS);
+	    _volumeManager = new VolumeManager(kVolumeLinear);
 	    break;
     case GID_GRANDINQUISITOR:
       _renderManager = new RenderManager(this, zgiLayout, _resourcePixelFormat, _doubleFPS, _widescreen);
 		  _menu = new MenuZGI(this, _renderManager->getMenuArea());
       _subtitleManager = new SubtitleManager(this, zgiLayout, _resourcePixelFormat, _doubleFPS);
+	    _volumeManager = new VolumeManager(kVolumeLogAmplitude);
 		  break;
 	  case GID_NONE:
 	  default:
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index f7008a6a3da..44a96318eb7 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -68,6 +68,7 @@ class SubtitleManager;
 class TextRenderer;
 class Subtitle;
 class MidiManager;
+class VolumeManager;
 
 struct ScreenLayout {
   Common::Rect screenArea;  //Original screen resolution
@@ -180,6 +181,7 @@ private:
 	SaveManager *_saveManager;
 	MenuManager *_menu;
   SubtitleManager *_subtitleManager;
+  VolumeManager *_volumeManager;
 
 	// Clock
 	Clock _clock;
@@ -241,7 +243,9 @@ public:
 	SubtitleManager *getSubtitleManager() const {
 		return _subtitleManager;
 	}
-
+	VolumeManager *getVolumeManager() const {
+		return _volumeManager;
+	}
 	Common::Keymap *getGameKeymap() const {
 		return _gameKeymap;
 	}


Commit: 292378a7c0c932b21f04f753dedcfd765a62ddb1
    https://github.com/scummvm/scummvm/commit/292378a7c0c932b21f04f753dedcfd765a62ddb1
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:56+02:00

Commit Message:
ZVISION: Sound system rework.
Panoramic audio now works correctly when different volume profiles are in use.
MIDI driver made more robust, now handles both pan and balance.
Volume scale conversion fully encapsulated in VolumeManager;
no more converting between Zvision and ScummVM volume scales on the fly.

Changed paths:
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/effects/music_effect.h
    engines/zvision/scripting/scr_file_handling.cpp
    engines/zvision/sound/midi.cpp
    engines/zvision/sound/midi.h
    engines/zvision/sound/volume_manager.cpp
    engines/zvision/sound/volume_manager.h
    engines/zvision/zvision.cpp


diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index 4814c714a8a..2eda7d7402f 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -43,6 +43,7 @@
 #include "zvision/graphics/effects/light.h"
 #include "zvision/graphics/effects/wave.h"
 #include "zvision/graphics/cursors/cursor_manager.h"
+#include "zvision/sound/volume_manager.h"
 
 namespace ZVision {
 
@@ -102,12 +103,17 @@ bool ActionAssign::execute() {
 // ActionAttenuate
 //////////////////////////////////////////////////////////////////////////////
 
+//TODO - the effects of this seem permanent until the musicnode is deleted; check if they should only be applied on a per-cycle basis!
+
 ActionAttenuate::ActionAttenuate(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
 	_key = 0;
 	_attenuation = 0;
 
 	sscanf(line.c_str(), "%u, %d", &_key, &_attenuation);
+  debug(2,"Created Action: Attenuate, slotKey %d", _slotKey);
+  debug(2,"Attenuate script: %s", line.c_str());
+  debug(2,"Attenuate parameters: key1 %d, attenuation %d", _key, _attenuation);
 }
 
 bool ActionAttenuate::execute() {
@@ -115,7 +121,7 @@ bool ActionAttenuate::execute() {
 	ScriptingEffect *fx = _scriptManager->getSideFX(_key);
 	if (fx && fx->getType() == ScriptingEffect::SCRIPTING_EFFECT_AUDIO) {
 		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
-		mus->setVolume(255 * (10000 - abs(_attenuation)) / 10000 );
+	mus->setVolume((10000 - abs(_attenuation)) / 100 ); //TODO - verify that this is working correctly.
 	}
 	return true;
 }
@@ -158,19 +164,20 @@ ActionCrossfade::ActionCrossfade(ZVision *engine, int32 slotKey, const Common::S
 	sscanf(line.c_str(),
 	       "%u %u %d %d %d %d %d",
 	       &_keyOne, &_keyTwo, &_oneStartVolume, &_twoStartVolume, &_oneEndVolume, &_twoEndVolume, &_timeInMillis);
-  debug(2,"Created Action: CrossFade, slotKey %d", slotKey);
+  debug(2,"Created Action: CrossFade, slotKey %d", _slotKey);
   debug(2,"Crossfade script: %s", line.c_str());
+  debug(2,"Crossfade parameters: key1 %u, key2 %u, startVol1 %d, startVol2 %d, endVol1 %d, endVol2 %d, time %dms", _keyOne, _keyTwo, _oneStartVolume, _twoStartVolume, _oneEndVolume, _twoEndVolume, _timeInMillis);
 }
 
 bool ActionCrossfade::execute() {
-  debug(2,"Executing Action: CrossFade");
+  debug(2,"Executing Action: CrossFade, slotkey %d", _slotKey);
 	if (_keyOne) {
 		ScriptingEffect *fx = _scriptManager->getSideFX(_keyOne);
 		if (fx && fx->getType() == ScriptingEffect::SCRIPTING_EFFECT_AUDIO) {
 			MusicNodeBASE *mus = (MusicNodeBASE *)fx;
 			if (_oneStartVolume >= 0)
-				mus->setVolume((_oneStartVolume * 255) / 100);
-			mus->setFade(_timeInMillis, (_oneEndVolume * 255) / 100);
+				mus->setVolume(_oneStartVolume);
+			mus->setFade(_timeInMillis, _oneEndVolume);
 		}
 	}
 	if (_keyTwo) {
@@ -178,8 +185,8 @@ bool ActionCrossfade::execute() {
 		if (fx && fx->getType() == ScriptingEffect::SCRIPTING_EFFECT_AUDIO) {
 			MusicNodeBASE *mus = (MusicNodeBASE *)fx;
 			if (_twoStartVolume >= 0)
-				mus->setVolume((_twoStartVolume * 255) / 100);
-			mus->setFade(_timeInMillis, (_twoEndVolume * 255) / 100);
+				mus->setVolume(_twoStartVolume);
+			mus->setFade(_timeInMillis, _twoEndVolume);
 		}
 	}
 	return true;
@@ -282,7 +289,7 @@ ActionDissolve::ActionDissolve(ZVision *engine) :
 
 bool ActionDissolve::execute() {
 	// Cause black screen flick
-	// _engine->getRenderManager()->bkgFill(0, 0, 0);
+	// _engine->getRenderManager()->bkgFill(0, 0, 0); //TODO - reimplement this?  Find out where it is used first.
 	return true;
 }
 
@@ -476,37 +483,35 @@ ActionMusic::ActionMusic(ZVision *engine, int32 slotKey, const Common::String &l
 	// Zork: Nemesis, for the flute and piano puzzles (tj4e and ve6f, as well
 	// as vr)
 	switch(type) {
-    case 4: {
+    case 4:
 		  _midi = true;
 		  int note;
 		  int prog;
 		  sscanf(line.c_str(), "%u %d %d %14s", &type, &prog, &note, volumeBuffer);
-		  _volume = new ValueSlot(_scriptManager, volumeBuffer);
 		  _note = note;
 		  _prog = prog;
 		  break;
-	  }
-	  default: {
+	  default:
 		  _midi = false;
 		  _fileName = Common::String(fileNameBuffer);
 		  _loop = loop == 1 ? true : false;
-		  if (volumeBuffer[0] != '[' && atoi(volumeBuffer) > 100) {
-			  // I thought I saw a case like this in Zork Nemesis, so
-			  // let's guard against it.
-			  warning("ActionMusic: Adjusting volume for %s from %s to 100", _fileName.toString().c_str(), volumeBuffer);
-			  Common::strcpy_s(volumeBuffer, "100");
-		  }
-		  _volume = new ValueSlot(_scriptManager, volumeBuffer);
 		  break;
-	  }
   }
+  if (volumeBuffer[0] != '[' && atoi(volumeBuffer) > 100) {
+	  // I thought I saw a case like this in Zork Nemesis, so
+	  // let's guard against it.
+	  warning("\tActionMusic: Adjusting volume for %s from %s to 100", _fileName.toString().c_str(), volumeBuffer);
+	  Common::strcpy_s(volumeBuffer, "100");
+  }
+  _volume = new ValueSlot(_scriptManager, volumeBuffer);
+
 	// WORKAROUND for a script bug in Zork Nemesis, rooms mq70/mq80.
 	// Fixes an edge case where the player goes to the dark room with the grue
 	// without holding a torch, and then quickly runs away before the grue's
 	// sound effect finishes. Fixes script bug #6794.
 	if (engine->getGameId() == GID_NEMESIS && _slotKey == 14822 && _scriptManager->getStateValue(_slotKey) == 2)
 		_scriptManager->setStateValue(_slotKey, 0);
-  //debug(2,"Created Action: Music, slotKey %d, type %u, file %24s, note %u, volume %14s", _slotKey, type, fileNameBuffer);
+  debug(2,"Created Action: Music, slotKey %d, type %u, file %24s, note %u, volume %d", _slotKey, type, fileNameBuffer, _note, _volume->getValue());
   debug(2,"Music script: %s", line.c_str());
 }
 
@@ -517,19 +522,18 @@ ActionMusic::~ActionMusic() {
 }
 
 bool ActionMusic::execute() {
-  debug(2,"Executing Action: Music, slotKey %d", _slotKey);
+  debug(2,"Executing Action: Music, slotKey %d, volume %d", _slotKey, _volume->getValue());
 	if (_scriptManager->getSideFX(_slotKey)) {
 		_scriptManager->killSideFx(_slotKey);
 		_scriptManager->setStateValue(_slotKey, 2);
 	}
 	uint volume = _volume->getValue();
-	if (_midi) {
+	if (_midi)
 		_scriptManager->addSideFX(new MusicMidiNode(_engine, _slotKey, _prog, _note, volume));
-	} else {
+	else {
 		if (!_engine->getSearchManager()->hasFile(_fileName))
 			return true;
-		// Volume in the script files is mapped to [0, 100], but the ScummVM mixer uses [0, 255]
-		_scriptManager->addSideFX(new MusicNode(_engine, _slotKey, _fileName, _loop, volume * 255 / 100));
+    _scriptManager->addSideFX(new MusicNode(_engine, _slotKey, _fileName, _loop, volume));
 	}
 	return true;
 }
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 08907ef7446..5c6077a57d5 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -40,11 +40,29 @@
 
 namespace ZVision {
 
+void MusicNodeBASE::setAzimuth(Math::Angle azimuth) {
+  _azimuth = azimuth;
+  _balance = (int)(127*_azimuth.getSine());
+	updateMixer();
+}
+
+void MusicNodeBASE::setBalance(int8 balance) {
+  _balance = balance;
+  _azimuth.setDegrees(0);
+	updateMixer();
+}
+
+void MusicNodeBASE::updateMixer() {
+  uint16 tmpVol = _volume * fadeGain;
+  tmpVol /= 0xFF;
+  volumeOut = _engine->getVolumeManager()->convert(tmpVol, _azimuth);  //Apply volume profile and then attenuate according to azimuth
+  outputMixer();
+}
+
 MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool loop, uint8 volume)
 	: MusicNodeBASE(engine, key, SCRIPTING_EFFECT_AUDIO) {
 	_loop = loop;
 	_volume = volume;
-	_deltaVolume = 0;
 	_balance = 0;
 	_crossfade = false;
 	_crossfadeTarget = 0;
@@ -57,25 +75,20 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 
 	if (filename.baseName().contains(".wav")) {
 		Common::File *file = new Common::File();
-		if (_engine->getSearchManager()->openFile(*file, filename)) {
+		if (_engine->getSearchManager()->openFile(*file, filename))
 			audioStream = Audio::makeWAVStream(file, DisposeAfterUse::YES);
-		}
-	} else {
+	} 
+	else
 		audioStream = makeRawZorkStream(filename, _engine);
-	}
-
+		
 	if (audioStream) {
 		_stereo = audioStream->isStereo();
-
 		if (_loop) {
 			Audio::LoopingAudioStream *loopingAudioStream = new Audio::LoopingAudioStream(audioStream, 0, DisposeAfterUse::YES);
-//			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, loopingAudioStream, -1, _volume /*dbMapLinear[_volume]*/);
-			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, loopingAudioStream, -1, _engine->getVolumeManager()->convert(_volume));
-		} else {
-//			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, audioStream, -1, _volume /*dbMapLinear[_volume]*/);
-			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, audioStream, -1, _engine->getVolumeManager()->convert(_volume));
-		}
-
+			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, loopingAudioStream, -1, _volume);
+		} 
+		else
+			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, audioStream, -1, _volume);
 		if (_key != StateKey_NotSet)
 			_engine->getScriptManager()->setStateValue(_key, 1);
 
@@ -85,11 +98,11 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 		subname.setChar('u', subname.size() - 2);
 		subname.setChar('b', subname.size() - 1);
 
-
 		Common::Path subpath(filename.getParent().appendComponent(subname));
 		if (_engine->getSearchManager()->hasFile(subpath))
 		  _sub = _engine->getSubtitleManager()->create(subpath);
 		_loaded = true;
+		updateMixer();
 	}
 }
 
@@ -103,14 +116,9 @@ MusicNode::~MusicNode() {
 	debug(2, "MusicNode: %d destroyed", _key);
 }
 
-void MusicNode::setDeltaVolume(uint8 volume) {
-	_deltaVolume = volume;
-	setVolume(_volume);
-}
-
-void MusicNode::setBalance(int8 balance) {
-	_balance = balance;
+void MusicNode::outputMixer() {
 	_engine->_mixer->setChannelBalance(_handle, _balance);
+	_engine->_mixer->setChannelVolume(_handle, volumeOut);
 }
 
 void MusicNode::setFade(int32 time, uint8 target) {
@@ -124,7 +132,6 @@ bool MusicNode::process(uint32 deltaTimeInMillis) {
 		return stop();
 	else {
 		uint8 _newvol = _volume;
-
 		if (_crossfade) {
 			if (_crossfadeTime > 0) {
 				if ((int32)deltaTimeInMillis > _crossfadeTime)
@@ -136,7 +143,6 @@ bool MusicNode::process(uint32 deltaTimeInMillis) {
 				_newvol = _crossfadeTarget;
 			}
 		}
-
 		if (_volume != _newvol)
 			setVolume(_newvol);
 		if (_sub && _engine->getScriptManager()->getStateValue(StateKey_Subtitles) == 1)
@@ -146,29 +152,17 @@ bool MusicNode::process(uint32 deltaTimeInMillis) {
 }
 
 void MusicNode::setVolume(uint8 newVolume) {
-	if (!_loaded)
-		return;
-
-	_volume = newVolume;
-
-	if (_deltaVolume >= _volume)
-		_engine->_mixer->setChannelVolume(_handle, 0);
-	else
-//		_engine->_mixer->setChannelVolume(_handle, _volume - _deltaVolume /*dbMapLinear[_volume - _deltaVolume]*/);
-    _engine->_mixer->setChannelVolume(_handle, _engine->getVolumeManager()->convert(_volume - _deltaVolume));
-}
-
-uint8 MusicNode::getVolume() {
-	return _volume;
+	if (_loaded) {
+	  _volume = newVolume;
+    updateMixer();
+  }
 }
 
 PanTrackNode::PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos)
 	: ScriptingEffect(engine, key, SCRIPTING_EFFECT_PANTRACK) {
 	_slot = slot;
 	sourcePos = pos;
-
-	// Try to set pan value for music node immediately
-	process(0);
+	process(0); 	// Try to set pan value for music node immediately
 }
 
 PanTrackNode::~PanTrackNode() {
@@ -179,11 +173,10 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 	ScriptingEffect *fx = scriptManager->getSideFX(_slot);
 	if (fx && fx->getType() == SCRIPTING_EFFECT_AUDIO) {
 		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
-
 		int viewPos = scriptManager->getStateValue(StateKey_ViewPos);
 		int16 _width = _engine->getRenderManager()->getBkgSize().x;
-		int16 _halfWidth = _width / 2;
-		int16 _quarterWidth = _width / 4;
+//		int16 _halfWidth = _width / 2;
+//		int16 _quarterWidth = _width / 4;
 
 		int deltaPos = 0;
 		if (viewPos <= sourcePos)
@@ -194,13 +187,7 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
     //deltaPos is sound source position relative to player, clockwise from centre of camera axis to front when viewed top-down
 //*/
     //NEW SYSTEM
-    Math::Angle azimuth = 360*deltaPos/_width;
-    int8 balance = (int)127*azimuth.getSine();
-    uint8 volume = mus->getVolume();
-    uint8 deltaVol = volume - _engine->getVolumeManager()->convert(volume, kVolumeLinear, azimuth);
-		mus->setBalance(balance);  
-		mus->setDeltaVolume(deltaVol);
-		debug(1,"Balance %d, volume %d, deltaVol %d", balance, volume-deltaVol, deltaVol);
+    mus->setAzimuth(Math::Angle(360*deltaPos/_width));
       
 /*/
     //OLD SYSTEM;		
@@ -215,9 +202,6 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 			deltaPos = -_halfWidth - deltaPos;  //Make relative to left centre?
 		}
 
-    //TODO - rework this so that balance correctly shifts back to centre when in rear, and ensure that attenuation in rear is also correct.
-    //Correlate this effort with adjusting the volume curves in VolumeManager.
-
 		// Originally it's value -90...90 but we use -127...127 and therefore 360 replaced by 508
 		// Left = -127, centre = 0, right = +127
 		mus->setBalance( (508 * deltaPos) / _width );
@@ -243,40 +227,29 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 	return false;
 }
 
-MusicMidiNode::MusicMidiNode(ZVision *engine, uint32 key, int8 program, int8 note, int8 volume)
+MusicMidiNode::MusicMidiNode(ZVision *engine, uint32 key, uint8 program, uint8 note, uint8 volume)
 	: MusicNodeBASE(engine, key, SCRIPTING_EFFECT_AUDIO) {
 	_volume = volume;
 	_prog = program;
 	_noteNumber = note;
 	_pan = 0;
-
 	_chan = _engine->getMidiManager()->getFreeChannel();
-
 	if (_chan >= 0) {
-		_engine->getMidiManager()->setVolume(_chan, _volume);
-		_engine->getMidiManager()->setPan(_chan, _pan);
+	  updateMixer();
 		_engine->getMidiManager()->setProgram(_chan, _prog);
 		_engine->getMidiManager()->noteOn(_chan, _noteNumber, _volume);
 	}
-
 	if (_key != StateKey_NotSet)
 		_engine->getScriptManager()->setStateValue(_key, 1);
 }
 
 MusicMidiNode::~MusicMidiNode() {
-	if (_chan >= 0) {
+	if (_chan >= 0)
 		_engine->getMidiManager()->noteOff(_chan);
-	}
 	if (_key != StateKey_NotSet)
 		_engine->getScriptManager()->setStateValue(_key, 2);
 }
 
-void MusicMidiNode::setDeltaVolume(uint8 volume) {
-}
-
-void MusicMidiNode::setBalance(int8 balance) {
-}
-
 void MusicMidiNode::setFade(int32 time, uint8 target) {
 }
 
@@ -286,13 +259,15 @@ bool MusicMidiNode::process(uint32 deltaTimeInMillis) {
 
 void MusicMidiNode::setVolume(uint8 newVolume) {
 	if (_chan >= 0) {
-		_engine->getMidiManager()->setVolume(_chan, newVolume);
+	  _volume = newVolume;
+	  updateMixer();
 	}
-	_volume = newVolume;
 }
 
-uint8 MusicMidiNode::getVolume() {
-	return _volume;
+void MusicMidiNode::outputMixer() {
+	_engine->getMidiManager()->setBalance(_chan, _balance);
+	_engine->getMidiManager()->setPan(_chan, _pan);
+  _engine->getMidiManager()->setVolume(_chan, volumeOut);
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/effects/music_effect.h b/engines/zvision/scripting/effects/music_effect.h
index d535d029d13..257f769c5f8 100644
--- a/engines/zvision/scripting/effects/music_effect.h
+++ b/engines/zvision/scripting/effects/music_effect.h
@@ -25,7 +25,7 @@
 #include "audio/mixer.h"
 #include "zvision/scripting/scripting_effect.h"
 #include "zvision/text/subtitle_manager.h"
-
+#include "zvision/sound/volume_manager.h"
 
 namespace Common {
 class String;
@@ -48,10 +48,19 @@ public:
 	bool process(uint32 deltaTimeInMillis) override = 0;
 
 	virtual void setVolume(uint8 volume) = 0;
-	virtual uint8 getVolume() = 0;
-	virtual void setDeltaVolume(uint8 volume) = 0;
-	virtual void setBalance(int8 balance) = 0;
+	uint8 getVolume() {return _volume;};
 	virtual void setFade(int32 time, uint8 target) = 0;
+	virtual void setBalance(int8 balance);  //NB Overrides effects of setAzimuth()
+	void setAzimuth(Math::Angle azimuth);  //NB Overrides effects of setBalance()
+protected:
+  void updateMixer();
+  virtual void outputMixer() = 0;
+  
+  uint8 _volume = 0;
+	int8 _balance = 0;
+  Math::Angle _azimuth;
+  uint8 fadeGain = 255;  //Linear scale, 255 corresponds to unity gain
+	uint8 volumeOut = 0;
 };
 
 class MusicNode : public MusicNodeBASE {
@@ -67,18 +76,11 @@ public:
 	 * @return                     If true, the node can be deleted after process() finishes
 	 */
 	bool process(uint32 deltaTimeInMillis) override;
-
 	void setVolume(uint8 volume) override;
-	uint8 getVolume() override;
-	void setDeltaVolume(uint8 volume) override;
-	void setBalance(int8 balance) override;
-
 	void setFade(int32 time, uint8 target) override;
 
 private:
-	uint8 _volume;
-	uint8 _deltaVolume;
-	int8 _balance;
+  void outputMixer() override;
 	bool _loop;
 	bool _crossfade;
 	uint8 _crossfadeTarget;
@@ -92,7 +94,7 @@ private:
 // Only used by Zork: Nemesis, for the flute and piano puzzles (tj4e and ve6f, as well as vr)
 class MusicMidiNode : public MusicNodeBASE {
 public:
-	MusicMidiNode(ZVision *engine, uint32 key, int8 program, int8 note, int8 volume);
+	MusicMidiNode(ZVision *engine, uint32 key, uint8 program, uint8 note, uint8 volume);
 	~MusicMidiNode() override;
 
 	/**
@@ -103,20 +105,15 @@ public:
 	 * @return                     If true, the node can be deleted after process() finishes
 	 */
 	bool process(uint32 deltaTimeInMillis) override;
-
 	void setVolume(uint8 volume) override;
-	uint8 getVolume() override;
-	void setDeltaVolume(uint8 volume) override;
-	void setBalance(int8 balance) override;
-
 	void setFade(int32 time, uint8 target) override;
 
 private:
+  void outputMixer() override;
 	int8 _chan;
-	int8 _noteNumber;
+	uint8 _noteNumber;
 	int8 _pan;
-	int8 _volume;
-	int8 _prog;
+	uint8 _prog;
 };
 
 class PanTrackNode : public ScriptingEffect {
diff --git a/engines/zvision/scripting/scr_file_handling.cpp b/engines/zvision/scripting/scr_file_handling.cpp
index 3f1cdf5d1d4..bb4732e309f 100644
--- a/engines/zvision/scripting/scr_file_handling.cpp
+++ b/engines/zvision/scripting/scr_file_handling.cpp
@@ -274,9 +274,7 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 				break;
 
 		if (pos < line.size()) {
-
 			uint startpos = pos + 1;
-
 			for (pos = startpos; pos < line.size(); pos++)
 				if (chrs[pos] == ':' || chrs[pos] == '(')
 					break;
@@ -324,6 +322,7 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 					actionList.push_back(new ActionChangeLocation(_engine, slot, args));
 				} else if (act.matchString("crossfade", true)) {
 					actionList.push_back(new ActionCrossfade(_engine, slot, args));
+//					debug(1,"\tpush.ActionCrossFade, script line: %s", line.c_str());
 				} else if (act.matchString("cursor", true)) {
 					actionList.push_back(new ActionCursor(_engine, slot, args));
 				} else if (act.matchString("debug", true)) {
@@ -354,8 +353,10 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 					actionList.push_back(new ActionMenuBarEnable(_engine, slot, args));
 				} else if (act.matchString("music", true)) {
 					actionList.push_back(new ActionMusic(_engine, slot, args, false));
+//					debug(1,"\tpush.ActionMusic, script line: %s", line.c_str());
 				} else if (act.matchString("pan_track", true)) {
 					actionList.push_back(new ActionPanTrack(_engine, slot, args));
+//					debug(1,"\tpush.ActionPanTrack, script line: %s", line.c_str());
 				} else if (act.matchString("playpreload", true)) {
 					actionList.push_back(new ActionPlayPreloadAnimation(_engine, slot, args));
 				} else if (act.matchString("preferences", true)) {
diff --git a/engines/zvision/sound/midi.cpp b/engines/zvision/sound/midi.cpp
index 0b26ec329af..b2135e4548b 100644
--- a/engines/zvision/sound/midi.cpp
+++ b/engines/zvision/sound/midi.cpp
@@ -53,50 +53,65 @@ MidiManager::~MidiManager() {
 	delete _driver;
 }
 
+void MidiManager::send(uint8 status, uint8 data1, uint8 data2) {
+  assert(status & 0x80 && "Malformed MIDI status byte");
+  assert(!(data1 & 0x80) && "Malformed MIDI data byte 1");
+  assert(!(data2 & 0x80) && "Malformed MIDI data byte 2");
+  _driver->send(status | (data1 << 8) | (data2 << 16) );
+}
+
 void MidiManager::stop() {
-	for (int8 i = 0; i < 16; i++)
-		if (activeChannels[i].playing)
-			noteOff(i);
+	for (uint8 i = 0; i < 16; i++)
+		noteOff(i);
 }
 
-void MidiManager::noteOn(int8 channel, int8 note, int8 velocity) {
+void MidiManager::noteOn(uint8 channel, uint8 note, uint8 velocity) {
 	assert(channel <= 15);
 	activeChannels[channel].playing = true;
 	activeChannels[channel].note = note;
-	_driver->send(channel | (velocity << 16) | (note << 8) | 0x90);
+  send(0x90 | channel, note, velocity);
 	debug(1,"MIDI note on, channel %d, note %d, velocity %d", channel, note, velocity);
 }
 
-void MidiManager::noteOff(int8 channel) {
+void MidiManager::noteOff(uint8 channel) {
 	assert(channel <= 15);
-
 	if (activeChannels[channel].playing) {
 		activeChannels[channel].playing = false;
-		_driver->send(channel | (activeChannels[channel].note << 8) | 0x80);
+		send(0x80 | channel, activeChannels[channel].note);
 	}
 }
 
 int8 MidiManager::getFreeChannel() {
   uint8 start = mt32workaround ? 1 : 0; //MT-32 emulator driver currently fails to play anything when sent notes on channel 0.  Quick & dirty fix, since we only need a few notes for Nemesis music puzzles.  Inform maintainer of MT-32 emulator code of bug for proper fix in the future & then remove this nasty hack once that's sorted out.
-	for (int8 i = start; i < 16; i++)
+	for (uint8 i = start; i < 16; i++)
 		if (!activeChannels[i].playing)
 			return i;
 	return -1;
 }
 
-void MidiManager::setPan(int8 channel, int8 pan) {
+void MidiManager::setVolume(uint8 channel, uint8 volume) {
+	assert(channel <= 15);
+	debug(1,"MIDI volume out %d", volume >> 1);
+  send(0xB0 | channel, 0x07, volume >> 1);
+}
+
+void MidiManager::setBalance(uint8 channel, int8 balance) {
 	assert(channel <= 15);
-	_driver->send(channel | (pan << 16) | 0xAB0);
+	uint8 _balance = (uint8)(balance + 128);
+	debug(1,"MIDI balance out %d", _balance >> 1);
+  send(0xB0 | channel, 0x08, _balance >> 1);
 }
 
-void MidiManager::setVolume(int8 channel, int8 volume) {
+void MidiManager::setPan(uint8 channel, int8 pan) {
 	assert(channel <= 15);
-	_driver->send(channel | (volume << 16) | 0x7B0);
+	uint8 _pan = (uint8)(pan + 128);
+	debug(1,"MIDI pan in %d, out %d", pan, _pan >> 1);
+  send(0xB0 | channel, 0x0A, _pan >> 1);
 }
 
-void MidiManager::setProgram(int8 channel, int8 prog) {
+void MidiManager::setProgram(uint8 channel, uint8 prog) {
 	assert(channel <= 15);
-	_driver->send(channel | (prog << 8) | 0xC0);
+  send(0xC0 | channel, prog);
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/sound/midi.h b/engines/zvision/sound/midi.h
index 25dd55bbc05..774a4534dba 100644
--- a/engines/zvision/sound/midi.h
+++ b/engines/zvision/sound/midi.h
@@ -32,13 +32,14 @@ public:
 	~MidiManager();
 
 	void stop();
-	void noteOn(int8 channel, int8 noteNumber, int8 velocity);
-	void noteOff(int8 channel);
-	void setPan(int8 channel, int8 pan);
-	void setVolume(int8 channel, int8 volume);
-	void setProgram(int8 channel, int8 prog);
+	void noteOn(uint8 channel, uint8 noteNumber, uint8 velocity);
+	void noteOff(uint8 channel);
+	void setVolume(uint8 channel, uint8 volume);
+	void setBalance(uint8 channel, int8 balance);
+	void setPan(uint8 channel, int8 pan);
+	void setProgram(uint8 channel, uint8 prog);
 
-	int8 getFreeChannel();
+	int8 getFreeChannel();  //Negative if none available
 	bool isAvailable() {
 	  return available;
 	};
@@ -48,9 +49,10 @@ protected:
   bool mt32workaround = false;
 	struct chan {
 		bool playing;
-		int8 note;
+		uint8 note;
 		chan() : playing(false), note(0) {};
 	};
+  void send(uint8 status, uint8 data1=0x00, uint8 data2=0x00);
   uint8 startChannel = 0;
   uint8 maxChannels = 16;
 	MidiDriver *_driver;
diff --git a/engines/zvision/sound/volume_manager.cpp b/engines/zvision/sound/volume_manager.cpp
index ebb3bdddb1a..dbe2a814506 100644
--- a/engines/zvision/sound/volume_manager.cpp
+++ b/engines/zvision/sound/volume_manager.cpp
@@ -105,9 +105,16 @@ static constexpr uint8 logAmplitude[256] = {
 };
 //*/
 
-//Relative absolute amplitude (to 255) of a sound source as it circles the listener's head from front to rear, due to ear pinna shape.
-//Maximum attenuation -5dB when fully to rear.
-//Ideally should be applied AFTER volume profile is applied to script files.
+/*
+Estimated relative amplitude of a point sound source as it circles the listener's head from front to rear, due to ear pinna shape.
+Maximum attenuation -5dB when fully to rear.  Seems to give a reasonably realistic effect when tested on the Nemesis cloister fountain.
+Ideally should be applied AFTER volume profile is applied to script files.
+Generating function:
+  for 0 < theta < 90, amp = 255;
+  for 90 < theta < 180, amp = 255*10^(1-(cos(2*(theta-90))/4))
+  where theta is the azimuth, in degrees, of the sound source relative to straight ahead of listener
+Source: Own work; crude and naive model that is probably not remotely scientifically accurate, but good enough for a 30-year-old game.
+*/
 static constexpr uint8 directionalAmplitude[181] = {
 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
@@ -136,31 +143,17 @@ uint8 VolumeManager::convert(uint8 inputValue, Math::Angle azimuth) {
 };
 
 uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode, Math::Angle azimuth) {
-  Math::Angle _azimuth = azimuth;
-  uint8 index = abs(round(_azimuth.getDegrees(-180)));
-  switch(mode) {
-    case kVolumeLogPower:
-      break;
-    case kVolumeLogAmplitude:
-      break;
-    case kVolumePowerLaw:
-      break;
-    case kVolumeParabolic:
-      break;
-    case kVolumeCubic:
-      break;
-    case kVolumeQuartic:
-      break;
-    case kVolumeLinear:
-    default:
-      break;
-  }
-  uint8 deltaVolume = (255 - directionalAmplitude[index])/directionalDivisor;
-  return convert(inputValue*(255-deltaVolume)/255, mode);
+  uint8 index = abs(round(azimuth.getDegrees(-180)));
+  uint16 output = convert(inputValue, mode);
+  output *= directionalAmplitude[index];
+  output /= 255;
+  debug(1,"Azimuth-scaled converted output %d", output);
+  return output;
 };
 
 uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode) {
-  uint8 scaledInput = inputValue * 255 / internalScale;
+  uint16 scaledInput = inputValue * 255;
+  scaledInput /= scriptScale;
   uint8 output = 0;
   switch(mode) {
     case kVolumeLogPower:
@@ -186,7 +179,7 @@ uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode) {
       output = scaledInput;
       break;
   }
-  debug(1,"Script volume %d, converted output %d", scaledInput, output);
+  debug(1,"Scripted volume %d, scaled volume %d, converted output %d", inputValue, scaledInput, output);
   return output;
 };
 
diff --git a/engines/zvision/sound/volume_manager.h b/engines/zvision/sound/volume_manager.h
index 8631039ef3d..0cc558860b0 100644
--- a/engines/zvision/sound/volume_manager.h
+++ b/engines/zvision/sound/volume_manager.h
@@ -48,8 +48,7 @@ public:
   uint8 convert(uint8 inputValue, Math::Angle azimuth);
   uint8 convert(uint8 inputValue, volumeScaling mode, Math::Angle azimuth);
 private:
-  uint8 directionalDivisor = 1; //Used to lessen effect of directional audio to match directional effect strength to different volume scaling profiles.
-  uint internalScale = 255;
+  uint scriptScale = 100; //Z-Vision scripts internally use a volume scale of 0-100; ScummVM uses a scale of 0-255.
   volumeScaling _mode = kVolumeLinear;
 };
 
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index a3fabbb61c5..4b9ef72fdb7 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -212,7 +212,7 @@ void ZVision::initialize() {
       _renderManager = new RenderManager(this, nemesisLayout, _resourcePixelFormat, _doubleFPS, _widescreen);
 	    _menu = new MenuNemesis(this, _renderManager->getMenuArea());
       _subtitleManager = new SubtitleManager(this, nemesisLayout, _resourcePixelFormat, _doubleFPS);
-	    _volumeManager = new VolumeManager(kVolumeLinear);
+	    _volumeManager = new VolumeManager(kVolumePowerLaw);
 	    break;
     case GID_GRANDINQUISITOR:
       _renderManager = new RenderManager(this, zgiLayout, _resourcePixelFormat, _doubleFPS, _widescreen);


Commit: 99f72d515ee3defc8d3c7f0e9e0e061073af1080
    https://github.com/scummvm/scummvm/commit/99f72d515ee3defc8d3c7f0e9e0e061073af1080
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:56+02:00

Commit Message:
ZVISION: Modified ActionMusic::execute() behaviour to eliminate pan_track bug.
Panoramic sound now works correctly whether loading from a saved game or entering a new area.
Enable "3D sound" controls (not genuine Qsound; enables directional audio and non-linear volume)

Changed paths:
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/sound/volume_manager.cpp
    engines/zvision/sound/volume_manager.h
    engines/zvision/zvision.cpp


diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index 2eda7d7402f..df76bfad158 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -83,7 +83,6 @@ bool ActionAdd::execute() {
 ActionAssign::ActionAssign(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
 	_key = 0;
-
 	char buf[64];
 	memset(buf, 0, 64);
 	sscanf(line.c_str(), "%u, %s", &_key, buf);
@@ -511,7 +510,8 @@ ActionMusic::ActionMusic(ZVision *engine, int32 slotKey, const Common::String &l
 	// sound effect finishes. Fixes script bug #6794.
 	if (engine->getGameId() == GID_NEMESIS && _slotKey == 14822 && _scriptManager->getStateValue(_slotKey) == 2)
 		_scriptManager->setStateValue(_slotKey, 0);
-  debug(2,"Created Action: Music, slotKey %d, type %u, file %24s, note %u, volume %d", _slotKey, type, fileNameBuffer, _note, _volume->getValue());
+
+  debug(1,"Created Action: Music, slotKey %d, type %u, file %24s, note %u, volume %d", _slotKey, type, fileNameBuffer, _note, _volume->getValue());
   debug(2,"Music script: %s", line.c_str());
 }
 
@@ -522,7 +522,7 @@ ActionMusic::~ActionMusic() {
 }
 
 bool ActionMusic::execute() {
-  debug(2,"Executing Action: Music, slotKey %d, volume %d", _slotKey, _volume->getValue());
+  debug(1,"Executing Action: Music, slotKey %d, volume %d", _slotKey, _volume->getValue());
 	if (_scriptManager->getSideFX(_slotKey)) {
 		_scriptManager->killSideFx(_slotKey);
 		_scriptManager->setStateValue(_slotKey, 2);
@@ -547,15 +547,18 @@ ActionPanTrack::ActionPanTrack(ZVision *engine, int32 slotKey, const Common::Str
 	_pos(0),
 	_musicSlot(0) {
 	sscanf(line.c_str(), "%u %d", &_musicSlot, &_pos);
-  debug(2,"Created Action: PanTrack, musicSlot %u, pos %d", _musicSlot, _pos);
+	if(_scriptManager->getStateValue(_musicSlot) != 2)
+    _scriptManager->setStateValue(_musicSlot, 2); //Pan_track scripts do not always trigger correctly unless this is set!
+  debug(1,"Created Action: PanTrack, slotkey %d, musicSlot %u, pos %d", _slotKey, _musicSlot, _pos);
 }
 
 ActionPanTrack::~ActionPanTrack() {
 	_scriptManager->killSideFx(_slotKey);
+  debug(1,"Destroyed Action: PanTrack, slotkey %d", _slotKey);
 }
 
 bool ActionPanTrack::execute() {
-  debug(2,"Executing Action: PanTrack, musicSlot %u, pos %d", _musicSlot, _pos);
+  debug(1,"Executing Action: PanTrack, slotkey %d, musicSlot %u, pos %d", _slotKey, _musicSlot, _pos);
 	if (_scriptManager->getSideFX(_slotKey))
 		return true;
 	_scriptManager->addSideFX(new PanTrackNode(_engine, _slotKey, _musicSlot, _pos));
@@ -615,7 +618,8 @@ bool ActionPreloadAnimation::execute() {
 	if (!nod) {
 		nod = new AnimationEffect(_engine, _slotKey, _fileName, _mask, _framerate, false);
 		_scriptManager->addSideFX(nod);
-	} else
+	} 
+	else
 		nod->stop();
 	_scriptManager->setStateValue(_slotKey, 2);
 	return true;
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 5c6077a57d5..9cf4f5ed194 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -41,8 +41,10 @@
 namespace ZVision {
 
 void MusicNodeBASE::setAzimuth(Math::Angle azimuth) {
-  _azimuth = azimuth;
-  _balance = (int)(127*_azimuth.getSine());
+  if(_engine->getScriptManager()->getStateValue(StateKey_Qsound) >= 1) {
+    _azimuth = azimuth;
+    _balance = (int)(127*_azimuth.getSine());
+  }
 	updateMixer();
 }
 
@@ -55,7 +57,10 @@ void MusicNodeBASE::setBalance(int8 balance) {
 void MusicNodeBASE::updateMixer() {
   uint16 tmpVol = _volume * fadeGain;
   tmpVol /= 0xFF;
-  volumeOut = _engine->getVolumeManager()->convert(tmpVol, _azimuth);  //Apply volume profile and then attenuate according to azimuth
+  if(_engine->getScriptManager()->getStateValue(StateKey_Qsound) >= 1)
+    volumeOut = _engine->getVolumeManager()->convert(tmpVol, _azimuth);  //Apply volume profile and then attenuate according to azimuth
+  else
+    volumeOut = _engine->getVolumeManager()->convert(tmpVol, kVolumeLinear);  //Apply linear volume profile and ignore azimuth
   outputMixer();
 }
 
@@ -86,11 +91,13 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 		if (_loop) {
 			Audio::LoopingAudioStream *loopingAudioStream = new Audio::LoopingAudioStream(audioStream, 0, DisposeAfterUse::YES);
 			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, loopingAudioStream, -1, _volume);
-		} 
+		}
 		else
 			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, audioStream, -1, _volume);
-		if (_key != StateKey_NotSet)
+		if (_key != StateKey_NotSet) {
+		  debug(1,"setting musicnode state value to 1");
 			_engine->getScriptManager()->setStateValue(_key, 1);
+		}
 
 		// Change filename.raw into filename.sub
 		Common::String subname = filename.baseName();
@@ -104,16 +111,19 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 		_loaded = true;
 		updateMixer();
 	}
+	debug(1, "MusicNode: %d created", _key);
 }
 
 MusicNode::~MusicNode() {
 	if (_loaded)
 		_engine->_mixer->stopHandle(_handle);
-	if (_key != StateKey_NotSet)
+	if (_key != StateKey_NotSet) {
 		_engine->getScriptManager()->setStateValue(_key, 2);
+		  debug(1,"setting musicnode state value to 2");
+		}
 	if (_sub)
 		_engine->getSubtitleManager()->destroy(_sub);
-	debug(2, "MusicNode: %d destroyed", _key);
+	debug(1, "MusicNode: %d destroyed", _key);
 }
 
 void MusicNode::outputMixer() {
@@ -158,6 +168,7 @@ void MusicNode::setVolume(uint8 newVolume) {
   }
 }
 
+
 PanTrackNode::PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos)
 	: ScriptingEffect(engine, key, SCRIPTING_EFFECT_PANTRACK) {
 	_slot = slot;
@@ -183,7 +194,7 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 			deltaPos = sourcePos - viewPos;
 		else
 			deltaPos = sourcePos - viewPos + _width;
-		debug(1,"soundPos: %d, viewPos: %d, deltaPos: %d, width: %d", sourcePos, viewPos, deltaPos, _width);
+		debug(3,"soundPos: %d, viewPos: %d, deltaPos: %d, width: %d", sourcePos, viewPos, deltaPos, _width);
     //deltaPos is sound source position relative to player, clockwise from centre of camera axis to front when viewed top-down
 //*/
     //NEW SYSTEM
diff --git a/engines/zvision/sound/volume_manager.cpp b/engines/zvision/sound/volume_manager.cpp
index dbe2a814506..dcb50702806 100644
--- a/engines/zvision/sound/volume_manager.cpp
+++ b/engines/zvision/sound/volume_manager.cpp
@@ -20,6 +20,7 @@
  */
 
 #include "zvision/sound/volume_manager.h"
+#include "zvision/scripting/script_manager.h"
 #include "common/debug.h"
 
 namespace ZVision {
@@ -130,7 +131,8 @@ static constexpr uint8 directionalAmplitude[181] = {
  81, 81, 81, 81, 81
 };
 
-VolumeManager::VolumeManager(volumeScaling mode) :
+VolumeManager::VolumeManager(ZVision *engine, volumeScaling mode) :
+  _engine(engine),
   _mode(mode) {
 };
   
@@ -143,11 +145,11 @@ uint8 VolumeManager::convert(uint8 inputValue, Math::Angle azimuth) {
 };
 
 uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode, Math::Angle azimuth) {
-  uint8 index = abs(round(azimuth.getDegrees(-180)));
   uint16 output = convert(inputValue, mode);
+  uint8 index = abs(round(azimuth.getDegrees(-180)));
   output *= directionalAmplitude[index];
   output /= 255;
-  debug(1,"Azimuth-scaled converted output %d", output);
+  debug(2,"Azimuth-scaled converted output %d", output);
   return output;
 };
 
@@ -179,7 +181,7 @@ uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode) {
       output = scaledInput;
       break;
   }
-  debug(1,"Scripted volume %d, scaled volume %d, converted output %d", inputValue, scaledInput, output);
+  debug(2,"Scripted volume %d, scaled volume %d, converted output %d", inputValue, scaledInput, output);
   return output;
 };
 
diff --git a/engines/zvision/sound/volume_manager.h b/engines/zvision/sound/volume_manager.h
index 0cc558860b0..bdc95446e28 100644
--- a/engines/zvision/sound/volume_manager.h
+++ b/engines/zvision/sound/volume_manager.h
@@ -21,6 +21,7 @@
 
 #include "common/scummsys.h"
 #include "math/angle.h"
+#include "zvision/zvision.h"
 
 #ifndef ZVISION_VOLUME_MANAGER
 #define ZVISION_VOLUME_MANAGER
@@ -39,7 +40,7 @@ enum volumeScaling {
 
 class VolumeManager {
 public:
-  VolumeManager(volumeScaling mode);
+  VolumeManager(ZVision *engine, volumeScaling mode);
   ~VolumeManager() {};
   volumeScaling getMode() {return _mode;};
   void setMode(volumeScaling mode) {_mode = mode;};
@@ -48,6 +49,7 @@ public:
   uint8 convert(uint8 inputValue, Math::Angle azimuth);
   uint8 convert(uint8 inputValue, volumeScaling mode, Math::Angle azimuth);
 private:
+	ZVision *_engine;
   uint scriptScale = 100; //Z-Vision scripts internally use a volume scale of 0-100; ScummVM uses a scale of 0-255.
   volumeScaling _mode = kVolumeLinear;
 };
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index 4b9ef72fdb7..e9318d3d693 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -70,10 +70,10 @@ struct zvisionIniSettings {
 	{"countrycode", StateKey_CountryCode, 0, false, false},	// always 0 = US, subtitles are shown for codes 0 - 4, unused
 	{"lineskipvideo", StateKey_VideoLineSkip, 0, false, false},	// video line skip, 0 = default, 1 = always, 2 = pixel double when possible, unused
 	{"installlevel", StateKey_InstallLevel, 0, false, false},	// 0 = full, checked by universe.scr
-	{"highquality", StateKey_HighQuality, -1, true, false},	// high panorama quality, unused
-	{"qsoundenabled", StateKey_Qsound, -1, true, false},	// 1 = enable QSound - TODO: not supported yet
 	{"debugcheats", StateKey_DebugCheats, -1, true, false},	// always start with the GOxxxx cheat enabled
 	// Editable settings
+	{"highquality", StateKey_HighQuality, -1, true, false},	// high panorama quality
+	{"qsoundenabled", StateKey_Qsound, -1, true, false},	// 1 = enable generic directional audio and non-linear volume scaling.  Genuine Qsound is copyright & unlikely to be implemented.
 	{"keyboardturnspeed", StateKey_KbdRotateSpeed, 5, false, true},
 	{"panarotatespeed", StateKey_RotateSpeed, 540, false, true},	// checked by universe.scr
 	{"noanimwhileturning", StateKey_NoTurnAnim, -1, false, true},	// toggle playing animations during pana rotation
@@ -181,16 +181,21 @@ void ZVision::initialize() {
 	_searchManager = new SearchManager(ConfMan.getPath("path"), 6);
 	_searchManager->addDir("FONTS");
 	_searchManager->addDir("addon");
-	if (getGameId() == GID_GRANDINQUISITOR) {
-		if (!_searchManager->loadZix("INQUIS.ZIX"))
-			error("Unable to load file INQUIS.ZIX");
-	} 
-	else if (getGameId() == GID_NEMESIS) {
-		if (!_searchManager->loadZix("NEMESIS.ZIX")) {
-			// The game might not be installed, try MEDIUM.ZIX instead
-			if (!_searchManager->loadZix("ZNEMSCR/MEDIUM.ZIX"))
-				error("Unable to load the file ZNEMSCR/MEDIUM.ZIX");
-		}
+	switch(getGameId()) {
+	  case GID_GRANDINQUISITOR:
+		  if (!_searchManager->loadZix("INQUIS.ZIX"))
+			  error("Unable to load file INQUIS.ZIX");	  
+	    break;
+    case GID_NEMESIS:
+		  if (!_searchManager->loadZix("NEMESIS.ZIX"))
+			  // The game might not be installed, try MEDIUM.ZIX instead
+			  if (!_searchManager->loadZix("ZNEMSCR/MEDIUM.ZIX"))
+				  error("Unable to load the file ZNEMSCR/MEDIUM.ZIX");
+      break;
+	  case GID_NONE:
+    default:   
+  		error("Unknown/unspecified GameId");
+	    break;
 	}
 	
 	//Graphics
@@ -212,13 +217,13 @@ void ZVision::initialize() {
       _renderManager = new RenderManager(this, nemesisLayout, _resourcePixelFormat, _doubleFPS, _widescreen);
 	    _menu = new MenuNemesis(this, _renderManager->getMenuArea());
       _subtitleManager = new SubtitleManager(this, nemesisLayout, _resourcePixelFormat, _doubleFPS);
-	    _volumeManager = new VolumeManager(kVolumePowerLaw);
+	    _volumeManager = new VolumeManager(this, kVolumePowerLaw);
 	    break;
     case GID_GRANDINQUISITOR:
       _renderManager = new RenderManager(this, zgiLayout, _resourcePixelFormat, _doubleFPS, _widescreen);
 		  _menu = new MenuZGI(this, _renderManager->getMenuArea());
       _subtitleManager = new SubtitleManager(this, zgiLayout, _resourcePixelFormat, _doubleFPS);
-	    _volumeManager = new VolumeManager(kVolumeLogAmplitude);
+	    _volumeManager = new VolumeManager(this, kVolumeLogAmplitude);
 		  break;
 	  case GID_NONE:
 	  default:


Commit: bffc3012f9a441942b443ee2c9fa938fa6a40221
    https://github.com/scummvm/scummvm/commit/bffc3012f9a441942b443ee2c9fa938fa6a40221
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:56+02:00

Commit Message:
ZVISION: Code cleanup.  Additional code comments.

Changed paths:
    engines/zvision/core/events.cpp
    engines/zvision/file/save_manager.cpp
    engines/zvision/scripting/effects/music_effect.h
    engines/zvision/scripting/scr_file_handling.cpp
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/scripting/script_manager.h
    engines/zvision/video/rlf_decoder.cpp


diff --git a/engines/zvision/core/events.cpp b/engines/zvision/core/events.cpp
index 0ebe32bc0ac..d7eafc9d13e 100644
--- a/engines/zvision/core/events.cpp
+++ b/engines/zvision/core/events.cpp
@@ -44,20 +44,16 @@ namespace ZVision {
 void ZVision::pushKeyToCheatBuf(uint8 key) {
 	for (int i = 0; i < KEYBUF_SIZE - 1; i++)
 		_cheatBuffer[i] = _cheatBuffer[i + 1];
-
 	_cheatBuffer[KEYBUF_SIZE - 1] = key;
 }
 
 bool ZVision::checkCode(const char *code) {
 	int codeLen = strlen(code);
-
 	if (codeLen > KEYBUF_SIZE)
 		return false;
-
 	for (int i = 0; i < codeLen; i++)
 		if (code[i] != _cheatBuffer[KEYBUF_SIZE - codeLen + i] && code[i] != '?')
 			return false;
-
 	return true;
 }
 
@@ -188,7 +184,6 @@ void ZVision::processEvents() {
 			_cursorManager->cursorDown(true);
 			if(!_menu->inMenu() || !_widescreen) {
 			  _scriptManager->setStateValue(StateKey_RMouse, 1);
-
 			  if (getGameId() == GID_NEMESIS)
 				  _scriptManager->inventoryCycle();
 			}
@@ -196,9 +191,8 @@ void ZVision::processEvents() {
 
 		case Common::EVENT_RBUTTONUP:
 			_cursorManager->cursorDown(false);
-			if(!_menu->inMenu() || !_widescreen) {
+			if(!_menu->inMenu() || !_widescreen)
   			_scriptManager->setStateValue(StateKey_RMouse, 0);
-			}
 			break;
 
 		case Common::EVENT_MOUSEMOVE:
@@ -276,9 +270,7 @@ void ZVision::processEvents() {
 
 		case Common::EVENT_KEYDOWN: {
 			uint8 vkKey = getZvisionKey(_event.kbd.keycode);
-
 			_scriptManager->setStateValue(StateKey_KeyPress, vkKey);
-
 			_scriptManager->addEvent(_event);
 			cheatCodes(vkKey);
 		}
diff --git a/engines/zvision/file/save_manager.cpp b/engines/zvision/file/save_manager.cpp
index 21b84017f49..897ba55c052 100644
--- a/engines/zvision/file/save_manager.cpp
+++ b/engines/zvision/file/save_manager.cpp
@@ -111,9 +111,9 @@ void SaveManager::writeSaveGameHeader(Common::OutSaveFile *file, const Common::S
 
 Common::Error SaveManager::loadGame(int slot) {
 	Common::SeekableReadStream *saveFile = NULL;
-	if (slot >= 0) {
+	if (slot >= 0)
 		saveFile = getSlotFile(slot);
-	} else {
+	else {
 		saveFile = _engine->getSearchManager()->openFile("r.svr");
 		if (!saveFile) {
 			Common::File *restoreFile = new Common::File();
@@ -128,9 +128,8 @@ Common::Error SaveManager::loadGame(int slot) {
 		return Common::kPathDoesNotExist;
 	// Read the header
 	SaveGameHeader header;
-	if (!readSaveGameHeader(saveFile, header)) {
+	if (!readSaveGameHeader(saveFile, header))
 		return Common::kUnknownError;
-	}
 	ScriptManager *scriptManager = _engine->getScriptManager();
 	// Update the state table values
 	scriptManager->deserialize(saveFile);
diff --git a/engines/zvision/scripting/effects/music_effect.h b/engines/zvision/scripting/effects/music_effect.h
index 257f769c5f8..5b3011f927f 100644
--- a/engines/zvision/scripting/effects/music_effect.h
+++ b/engines/zvision/scripting/effects/music_effect.h
@@ -120,7 +120,6 @@ class PanTrackNode : public ScriptingEffect {
 public:
 	PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos);
 	~PanTrackNode() override;
-
 	bool process(uint32 deltaTimeInMillis) override;
 
 private:
diff --git a/engines/zvision/scripting/scr_file_handling.cpp b/engines/zvision/scripting/scr_file_handling.cpp
index bb4732e309f..9e7f433db44 100644
--- a/engines/zvision/scripting/scr_file_handling.cpp
+++ b/engines/zvision/scripting/scr_file_handling.cpp
@@ -45,20 +45,15 @@ namespace ZVision {
 
 void ScriptManager::parseScrFile(const Common::Path &fileName, ScriptScope &scope) {
 	Common::File file;
-	if (!_engine->getSearchManager()->openFile(file, fileName)) {
+	if (!_engine->getSearchManager()->openFile(file, fileName))
 		error("Script file not found: %s", fileName.toString().c_str());
-	}
-
 	while (!file.eos()) {
 		Common::String line = file.readLine();
-		if (file.err()) {
+		if (file.err())
 			error("Error parsing scr file: %s", fileName.toString().c_str());
-		}
-
 		trimCommentsAndWhiteSpace(&line);
 		if (line.empty())
 			continue;
-
 		if (line.matchString("puzzle:*", true)) {
 			Puzzle *puzzle = new Puzzle();
 			sscanf(line.c_str(), "puzzle:%u", &(puzzle->key));
@@ -66,8 +61,8 @@ void ScriptManager::parseScrFile(const Common::Path &fileName, ScriptScope &scop
 				setStateValue(puzzle->key, 0);
 			parsePuzzle(puzzle, file);
 			scope.puzzles.push_back(puzzle);
-
-		} else if (line.matchString("control:*", true)) {
+		} 
+		else if (line.matchString("control:*", true)) {
 			Control *ctrl = parseControl(line, file);
 			if (ctrl)
 				scope.controls.push_back(ctrl);
@@ -79,11 +74,10 @@ void ScriptManager::parseScrFile(const Common::Path &fileName, ScriptScope &scop
 void ScriptManager::parsePuzzle(Puzzle *puzzle, Common::SeekableReadStream &stream) {
 	Common::String line = stream.readLine();
 	trimCommentsAndWhiteSpace(&line);
-
 	while (!stream.eos() && !line.contains('}')) {
-		if (line.matchString("criteria {", true)) {
+		if (line.matchString("criteria {", true))
 			parseCriteria(stream, puzzle->criteriaList, puzzle->key);
-		} else if (line.matchString("results {", true)) {
+		else if (line.matchString("results {", true)) {
 			parseResults(stream, puzzle->resultActions);
 
 			// WORKAROUND for a script bug in Zork Nemesis, room ve5e (tuning
@@ -111,14 +105,12 @@ void ScriptManager::parsePuzzle(Puzzle *puzzle, Common::SeekableReadStream &stre
 			// version doesn't have a separate room for the cutscene.
 			else if (_engine->getGameId() == GID_GRANDINQUISITOR && (_engine->getFeatures() & ADGF_DVD) && puzzle->key == 10836)
 				puzzle->resultActions.push_front(new ActionAssign(_engine, 11, "10803, 0"));
-		} else if (line.matchString("flags {", true)) {
+		} 
+		else if (line.matchString("flags {", true))
 			setStateFlag(puzzle->key, parseFlags(stream));
-		}
-
 		line = stream.readLine();
 		trimCommentsAndWhiteSpace(&line);
 	}
-
 	puzzle->addedBySetState = false;
 }
 
@@ -133,45 +125,47 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 		line = stream.readLine();
 		trimCommentsAndWhiteSpace(&line);
 	}
-
 	// Criteria can be empty
-	if (line.contains('}')) {
+	if (line.contains('}'))
 		return false;
-	}
-
 	// Create a new List to hold the CriteriaEntries
 	criteriaList.push_back(Common::List<Puzzle::CriteriaEntry>());
-
-	// WORKAROUND for a script bug in Zork: Nemesis, room td9e (fist puzzle)
-	// Since we patch the script that triggers when manipulating the left fist
-	// (below), we add an additional check for the left fist sound, so that it
-	// doesn't get killed immediately when the left fist animation starts.
-	// Together with the workaround below, it fixes bug #6783.
-	if (_engine->getGameId() == GID_NEMESIS && key == 3594) {
-		Puzzle::CriteriaEntry entry;
-		entry.key = 567;
-		entry.criteriaOperator = Puzzle::NOT_EQUAL_TO;
-		entry.argumentIsAKey = false;
-		entry.argument = 1;
-
-		criteriaList.back().push_back(entry);
-	}
-
-	// WORKAROUND for a script bug in Zork: Grand Inquisitor, room me2j
-	// (Closing the Time Tunnels). When the time tunnel is open the game
-	// shows a close-up of only the tunnel, instead of showing the entire
-	// booth. However, the scripts that draw the lever in its correct
-	// state do not test this flag, causing it to be drawn when it should
-	// not be. This fixes bug #6770.
-	if (_engine->getGameId() == GID_GRANDINQUISITOR && key == 9536) {
-		Puzzle::CriteriaEntry entry;
-		entry.key = 9404; // me2j_time_tunnel_open
-		entry.criteriaOperator = Puzzle::EQUAL_TO;
-		entry.argumentIsAKey = false;
-		entry.argument = 0;
-
-		criteriaList.back().push_back(entry);
-	}
+	
+  switch(_engine->getGameId()) {
+    case GID_NEMESIS:
+	    // WORKAROUND for a script bug in Zork: Nemesis, room td9e (fist puzzle)
+	    // Since we patch the script that triggers when manipulating the left fist
+	    // (below), we add an additional check for the left fist sound, so that it
+	    // doesn't get killed immediately when the left fist animation starts.
+	    // Together with the workaround below, it fixes bug #6783.
+	    if (key == 3594) {
+		    Puzzle::CriteriaEntry entry;
+		    entry.key = 567;
+		    entry.criteriaOperator = Puzzle::NOT_EQUAL_TO;
+		    entry.argumentIsAKey = false;
+		    entry.argument = 1;
+		    criteriaList.back().push_back(entry);
+	    }
+      break;
+    case GID_GRANDINQUISITOR:
+	    // WORKAROUND for a script bug in Zork: Grand Inquisitor, room me2j
+	    // (Closing the Time Tunnels). When the time tunnel is open the game
+	    // shows a close-up of only the tunnel, instead of showing the entire
+	    // booth. However, the scripts that draw the lever in its correct
+	    // state do not test this flag, causing it to be drawn when it should
+	    // not be. This fixes bug #6770.
+	    if (key == 9536) {
+		    Puzzle::CriteriaEntry entry;
+		    entry.key = 9404; // me2j_time_tunnel_open
+		    entry.criteriaOperator = Puzzle::EQUAL_TO;
+		    entry.argumentIsAKey = false;
+		    entry.argument = 0;
+		    criteriaList.back().push_back(entry);
+	    }
+      break;
+    default:
+      break;
+  }
 
 	while (!stream.eos() && !line.contains('}')) {
 		Puzzle::CriteriaEntry entry;
@@ -205,18 +199,18 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 		// There are supposed to be three tokens, but there is no
 		// guarantee that there will be a space between the second and
 		// the third one (bug #6774)
-		if (token.size() == 1) {
+		if (token.size() == 1)
 			token = tokenizer.nextToken();
-		} else {
+		else
 			token.deleteChar(0);
-		}
 
 		// First determine if the last token is an id or a value
 		// Then parse it into 'argument'
 		if (token.contains('[')) {
 			sscanf(token.c_str(), "[%u]", &(entry.argument));
 			entry.argumentIsAKey = true;
-		} else {
+		} 
+		else {
 			sscanf(token.c_str(), "%u", &(entry.argument));
 			entry.argumentIsAKey = false;
 		}
@@ -236,19 +230,15 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 			entry0.criteriaOperator = Puzzle::GREATER_THAN;
 			entry0.argumentIsAKey = false;
 			entry0.argument = 0;
-
 			criteriaList.back().push_back(entry0);
-
 			entry.criteriaOperator = Puzzle::NOT_EQUAL_TO;
 			entry.argument = 2;
 		}
-
+		
 		criteriaList.back().push_back(entry);
-
 		line = stream.readLine();
 		trimCommentsAndWhiteSpace(&line);
 	}
-
 	return true;
 }
 
@@ -266,41 +256,33 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 			line.toLowercase();
 			continue;
 		}
-
 		const char *chrs = line.c_str();
 		uint pos;
 		for (pos = 0; pos < line.size(); pos++)
 			if (chrs[pos] == ':')
 				break;
-
 		if (pos < line.size()) {
 			uint startpos = pos + 1;
 			for (pos = startpos; pos < line.size(); pos++)
 				if (chrs[pos] == ':' || chrs[pos] == '(')
 					break;
-
 			if (pos < line.size()) {
 				int32 slot = 11;
 				Common::String args = "";
 				Common::String act(chrs + startpos, chrs + pos);
-
 				startpos = pos + 1;
-
 				if (chrs[pos] == ':') {
 					for (pos = startpos; pos < line.size(); pos++)
 						if (chrs[pos] == '(')
 							break;
 					Common::String strSlot(chrs + startpos, chrs + pos);
 					slot = atoi(strSlot.c_str());
-
 					startpos = pos + 1;
 				}
-
 				if (pos < line.size()) {
 					for (pos = startpos; pos < line.size(); pos++)
 						if (chrs[pos] == ')')
 							break;
-
 					args = Common::String(chrs + startpos, chrs + pos);
 				}
 
@@ -401,35 +383,28 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 				}
 			}
 		}
-
 		line = stream.readLine();
 		trimCommentsAndWhiteSpace(&line);
 		line.toLowercase();
 	}
-
 	return;
 }
 
 uint ScriptManager::parseFlags(Common::SeekableReadStream &stream) const {
 	uint flags = 0;
-
 	// Loop until we find the closing brace
 	Common::String line = stream.readLine();
 	trimCommentsAndWhiteSpace(&line);
-
 	while (!stream.eos() && !line.contains('}')) {
-		if (line.matchString("ONCE_PER_INST", true)) {
+		if (line.matchString("ONCE_PER_INST", true))
 			flags |= Puzzle::ONCE_PER_INST;
-		} else if (line.matchString("DO_ME_NOW", true)) {
+		else if (line.matchString("DO_ME_NOW", true))
 			flags |= Puzzle::DO_ME_NOW;
-		} else if (line.matchString("DISABLED", true)) {
+		else if (line.matchString("DISABLED", true))
 			flags |= Puzzle::DISABLED;
-		}
-
 		line = stream.readLine();
 		trimCommentsAndWhiteSpace(&line);
 	}
-
 	return flags;
 }
 
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index 132e6c0f123..02bc27695dc 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -58,17 +58,13 @@ void ScriptManager::initialize() {
 	cleanScriptScope(world);
 	cleanScriptScope(room);
 	cleanScriptScope(nodeview);
-
 	_currentLocation.node = 0;
 	_currentLocation.world = 0;
 	_currentLocation.room = 0;
 	_currentLocation.view = 0;
-
 	_changeLocationDelayCycles = 0;
-
 	parseScrFile("universe.scr", universe);
 	changeLocation('g', 'a', 'r', 'y', 0);
-
 	_controlEvents.clear();
 }
 
@@ -83,25 +79,19 @@ void ScriptManager::update(uint deltaTimeMillis) {
 		// in the exec queues, but that could cause this to hang
 		// indefinitely.
 		// TODO - this causes noticeable pauses on location change; see if these can be reduced by improving this functionality.
-		if (_changeLocationDelayCycles-- <= 0) {
+		if (_changeLocationDelayCycles-- <= 0)
 			ChangeLocationReal(false);
-		}
 	}
-
 	updateNodes(deltaTimeMillis);
 	debug(5,"Script nodes updated");
-	if (!execScope(nodeview)) {
+	if (!execScope(nodeview))
 		return;
-	}
-	if (!execScope(room)) {
+	if (!execScope(room))
 		return;
-	}
-	if (!execScope(world)) {
+	if (!execScope(world))
 		return;
-	}
-	if (!execScope(universe)) {
+	if (!execScope(universe))
 		return;
-	}
 	updateControls(deltaTimeMillis);
 }
 
@@ -112,27 +102,23 @@ bool ScriptManager::execScope(ScriptScope &scope) {
 	scope.scopeQueue = tmp;
 	scope.scopeQueue->clear();
 
-	for (PuzzleList::iterator PuzzleIter = scope.puzzles.begin(); PuzzleIter != scope.puzzles.end(); ++PuzzleIter) {
+	for (PuzzleList::iterator PuzzleIter = scope.puzzles.begin(); PuzzleIter != scope.puzzles.end(); ++PuzzleIter)
 		(*PuzzleIter)->addedBySetState = false;
-	}
 
 	if (scope.procCount < 2 || getStateValue(StateKey_ExecScopeStyle)) {
 		for (PuzzleList::iterator PuzzleIter = scope.puzzles.begin(); PuzzleIter != scope.puzzles.end(); ++PuzzleIter) {
-			if (!checkPuzzleCriteria(*PuzzleIter, scope.procCount)) {
+			if (!checkPuzzleCriteria(*PuzzleIter, scope.procCount))
 				return false;
-			}
 		}
-	} else {
+	} 
+	else {
 		for (PuzzleList::iterator PuzzleIter = scope.execQueue->begin(); PuzzleIter != scope.execQueue->end(); ++PuzzleIter) {
-			if (!checkPuzzleCriteria(*PuzzleIter, scope.procCount)) {
+			if (!checkPuzzleCriteria(*PuzzleIter, scope.procCount))
 				return false;
-			}
 		}
 	}
-
-	if (scope.procCount < 2) {
+	if (scope.procCount < 2)
 		scope.procCount++;
-	}
 	return true;
 }
 
@@ -140,12 +126,10 @@ void ScriptManager::referenceTableAddPuzzle(uint32 key, PuzzleRef ref) {
 	if (_referenceTable.contains(key)) {
 		Common::Array<PuzzleRef> *arr = &_referenceTable[key];
 		for (uint32 i = 0; i < arr->size(); i++) {
-			if ((*arr)[i].puz == ref.puz) {
+			if ((*arr)[i].puz == ref.puz)
 				return;
-			}
 		}
 	}
-
 	_referenceTable[key].push_back(ref);
 }
 
@@ -153,18 +137,14 @@ void ScriptManager::addPuzzlesToReferenceTable(ScriptScope &scope) {
 	// Iterate through each local Puzzle
 	for (PuzzleList::iterator PuzzleIter = scope.puzzles.begin(); PuzzleIter != scope.puzzles.end(); ++PuzzleIter) {
 		Puzzle *puzzlePtr = (*PuzzleIter);
-
 		PuzzleRef ref;
 		ref.scope = &scope;
 		ref.puz = puzzlePtr;
-
 		referenceTableAddPuzzle(puzzlePtr->key, ref);
-
 		// Iterate through each CriteriaEntry and add a reference from the criteria key to the Puzzle
 		for (Common::List<Common::List<Puzzle::CriteriaEntry> >::iterator criteriaIter = (*PuzzleIter)->criteriaList.begin(); criteriaIter != (*PuzzleIter)->criteriaList.end(); ++criteriaIter) {
-			for (Common::List<Puzzle::CriteriaEntry>::iterator entryIter = criteriaIter->begin(); entryIter != criteriaIter->end(); ++entryIter) {
+			for (Common::List<Puzzle::CriteriaEntry>::iterator entryIter = criteriaIter->begin(); entryIter != criteriaIter->end(); ++entryIter)
 				referenceTableAddPuzzle(entryIter->key, ref);
-			}
 		}
 	}
 }
@@ -173,49 +153,44 @@ void ScriptManager::updateNodes(uint deltaTimeMillis) {
 	// If process() returns true, it means the node can be deleted
 	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end();) {
 		if ((*iter)->process(deltaTimeMillis)) {
-			delete(*iter);
-			// Remove the node
+			delete(*iter);  // Remove the node
 			iter = _activeSideFx.erase(iter);
-		} else {
+		} 
+		else
 			++iter;
-		}
 	}
 }
 
 void ScriptManager::updateControls(uint deltaTimeMillis) {
-	if (!_activeControls) {
+	if (!_activeControls)
 		return;
-	}
-
 	// Process only one event
 	if (!_controlEvents.empty()) {
 		Common::Event _event = _controlEvents.front();
 		Common::Point imageCoord;
 		switch (_event.type) {
-		case Common::EVENT_LBUTTONDOWN:
-			imageCoord = _engine->getRenderManager()->screenSpaceToImageSpace(_event.mouse);
-			onMouseDown(_event.mouse, imageCoord);
-			break;
-		case Common::EVENT_LBUTTONUP:
-			imageCoord = _engine->getRenderManager()->screenSpaceToImageSpace(_event.mouse);
-			onMouseUp(_event.mouse, imageCoord);
-			break;
-		case Common::EVENT_KEYDOWN:
-			onKeyDown(_event.kbd);
-			break;
-		case Common::EVENT_KEYUP:
-			onKeyUp(_event.kbd);
-			break;
-		default:
-			break;
+		  case Common::EVENT_LBUTTONDOWN:
+			  imageCoord = _engine->getRenderManager()->screenSpaceToImageSpace(_event.mouse);
+			  onMouseDown(_event.mouse, imageCoord);
+			  break;
+		  case Common::EVENT_LBUTTONUP:
+			  imageCoord = _engine->getRenderManager()->screenSpaceToImageSpace(_event.mouse);
+			  onMouseUp(_event.mouse, imageCoord);
+			  break;
+		  case Common::EVENT_KEYDOWN:
+			  onKeyDown(_event.kbd);
+			  break;
+		  case Common::EVENT_KEYUP:
+			  onKeyUp(_event.kbd);
+			  break;
+		  default:
+			  break;
 		}
 		_controlEvents.pop_front();
 	}
-
 	for (ControlList::iterator iter = _activeControls->begin(); iter != _activeControls->end(); iter++) {
-		if ((*iter)->process(deltaTimeMillis)) {
+		if ((*iter)->process(deltaTimeMillis))
 			break;
-		}
 	}
 }
 
@@ -234,60 +209,48 @@ bool ScriptManager::checkPuzzleCriteria(Puzzle *puzzle, uint counter) {
 	bool criteriaMet = false;
 	for (Common::List<Common::List<Puzzle::CriteriaEntry> >::iterator criteriaIter = puzzle->criteriaList.begin(); criteriaIter != puzzle->criteriaList.end(); ++criteriaIter) {
 		criteriaMet = false;
-
 		for (Common::List<Puzzle::CriteriaEntry>::iterator entryIter = criteriaIter->begin(); entryIter != criteriaIter->end(); ++entryIter) {
 			// Get the value to compare against
 			int argumentValue;
-			if (entryIter->argumentIsAKey) {
+			if (entryIter->argumentIsAKey)
 				argumentValue = getStateValue(entryIter->argument);
-			} else {
+			else
 				argumentValue = entryIter->argument;
-			}
-
 			// Do the comparison
 			switch (entryIter->criteriaOperator) {
-			case Puzzle::EQUAL_TO:
-				criteriaMet = getStateValue(entryIter->key) == argumentValue;
-				break;
-			case Puzzle::NOT_EQUAL_TO:
-				criteriaMet = getStateValue(entryIter->key) != argumentValue;
-				break;
-			case Puzzle::GREATER_THAN:
-				criteriaMet = getStateValue(entryIter->key) > argumentValue;
-				break;
-			case Puzzle::LESS_THAN:
-				criteriaMet = getStateValue(entryIter->key) < argumentValue;
-				break;
-			default:
-				break;
+			  case Puzzle::EQUAL_TO:
+				  criteriaMet = getStateValue(entryIter->key) == argumentValue;
+				  break;
+			  case Puzzle::NOT_EQUAL_TO:
+				  criteriaMet = getStateValue(entryIter->key) != argumentValue;
+				  break;
+			  case Puzzle::GREATER_THAN:
+				  criteriaMet = getStateValue(entryIter->key) > argumentValue;
+				  break;
+			  case Puzzle::LESS_THAN:
+				  criteriaMet = getStateValue(entryIter->key) < argumentValue;
+				  break;
+			  default:
+				  break;
 			}
-
 			// If one check returns false, don't keep checking
-			if (!criteriaMet) {
+			if (!criteriaMet)
 				break;
-			}
 		}
-
 		// If any of the Criteria are *fully* met, then execute the results
-		if (criteriaMet) {
+		if (criteriaMet)
 			break;
-		}
 	}
-
 	// criteriaList can be empty. Aka, the puzzle should be executed immediately
 	if (puzzle->criteriaList.empty() || criteriaMet) {
 		debug(3, "Puzzle %u criteria passed. Executing its ResultActions", puzzle->key);
-
 		// Set the puzzle as completed
 		setStateValue(puzzle->key, 1);
-
 		for (Common::List<ResultAction *>::iterator resultIter = puzzle->resultActions.begin(); resultIter != puzzle->resultActions.end(); ++resultIter) {
-			if (!(*resultIter)->execute()) {
+			if (!(*resultIter)->execute())
 				return false;
-			}
 		}
 	}
-
 	return true;
 }
 
@@ -295,10 +258,8 @@ void ScriptManager::cleanStateTable() {
 	for (StateMap::iterator iter = _globalState.begin(); iter != _globalState.end(); ++iter) {
 		// If the value is equal to zero, we can purge it since getStateValue()
 		// will return zero if _globalState doesn't contain a key
-		if (iter->_value == 0) {
-			// Remove the node
-			_globalState.erase(iter);
-		}
+		if (iter->_value == 0)
+			_globalState.erase(iter); // Remove the node
 	}
 }
 
@@ -307,27 +268,20 @@ void ScriptManager::cleanScriptScope(ScriptScope &scope) {
 	scope.privQueueTwo.clear();
 	scope.scopeQueue = &scope.privQueueOne;
 	scope.execQueue = &scope.privQueueTwo;
-	for (PuzzleList::iterator iter = scope.puzzles.begin(); iter != scope.puzzles.end(); ++iter) {
+	for (PuzzleList::iterator iter = scope.puzzles.begin(); iter != scope.puzzles.end(); ++iter)
 		delete(*iter);
-	}
-
 	scope.puzzles.clear();
-
-	for (ControlList::iterator iter = scope.controls.begin(); iter != scope.controls.end(); ++iter) {
+	for (ControlList::iterator iter = scope.controls.begin(); iter != scope.controls.end(); ++iter)
 		delete(*iter);
-	}
-
 	scope.controls.clear();
-
 	scope.procCount = 0;
 }
 
 int ScriptManager::getStateValue(uint32 key) {
-	if (_globalState.contains(key)) {
+	if (_globalState.contains(key))
 		return _globalState[key];
-	} else {
+  else
 		return 0;
-	}
 }
 
 void ScriptManager::queuePuzzles(uint32 key) {
@@ -343,84 +297,68 @@ void ScriptManager::queuePuzzles(uint32 key) {
 }
 
 void ScriptManager::setStateValue(uint32 key, int value) {
-	if (value == 0) {
+	if (value == 0)
 		_globalState.erase(key);
-	} else {
+	else
 		_globalState[key] = value;
-	}
-
 	queuePuzzles(key);
 }
 
 void ScriptManager::setStateValueSilent(uint32 key, int value) {
-	if (value == 0) {
+	if (value == 0)
 		_globalState.erase(key);
-	} else {
+	else
 		_globalState[key] = value;
-	}
 }
 
 uint ScriptManager::getStateFlag(uint32 key) {
-	if (_globalStateFlags.contains(key)) {
+	if (_globalStateFlags.contains(key))
 		return _globalStateFlags[key];
-	} else {
+	else
 		return 0;
-	}
 }
 
 void ScriptManager::setStateFlag(uint32 key, uint value) {
 	queuePuzzles(key);
-
 	_globalStateFlags[key] |= value;
 }
 
 void ScriptManager::setStateFlagSilent(uint32 key, uint value) {
-	if (value == 0) {
+	if (value == 0)
 		_globalStateFlags.erase(key);
-	} else {
+	else
 		_globalStateFlags[key] = value;
-	}
 }
 
 void ScriptManager::unsetStateFlag(uint32 key, uint value) {
 	queuePuzzles(key);
-
 	if (_globalStateFlags.contains(key)) {
 		_globalStateFlags[key] &= ~value;
-
-		if (_globalStateFlags[key] == 0) {
+		if (_globalStateFlags[key] == 0)
 			_globalStateFlags.erase(key);
-		}
 	}
 }
 
 Control *ScriptManager::getControl(uint32 key) {
 	for (ControlList::iterator iter = _activeControls->begin(); iter != _activeControls->end(); ++iter) {
-		if ((*iter)->getKey() == key) {
+		if ((*iter)->getKey() == key)
 			return *iter;
-		}
 	}
-
 	return nullptr;
 }
 
 void ScriptManager::focusControl(uint32 key) {
-	if (!_activeControls) {
+	if (!_activeControls)
 		return;
-	}
-	if (_currentlyFocusedControl == key) {
+	if (_currentlyFocusedControl == key)
 		return;
-	}
 	for (ControlList::iterator iter = _activeControls->begin(); iter != _activeControls->end(); ++iter) {
 		uint32 controlKey = (*iter)->getKey();
-
-		if (controlKey == key) {
+		if (controlKey == key)
 			(*iter)->focus();
-		} else if (controlKey == _currentlyFocusedControl) {
+		else if (controlKey == _currentlyFocusedControl)
 			(*iter)->unfocus();
-		}
 	}
-
 	_currentlyFocusedControl = key;
 }
 
@@ -434,11 +372,9 @@ void ScriptManager::addSideFX(ScriptingEffect *fx) {
 
 ScriptingEffect *ScriptManager::getSideFX(uint32 key) {
 	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); ++iter) {
-		if ((*iter)->getKey() == key) {
+		if ((*iter)->getKey() == key)
 			return (*iter);
-		}
 	}
-
 	return nullptr;
 }
 
@@ -482,67 +418,55 @@ void ScriptManager::killSideFxType(ScriptingEffect::ScriptingEffectType type) {
 			(*iter)->kill();
 			delete(*iter);
 			iter = _activeSideFx.erase(iter);
-		} else {
+		} 
+		else
 			++iter;
-		}
 	}
 }
 
 void ScriptManager::onMouseDown(const Common::Point &screenSpacePos, const Common::Point &backgroundImageSpacePos) {
-	if (!_activeControls) {
+	if (!_activeControls)
 		return;
-	}
 	for (ControlList::iterator iter = _activeControls->reverse_begin(); iter != _activeControls->end(); iter--) {
-		if ((*iter)->onMouseDown(screenSpacePos, backgroundImageSpacePos)) {
+		if ((*iter)->onMouseDown(screenSpacePos, backgroundImageSpacePos))
 			return;
-		}
 	}
 }
 
 void ScriptManager::onMouseUp(const Common::Point &screenSpacePos, const Common::Point &backgroundImageSpacePos) {
-	if (!_activeControls) {
+	if (!_activeControls)
 		return;
-	}
 	for (ControlList::iterator iter = _activeControls->reverse_begin(); iter != _activeControls->end(); iter--) {
-		if ((*iter)->onMouseUp(screenSpacePos, backgroundImageSpacePos)) {
+		if ((*iter)->onMouseUp(screenSpacePos, backgroundImageSpacePos))
 			return;
-		}
 	}
 }
 
 bool ScriptManager::onMouseMove(const Common::Point &screenSpacePos, const Common::Point &backgroundImageSpacePos) {
-	if (!_activeControls) {
+	if (!_activeControls)
 		return false;
-	}
-
 	for (ControlList::iterator iter = _activeControls->reverse_begin(); iter != _activeControls->end(); iter--) {
-		if ((*iter)->onMouseMove(screenSpacePos, backgroundImageSpacePos)) {
+		if ((*iter)->onMouseMove(screenSpacePos, backgroundImageSpacePos))
 			return true;
-		}
 	}
-
 	return false;
 }
 
 void ScriptManager::onKeyDown(Common::KeyState keyState) {
-	if (!_activeControls) {
+	if (!_activeControls)
 		return;
-	}
 	for (ControlList::iterator iter = _activeControls->begin(); iter != _activeControls->end(); ++iter) {
-		if ((*iter)->onKeyDown(keyState)) {
+		if ((*iter)->onKeyDown(keyState))
 			return;
-		}
 	}
 }
 
 void ScriptManager::onKeyUp(Common::KeyState keyState) {
-	if (!_activeControls) {
+	if (!_activeControls)
 		return;
-	}
 	for (ControlList::iterator iter = _activeControls->begin(); iter != _activeControls->end(); ++iter) {
-		if ((*iter)->onKeyUp(keyState)) {
+		if ((*iter)->onKeyUp(keyState))
 			return;
-		}
 	}
 }
 
@@ -552,7 +476,6 @@ void ScriptManager::changeLocation(const Location &_newLocation) {
 
 void ScriptManager::changeLocation(char _world, char _room, char _node, char _view, uint32 offset) {
 	_changeLocationDelayCycles = 1;
-
 	_nextLocation.world = _world;
 	_nextLocation.room = _room;
 	_nextLocation.node = _node;
@@ -566,7 +489,8 @@ void ScriptManager::changeLocation(char _world, char _room, char _node, char _vi
 			_nextLocation.node = getStateValue(StateKey_LastNode);
 			_nextLocation.view = getStateValue(StateKey_LastView);
 			_nextLocation.offset = getStateValue(StateKey_LastViewPos);
-		} else {
+		} 
+		else {
 			_nextLocation.world = getStateValue(StateKey_Menu_LastWorld);
 			_nextLocation.room = getStateValue(StateKey_Menu_LastRoom);
 			_nextLocation.node = getStateValue(StateKey_Menu_LastNode);
@@ -578,13 +502,11 @@ void ScriptManager::changeLocation(char _world, char _room, char _node, char _vi
 
 void ScriptManager::ChangeLocationReal(bool isLoading) {
 	assert(_nextLocation.world != 0);
-	debug(1, "\tChanging location to: %c %c %c %c %u", _nextLocation.world, _nextLocation.room, _nextLocation.node, _nextLocation.view, _nextLocation.offset);
-
+	debug(1, "\tChanging location to: World %c, Room %c, Node %c, View %c, Offset %u", _nextLocation.world, _nextLocation.room, _nextLocation.node, _nextLocation.view, _nextLocation.offset);
 	const bool enteringMenu = (_nextLocation.world == 'g' && _nextLocation.room == 'j');
 	const bool leavingMenu = (_currentLocation.world == 'g' && _currentLocation.room == 'j');
 	const bool isSaveScreen = (enteringMenu && _nextLocation.node == 's' && _nextLocation.view == 'e');
 	const bool isRestoreScreen = (enteringMenu && _nextLocation.node == 'r' && _nextLocation.view == 'e');
-
 	if (enteringMenu && !ConfMan.getBool("originalsaveload")) {
 		if (isSaveScreen || isRestoreScreen) {
 			// Hook up the ScummVM save/restore dialog
@@ -597,7 +519,8 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 				_nextLocation.view = _currentLocation.view;
 				_nextLocation.offset = _currentLocation.offset;
 				return;
-			} else {
+			} 
+			else {
 				_currentLocation.world = 'g';
 				_currentLocation.room = '0';
 				_currentLocation.node = '0';
@@ -614,7 +537,8 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 			setStateValue(StateKey_LastNode, getStateValue(StateKey_Node));
 			setStateValue(StateKey_LastView, getStateValue(StateKey_View));
 			setStateValue(StateKey_LastViewPos, getStateValue(StateKey_ViewPos));
-		} else {
+		} 
+		else {
 			setStateValue(StateKey_Menu_LastWorld, getStateValue(StateKey_World));
 			setStateValue(StateKey_Menu_LastRoom, getStateValue(StateKey_Room));
 			setStateValue(StateKey_Menu_LastNode, getStateValue(StateKey_Node));
@@ -624,14 +548,11 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 	}
 
 	if (enteringMenu) {
-		if (isSaveScreen && !leavingMenu) {
+		if (isSaveScreen && !leavingMenu)
 			_engine->getSaveManager()->prepareSaveBuffer();
-		}
-	} else {
-		if (leavingMenu) {
-			_engine->getSaveManager()->flushSaveBuffer();
-		}
-	}
+	} 
+	else if (leavingMenu)
+		_engine->getSaveManager()->flushSaveBuffer();
 
 	setStateValue(StateKey_World, _nextLocation.world);
 	setStateValue(StateKey_Room, _nextLocation.room);
@@ -648,38 +569,31 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 		cleanScriptScope(nodeview);
 		cleanScriptScope(room);
 		cleanScriptScope(world);
-
 		Common::Path fileName(Common::String::format("%c%c%c%c.scr", _nextLocation.world, _nextLocation.room, _nextLocation.node, _nextLocation.view));
 		parseScrFile(fileName, nodeview);
 		addPuzzlesToReferenceTable(nodeview);
-
 		fileName = Common::Path(Common::String::format("%c%c.scr", _nextLocation.world, _nextLocation.room));
 		parseScrFile(fileName, room);
 		addPuzzlesToReferenceTable(room);
-
 		fileName = Common::Path(Common::String::format("%c.scr", _nextLocation.world));
 		parseScrFile(fileName, world);
 		addPuzzlesToReferenceTable(world);
-	} else if (_nextLocation.room != _currentLocation.room) {
+	} 
+	else if (_nextLocation.room != _currentLocation.room) {
 		cleanScriptScope(nodeview);
 		cleanScriptScope(room);
-
 		addPuzzlesToReferenceTable(world);
-
 		Common::Path fileName(Common::String::format("%c%c%c%c.scr", _nextLocation.world, _nextLocation.room, _nextLocation.node, _nextLocation.view));
 		parseScrFile(fileName, nodeview);
 		addPuzzlesToReferenceTable(nodeview);
-
 		fileName = Common::Path(Common::String::format("%c%c.scr", _nextLocation.world, _nextLocation.room));
 		parseScrFile(fileName, room);
 		addPuzzlesToReferenceTable(room);
-
-	} else if (_nextLocation.node != _currentLocation.node || _nextLocation.view != _currentLocation.view) {
+	} 
+	else if (_nextLocation.node != _currentLocation.node || _nextLocation.view != _currentLocation.view) {
 		cleanScriptScope(nodeview);
-
 		addPuzzlesToReferenceTable(room);
 		addPuzzlesToReferenceTable(world);
-
 		Common::Path fileName(Common::String::format("%c%c%c%c.scr", _nextLocation.world, _nextLocation.room, _nextLocation.node, _nextLocation.view));
 		parseScrFile(fileName, nodeview);
 		addPuzzlesToReferenceTable(nodeview);
@@ -725,119 +639,86 @@ void ScriptManager::serialize(Common::WriteStream *stream) {
 	stream->writeByte(getStateValue(StateKey_Node));
 	stream->writeByte(getStateValue(StateKey_View));
 	stream->writeUint32LE(getStateValue(StateKey_ViewPos));
-
-	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); ++iter) {
+	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); ++iter)
 		(*iter)->serialize(stream);
-	}
-
 	stream->writeUint32BE(MKTAG('F', 'L', 'A', 'G'));
-
-	int32 slots = 20000;
-	if (_engine->getGameId() == GID_NEMESIS) {
-		slots = 30000;
-	}
-
+	int32 slots = _engine->getGameId() == GID_NEMESIS ? 30000 : 20000;
 	stream->writeUint32LE(slots * 2);
-
-	for (int32 i = 0; i < slots; i++) {
+	for (int32 i = 0; i < slots; i++)
 		stream->writeUint16LE(getStateFlag(i));
-	}
-
 	stream->writeUint32BE(MKTAG('P', 'U', 'Z', 'Z'));
-
 	stream->writeUint32LE(slots * 2);
-
-	for (int32 i = 0; i < slots; i++) {
+	for (int32 i = 0; i < slots; i++)
 		stream->writeSint16LE(getStateValue(i));
-	}
 }
 
 void ScriptManager::deserialize(Common::SeekableReadStream *stream) {
 	// Clear out the current table values
 	_globalState.clear();
 	_globalStateFlags.clear();
-
 	cleanScriptScope(nodeview);
 	cleanScriptScope(room);
 	cleanScriptScope(world);
-
 	_currentLocation.node = 0;
 	_currentLocation.world = 0;
 	_currentLocation.room = 0;
 	_currentLocation.view = 0;
-
-	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); iter++) {
+	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); iter++)
 		delete(*iter);
-	}
-
 	_activeSideFx.clear();
-
 	_referenceTable.clear();
-
 	if (stream->readUint32BE() != MKTAG('Z', 'N', 'S', 'G') || stream->readUint32LE() != 4) {
 		changeLocation('g', 'a', 'r', 'y', 0);
 		return;
 	}
-
 	stream->seek(4, SEEK_CUR);
-
 	if (stream->readUint32BE() != MKTAG('L', 'O', 'C', ' ') || stream->readUint32LE() != 8) {
 		changeLocation('g', 'a', 'r', 'y', 0);
 		return;
 	}
-
 	Location nextLocation;
-
 	nextLocation.world = stream->readByte();
 	nextLocation.room = stream->readByte();
 	nextLocation.node = stream->readByte();
 	nextLocation.view = stream->readByte();
 	nextLocation.offset = stream->readUint32LE() & 0x0000FFFF;
-
 	while (stream->pos() < stream->size()) {
 		uint32 tag = stream->readUint32BE();
 		uint32 tagSize = stream->readUint32LE();
 		switch (tag) {
-		case MKTAG('T', 'I', 'M', 'R'): {
-			uint32 key = stream->readUint32LE();
-			uint32 time = stream->readUint32LE();
-			if (_engine->getGameId() == GID_GRANDINQUISITOR) {
-				time /= 100;
-			} else if (_engine->getGameId() == GID_NEMESIS) {
-				time /= 1000;
-			}
-			addSideFX(new TimerNode(_engine, key, time));
-		}
-		break;
-		case MKTAG('F', 'L', 'A', 'G'):
-			for (uint32 i = 0; i < tagSize / 2; i++) {
-				setStateFlagSilent(i, stream->readUint16LE());
-			}
-			break;
-		case MKTAG('P', 'U', 'Z', 'Z'):
-			for (uint32 i = 0; i < tagSize / 2; i++) {
-				setStateValueSilent(i, stream->readUint16LE());
-			}
-			break;
-		default:
-			stream->seek(tagSize, SEEK_CUR);
+		  case MKTAG('T', 'I', 'M', 'R'): {
+			  uint32 key = stream->readUint32LE();
+			  uint32 time = stream->readUint32LE();
+			  if (_engine->getGameId() == GID_GRANDINQUISITOR)
+				  time /= 100;
+			  else if (_engine->getGameId() == GID_NEMESIS)
+				  time /= 1000;
+			  addSideFX(new TimerNode(_engine, key, time));
+			  }
+		    break;
+		  case MKTAG('F', 'L', 'A', 'G'):
+			  for (uint32 i = 0; i < tagSize / 2; i++)
+				  setStateFlagSilent(i, stream->readUint16LE());
+			  break;
+		  case MKTAG('P', 'U', 'Z', 'Z'):
+			  for (uint32 i = 0; i < tagSize / 2; i++)
+				  setStateValueSilent(i, stream->readUint16LE());
+			  break;
+		  default:
+			  stream->seek(tagSize, SEEK_CUR);
+			  break;
 		}
 	}
-
 	_nextLocation = nextLocation;
-
 	ChangeLocationReal(true);
-
 	_engine->setRenderDelay(10);
 	setStateValue(StateKey_RestoreFlag, 1);
-
 	_engine->loadSettings();
 }
 
 Location ScriptManager::getCurrentLocation() const {
 	Location location = _currentLocation;
 	location.offset = _engine->getRenderManager()->getCurrentBackgroundOffset();
-
 	return location;
 }
 
@@ -848,7 +729,6 @@ Location ScriptManager::getLastLocation() {
 	location.node = getStateValue(StateKey_LastNode);
 	location.view = getStateValue(StateKey_LastView);
 	location.offset = getStateValue(StateKey_LastViewPos);
-
 	return location;
 }
 
@@ -859,7 +739,6 @@ Location ScriptManager::getLastMenuLocation() {
 	location.node = getStateValue(StateKey_Menu_LastNode);
 	location.view = getStateValue(StateKey_Menu_LastView);
 	location.offset = getStateValue(StateKey_Menu_LastViewPos);
-
 	return location;
 }
 
@@ -870,22 +749,18 @@ void ScriptManager::addEvent(Common::Event event) {
 void ScriptManager::flushEvent(Common::EventType type) {
 	EventList::iterator it = _controlEvents.begin();
 	while (it != _controlEvents.end()) {
-
-		if ((*it).type == type) {
+		if ((*it).type == type)
 			it = _controlEvents.erase(it);
-		} else {
+		else
 			it++;
-		}
 	}
 }
 
 void ScriptManager::trimCommentsAndWhiteSpace(Common::String *string) const {
 	for (int i = string->size() - 1; i >= 0; i--) {
-		if ((*string)[i] == '#') {
+		if ((*string)[i] == '#')
 			string->erase(i);
-		}
 	}
-
 	string->trim();
 }
 
@@ -897,22 +772,21 @@ ValueSlot::ValueSlot(ScriptManager *scriptManager, const char *slotValue):
 	if (isSlot) {
 		slot = true;
 		value = atoi(isSlot + 1);
-	} else {
+	} 
+	else {
 		slot = false;
 		value = atoi(slotValue);
 	}
 }
 int16 ValueSlot::getValue() {
 	if (slot) {
-		if (value >= 0) {
+		if (value >= 0)
 			return _scriptManager->getStateValue(value);
-		}
-		else {
+		else
 			return 0;
-		}
-	} else {
-		return value;
 	}
+	else
+		return value;
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/script_manager.h b/engines/zvision/scripting/script_manager.h
index 04ed99ca8f3..5311a746bff 100644
--- a/engines/zvision/scripting/script_manager.h
+++ b/engines/zvision/scripting/script_manager.h
@@ -104,7 +104,6 @@ enum StateKey {
 
 struct Location {
 	Location() : world('g'), room('a'), node('r'), view('y'), offset(0) {}
-
 	char world;
 	char room;
 	char node;
@@ -366,6 +365,16 @@ private:
 	Control *parseControl(Common::String &line, Common::SeekableReadStream &stream);
 };
 
+	/**
+	 * Instances of this polymorphic class function either as a store of a single value, or as a "slot" that returns a StateValue
+	 *
+	 * @param line      The line initially read
+	 * @param slotValue A text string containing a number, which may be enclosed within square braces.
+	 *  If square braces are not present, getValue() will return slotValue.
+   *  If square braces are present, getValue() will return the StateValue to which slotValue is the key.
+   *
+   * Once instantiated, the value and nature of slotValue may not be changed.
+	 */
 class ValueSlot {
 public:
 	ValueSlot(ScriptManager *scriptManager, const char *slotValue);
diff --git a/engines/zvision/video/rlf_decoder.cpp b/engines/zvision/video/rlf_decoder.cpp
index 205b5f3c0c4..b18ddcb8d59 100644
--- a/engines/zvision/video/rlf_decoder.cpp
+++ b/engines/zvision/video/rlf_decoder.cpp
@@ -196,60 +196,51 @@ bool RLFDecoder::RLFVideoTrack::seek(const Audio::Timestamp &time) {
 const Graphics::Surface *RLFDecoder::RLFVideoTrack::decodeNextFrame() {
 	if (_displayedFrame >= (int)_frameCount)
 		return NULL;
-
 	_displayedFrame++;
 	applyFrameToCurrent(_displayedFrame);
-
 	return &_currentFrameBuffer;
 }
 
 void RLFDecoder::RLFVideoTrack::applyFrameToCurrent(uint frameNumber) {
-	if (_frames[frameNumber].type == Masked) {
+	if (_frames[frameNumber].type == Masked)
 		decodeMaskedRunLengthEncoding(_frames[frameNumber].encodedData, (int8 *)_currentFrameBuffer.getPixels(), _frames[frameNumber].encodedSize, _frameBufferByteSize);
-	} else if (_frames[frameNumber].type == Simple) {
+	else if (_frames[frameNumber].type == Simple)
 		decodeSimpleRunLengthEncoding(_frames[frameNumber].encodedData, (int8 *)_currentFrameBuffer.getPixels(), _frames[frameNumber].encodedSize, _frameBufferByteSize);
-	}
 }
 
 void RLFDecoder::RLFVideoTrack::decodeMaskedRunLengthEncoding(int8 *source, int8 *dest, uint32 sourceSize, uint32 destSize) const {
 	uint32 sourceOffset = 0;
 	uint32 destOffset = 0;
 	int16 numberOfCopy = 0;
-
 	while (sourceOffset < sourceSize) {
 		int8 numberOfSamples = source[sourceOffset];
 		sourceOffset++;
-
 		// If numberOfSamples is negative, the next abs(numberOfSamples) samples should
 		// be copied directly from source to dest
 		if (numberOfSamples < 0) {
 			numberOfCopy = -numberOfSamples;
-
 			while (numberOfCopy > 0) {
-				if (sourceOffset + 1 >= sourceSize) {
+				if (sourceOffset + 1 >= sourceSize)
 					return;
-				} else if (destOffset + 1 >= destSize) {
-					debug(2, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
+				else if (destOffset + 1 >= destSize) {
+					debug(3, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
 					return;
 				}
-
 				WRITE_UINT16(dest + destOffset, READ_LE_UINT16(source + sourceOffset));
-
 				sourceOffset += 2;
 				destOffset += 2;
 				numberOfCopy--;
 			}
-
 			// If numberOfSamples is >= 0, move destOffset forward ((numberOfSamples * 2) + 2)
 			// This function assumes the dest buffer has been memset with 0's.
-		} else {
-			if (sourceOffset + 1 >= sourceSize) {
+		} 
+		else {
+			if (sourceOffset + 1 >= sourceSize)
 				return;
-			} else if (destOffset + 1 >= destSize) {
-				debug(2, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
+      else if (destOffset + 1 >= destSize) {
+				debug(3, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
 				return;
 			}
-
 			destOffset += (numberOfSamples * 2) + 2;
 		}
 	}
@@ -259,48 +250,39 @@ void RLFDecoder::RLFVideoTrack::decodeSimpleRunLengthEncoding(int8 *source, int8
 	uint32 sourceOffset = 0;
 	uint32 destOffset = 0;
 	int16 numberOfCopy = 0;
-
 	while (sourceOffset < sourceSize) {
 		int8 numberOfSamples = source[sourceOffset];
 		sourceOffset++;
-
 		// If numberOfSamples is negative, the next abs(numberOfSamples) samples should
 		// be copied directly from source to dest
 		if (numberOfSamples < 0) {
 			numberOfCopy = -numberOfSamples;
-
 			while (numberOfCopy > 0) {
 				if (sourceOffset + 1 >= sourceSize) {
 					return;
 				} else if (destOffset + 1 >= destSize) {
-					debug(2, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
+					debug(3, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
 					return;
 				}
-
 				WRITE_UINT16(dest + destOffset, READ_LE_UINT16(source + sourceOffset));
-
 				sourceOffset += 2;
 				destOffset += 2;
 				numberOfCopy--;
 			}
-
 			// If numberOfSamples is >= 0, copy one sample from source to the
 			// next (numberOfSamples + 2) dest spots
-		} else {
-			if (sourceOffset + 1 >= sourceSize) {
+		} 
+		else {
+			if (sourceOffset + 1 >= sourceSize)
 				return;
-			}
-
 			uint16 sampleColor = READ_LE_UINT16(source + sourceOffset);
 			sourceOffset += 2;
-
 			numberOfCopy = numberOfSamples + 2;
 			while (numberOfCopy > 0) {
 				if (destOffset + 1 >= destSize) {
-					debug(2, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
+					debug(3, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
 					return;
 				}
-
 				WRITE_UINT16(dest + destOffset, sampleColor);
 				destOffset += 2;
 				numberOfCopy--;


Commit: ea7e8180cb7a8421089b27c8f47f1738f8b8a361
    https://github.com/scummvm/scummvm/commit/ea7e8180cb7a8421089b27c8f47f1738f8b8a361
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:56+02:00

Commit Message:
ZVISION: Fix bug in MusicNode fade/crossfade effect.
Now correctly fades for both positive and negative volume changes.
Code cleanup.

Changed paths:
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/effects/music_effect.h


diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index df76bfad158..1450b967482 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -511,8 +511,8 @@ ActionMusic::ActionMusic(ZVision *engine, int32 slotKey, const Common::String &l
 	if (engine->getGameId() == GID_NEMESIS && _slotKey == 14822 && _scriptManager->getStateValue(_slotKey) == 2)
 		_scriptManager->setStateValue(_slotKey, 0);
 
-  debug(1,"Created Action: Music, slotKey %d, type %u, file %24s, note %u, volume %d", _slotKey, type, fileNameBuffer, _note, _volume->getValue());
-  debug(2,"Music script: %s", line.c_str());
+  debug(3,"Created Action: Music, slotKey %d, type %u, file %24s, note %u, volume %d", _slotKey, type, fileNameBuffer, _note, _volume->getValue());
+  debug(4,"Music script: %s", line.c_str());
 }
 
 ActionMusic::~ActionMusic() {
@@ -522,7 +522,7 @@ ActionMusic::~ActionMusic() {
 }
 
 bool ActionMusic::execute() {
-  debug(1,"Executing Action: Music, slotKey %d, volume %d", _slotKey, _volume->getValue());
+  debug(3,"Executing Action: Music, slotKey %d, volume %d", _slotKey, _volume->getValue());
 	if (_scriptManager->getSideFX(_slotKey)) {
 		_scriptManager->killSideFx(_slotKey);
 		_scriptManager->setStateValue(_slotKey, 2);
@@ -549,16 +549,16 @@ ActionPanTrack::ActionPanTrack(ZVision *engine, int32 slotKey, const Common::Str
 	sscanf(line.c_str(), "%u %d", &_musicSlot, &_pos);
 	if(_scriptManager->getStateValue(_musicSlot) != 2)
     _scriptManager->setStateValue(_musicSlot, 2); //Pan_track scripts do not always trigger correctly unless this is set!
-  debug(1,"Created Action: PanTrack, slotkey %d, musicSlot %u, pos %d", _slotKey, _musicSlot, _pos);
+  debug(3,"Created Action: PanTrack, slotkey %d, musicSlot %u, pos %d", _slotKey, _musicSlot, _pos);
 }
 
 ActionPanTrack::~ActionPanTrack() {
 	_scriptManager->killSideFx(_slotKey);
-  debug(1,"Destroyed Action: PanTrack, slotkey %d", _slotKey);
+  debug(3,"Destroyed Action: PanTrack, slotkey %d", _slotKey);
 }
 
 bool ActionPanTrack::execute() {
-  debug(1,"Executing Action: PanTrack, slotkey %d, musicSlot %u, pos %d", _slotKey, _musicSlot, _pos);
+  debug(3,"Executing Action: PanTrack, slotkey %d, musicSlot %u, pos %d", _slotKey, _musicSlot, _pos);
 	if (_scriptManager->getSideFX(_slotKey))
 		return true;
 	_scriptManager->addSideFX(new PanTrackNode(_engine, _slotKey, _musicSlot, _pos));
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 9cf4f5ed194..2e02589feec 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -55,12 +55,10 @@ void MusicNodeBASE::setBalance(int8 balance) {
 }
 
 void MusicNodeBASE::updateMixer() {
-  uint16 tmpVol = _volume * fadeGain;
-  tmpVol /= 0xFF;
   if(_engine->getScriptManager()->getStateValue(StateKey_Qsound) >= 1)
-    volumeOut = _engine->getVolumeManager()->convert(tmpVol, _azimuth);  //Apply volume profile and then attenuate according to azimuth
+    volumeOut = _engine->getVolumeManager()->convert(_volume, _azimuth);  //Apply volume profile and then attenuate according to azimuth
   else
-    volumeOut = _engine->getVolumeManager()->convert(tmpVol, kVolumeLinear);  //Apply linear volume profile and ignore azimuth
+    volumeOut = _engine->getVolumeManager()->convert(_volume, kVolumeLinear);  //Apply linear volume profile and ignore azimuth
   outputMixer();
 }
 
@@ -69,9 +67,11 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 	_loop = loop;
 	_volume = volume;
 	_balance = 0;
-	_crossfade = false;
-	_crossfadeTarget = 0;
-	_crossfadeTime = 0;
+	_fade = false;
+  fadeStartVol = volume;
+	fadeEndVol = 0;
+	fadeTime = 0;
+	fadeElapsed = 0;
 	_sub = 0;
 	_stereo = false;
 	_loaded = false;
@@ -95,7 +95,7 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 		else
 			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, audioStream, -1, _volume);
 		if (_key != StateKey_NotSet) {
-		  debug(1,"setting musicnode state value to 1");
+		  debug(3,"setting musicnode state value to 1");
 			_engine->getScriptManager()->setStateValue(_key, 1);
 		}
 
@@ -111,19 +111,17 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 		_loaded = true;
 		updateMixer();
 	}
-	debug(1, "MusicNode: %d created", _key);
+	debug(3, "MusicNode: %d created", _key);
 }
 
 MusicNode::~MusicNode() {
 	if (_loaded)
 		_engine->_mixer->stopHandle(_handle);
-	if (_key != StateKey_NotSet) {
+	if (_key != StateKey_NotSet)
 		_engine->getScriptManager()->setStateValue(_key, 2);
-		  debug(1,"setting musicnode state value to 2");
-		}
 	if (_sub)
 		_engine->getSubtitleManager()->destroy(_sub);
-	debug(1, "MusicNode: %d destroyed", _key);
+	debug(3, "MusicNode: %d destroyed", _key);
 }
 
 void MusicNode::outputMixer() {
@@ -132,29 +130,34 @@ void MusicNode::outputMixer() {
 }
 
 void MusicNode::setFade(int32 time, uint8 target) {
-	_crossfadeTarget = target;
-	_crossfadeTime = time;
-	_crossfade = true;
+  fadeStartVol = _volume;
+	fadeEndVol = target;
+	fadeElapsed = 0;
+	fadeTime = time <= 0 ? 0 : (uint32)time;
+	_fade = true;
 }
 
 bool MusicNode::process(uint32 deltaTimeInMillis) {
 	if (!_loaded || ! _engine->_mixer->isSoundHandleActive(_handle))
 		return stop();
 	else {
-		uint8 _newvol = _volume;
-		if (_crossfade) {
-			if (_crossfadeTime > 0) {
-				if ((int32)deltaTimeInMillis > _crossfadeTime)
-					deltaTimeInMillis = _crossfadeTime;
-				_newvol += (int)(floor(((float)(_crossfadeTarget - _newvol) / (float)_crossfadeTime)) * (float)deltaTimeInMillis);
-				_crossfadeTime -= deltaTimeInMillis;
-			} else {
-				_crossfade = false;
-				_newvol = _crossfadeTarget;
-			}
+		if (_fade) {
+			debug(3,"Fading music, endVol %d, startVol %d, current %d, fade time %d, elapsed time %dms", fadeEndVol, fadeStartVol, _volume, fadeTime, fadeElapsed);
+		  uint8 _newvol = 0;
+		  fadeElapsed += deltaTimeInMillis;
+		  if( (fadeTime <= 0) | (fadeElapsed >= fadeTime) ) {
+        _newvol = fadeEndVol;
+		    _fade = false;
+		  }
+		  else {
+		    if(fadeEndVol > fadeStartVol)
+		      _newvol = fadeStartVol + (fadeElapsed*(fadeEndVol - fadeStartVol))/fadeTime;
+	      else
+  		    _newvol = fadeStartVol - (fadeElapsed*(fadeStartVol - fadeEndVol))/fadeTime;
+	    }
+		  if (_volume != _newvol)
+			  setVolume(_newvol);
 		}
-		if (_volume != _newvol)
-			setVolume(_newvol);
 		if (_sub && _engine->getScriptManager()->getStateValue(StateKey_Subtitles) == 1)
 			_engine->getSubtitleManager()->update(_engine->_mixer->getSoundElapsedTime(_handle) / 100, _sub);
 	}
@@ -173,6 +176,7 @@ PanTrackNode::PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos)
 	: ScriptingEffect(engine, key, SCRIPTING_EFFECT_PANTRACK) {
 	_slot = slot;
 	sourcePos = pos;
+  debug(3,"Created PanTrackNode, key %d, slot %d", _key, _slot);
 	process(0); 	// Try to set pan value for music node immediately
 }
 
@@ -180,6 +184,7 @@ PanTrackNode::~PanTrackNode() {
 }
 
 bool PanTrackNode::process(uint32 deltaTimeInMillis) {
+  debug(3,"Processing PanTrackNode, key %d, deltaT %d", _key, deltaTimeInMillis);
 	ScriptManager * scriptManager = _engine->getScriptManager();
 	ScriptingEffect *fx = scriptManager->getSideFX(_slot);
 	if (fx && fx->getType() == SCRIPTING_EFFECT_AUDIO) {
diff --git a/engines/zvision/scripting/effects/music_effect.h b/engines/zvision/scripting/effects/music_effect.h
index 5b3011f927f..2164d3e3199 100644
--- a/engines/zvision/scripting/effects/music_effect.h
+++ b/engines/zvision/scripting/effects/music_effect.h
@@ -59,7 +59,6 @@ protected:
   uint8 _volume = 0;
 	int8 _balance = 0;
   Math::Angle _azimuth;
-  uint8 fadeGain = 255;  //Linear scale, 255 corresponds to unity gain
 	uint8 volumeOut = 0;
 };
 
@@ -82,9 +81,11 @@ public:
 private:
   void outputMixer() override;
 	bool _loop;
-	bool _crossfade;
-	uint8 _crossfadeTarget;
-	int32 _crossfadeTime;
+	bool _fade;
+	uint8 fadeStartVol;
+	uint8 fadeEndVol;
+	uint32 fadeTime;
+	uint32 fadeElapsed; //Cumulative time since fade start
 	bool _stereo;
 	Audio::SoundHandle _handle;
 	uint16 _sub;


Commit: 65f409bc997f72f574cce1fc67a3bdb815c4c261
    https://github.com/scummvm/scummvm/commit/65f409bc997f72f574cce1fc67a3bdb815c4c261
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:56+02:00

Commit Message:
ZVISION: Added capacity to read auxiliary scripts for extra directional audio.
Additional debugging comments for developing these scripts.

Changed paths:
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/menu.cpp
    engines/zvision/scripting/scr_file_handling.cpp
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/sound/volume_manager.cpp
    engines/zvision/zvision.cpp


diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index 1450b967482..7eb1c89dc2f 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -547,18 +547,20 @@ ActionPanTrack::ActionPanTrack(ZVision *engine, int32 slotKey, const Common::Str
 	_pos(0),
 	_musicSlot(0) {
 	sscanf(line.c_str(), "%u %d", &_musicSlot, &_pos);
-	if(_scriptManager->getStateValue(_musicSlot) != 2)
+	if(_scriptManager->getStateValue(_musicSlot) != 2) {
+	  debug(2,"Setting musicSlot %d to 2", _musicSlot);
     _scriptManager->setStateValue(_musicSlot, 2); //Pan_track scripts do not always trigger correctly unless this is set!
-  debug(3,"Created Action: PanTrack, slotkey %d, musicSlot %u, pos %d", _slotKey, _musicSlot, _pos);
+  }
+  debug(2,"Created Action: PanTrack, slotkey %d, musicSlot %u, pos %d", _slotKey, _musicSlot, _pos);
 }
 
 ActionPanTrack::~ActionPanTrack() {
 	_scriptManager->killSideFx(_slotKey);
-  debug(3,"Destroyed Action: PanTrack, slotkey %d", _slotKey);
+  debug(2,"Destroyed Action: PanTrack, slotkey %d", _slotKey);
 }
 
 bool ActionPanTrack::execute() {
-  debug(3,"Executing Action: PanTrack, slotkey %d, musicSlot %u, pos %d", _slotKey, _musicSlot, _pos);
+  debug(2,"Executing Action: PanTrack, slotkey %d, musicSlot %u, pos %d", _slotKey, _musicSlot, _pos);
 	if (_scriptManager->getSideFX(_slotKey))
 		return true;
 	_scriptManager->addSideFX(new PanTrackNode(_engine, _slotKey, _musicSlot, _pos));
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 2e02589feec..3583282e78b 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -181,10 +181,11 @@ PanTrackNode::PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos)
 }
 
 PanTrackNode::~PanTrackNode() {
+  debug(1,"Deleting PanTrackNode, key %d, slot %d", _key, _slot);
 }
 
 bool PanTrackNode::process(uint32 deltaTimeInMillis) {
-  debug(3,"Processing PanTrackNode, key %d, deltaT %d", _key, deltaTimeInMillis);
+  debug(3,"Processing PanTrackNode, key %d", _key);
 	ScriptManager * scriptManager = _engine->getScriptManager();
 	ScriptingEffect *fx = scriptManager->getSideFX(_slot);
 	if (fx && fx->getType() == SCRIPTING_EFFECT_AUDIO) {
diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index 09170b1c2a2..29d6027db85 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -119,6 +119,7 @@ void MenuManager::onMouseDown(const Common::Point &Pos) {
       }
   }
   debug(1, "mouse position %d %d", Pos.x, Pos.y);
+  debug(1, "panorama position %d %d", Pos.x, Pos.y);
 }
 
 void MenuManager::onMouseMove(const Common::Point &Pos) {
diff --git a/engines/zvision/scripting/scr_file_handling.cpp b/engines/zvision/scripting/scr_file_handling.cpp
index 9e7f433db44..06e06af7aab 100644
--- a/engines/zvision/scripting/scr_file_handling.cpp
+++ b/engines/zvision/scripting/scr_file_handling.cpp
@@ -20,6 +20,7 @@
  */
 
 #include "common/scummsys.h"
+#include "common/str.h"
 
 #include "zvision/zvision.h"
 #include "zvision/scripting/script_manager.h"
@@ -44,29 +45,52 @@
 namespace ZVision {
 
 void ScriptManager::parseScrFile(const Common::Path &fileName, ScriptScope &scope) {
-	Common::File file;
-	if (!_engine->getSearchManager()->openFile(file, fileName))
+  auto parse = [&](Common::File &file) {
+	  while (!file.eos()) {
+		  Common::String line = file.readLine();
+		  if (file.err())
+			  error("Error parsing scr file: %s", fileName.toString().c_str());
+		  trimCommentsAndWhiteSpace(&line);
+		  if (line.empty())
+			  continue;
+		  if (line.matchString("puzzle:*", true)) {
+			  Puzzle *puzzle = new Puzzle();
+			  sscanf(line.c_str(), "puzzle:%u", &(puzzle->key));
+			  if (getStateFlag(puzzle->key) & Puzzle::ONCE_PER_INST)
+				  setStateValue(puzzle->key, 0);
+			  parsePuzzle(puzzle, file);
+			  scope.puzzles.push_back(puzzle);
+		  } 
+		  else if (line.matchString("control:*", true)) {
+			  Control *ctrl = parseControl(line, file);
+			  if (ctrl)
+				  scope.controls.push_back(ctrl);
+		  }
+	  }
+	};
+	
+	Common::File mainFile;
+	Common::File auxFile;
+	Common::String auxFileName = fileName.toString();
+  replace(auxFileName, Common::String(".scr"), Common::String(".aux"));
+  debug(1,"Auxiliary filename %s", auxFileName.c_str());
+  Common::Path auxFilePath(auxFileName);
+  debug(1,"Auxiliary path %s", auxFilePath.toString().c_str());
+  
+	if (!_engine->getSearchManager()->openFile(mainFile, fileName))
 		error("Script file not found: %s", fileName.toString().c_str());
-	while (!file.eos()) {
-		Common::String line = file.readLine();
-		if (file.err())
-			error("Error parsing scr file: %s", fileName.toString().c_str());
-		trimCommentsAndWhiteSpace(&line);
-		if (line.empty())
-			continue;
-		if (line.matchString("puzzle:*", true)) {
-			Puzzle *puzzle = new Puzzle();
-			sscanf(line.c_str(), "puzzle:%u", &(puzzle->key));
-			if (getStateFlag(puzzle->key) & Puzzle::ONCE_PER_INST)
-				setStateValue(puzzle->key, 0);
-			parsePuzzle(puzzle, file);
-			scope.puzzles.push_back(puzzle);
-		} 
-		else if (line.matchString("control:*", true)) {
-			Control *ctrl = parseControl(line, file);
-			if (ctrl)
-				scope.controls.push_back(ctrl);
-		}
+	else {
+    debug(1,"Parsing primary script file");
+  	parse(mainFile);
+	  if (auxFile.exists(auxFilePath)) {
+	    debug(1,"Auxiliary script file found");
+	    if (auxFile.open(auxFilePath)) {
+	      debug(1,"Parsing auxiliary script file %s", auxFilePath.toString().c_str());
+        parse(auxFile);
+      }
+      else
+        debug(1,"Unable to open auxiliary script file %s", auxFilePath.toString().c_str());
+    }
 	}
 	scope.procCount = 0;
 }
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index 02bc27695dc..12cc672b5fd 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -243,7 +243,7 @@ bool ScriptManager::checkPuzzleCriteria(Puzzle *puzzle, uint counter) {
 	}
 	// criteriaList can be empty. Aka, the puzzle should be executed immediately
 	if (puzzle->criteriaList.empty() || criteriaMet) {
-		debug(3, "Puzzle %u criteria passed. Executing its ResultActions", puzzle->key);
+		debug(5, "Puzzle %u criteria passed. Executing its ResultActions", puzzle->key);
 		// Set the puzzle as completed
 		setStateValue(puzzle->key, 1);
 		for (Common::List<ResultAction *>::iterator resultIter = puzzle->resultActions.begin(); resultIter != puzzle->resultActions.end(); ++resultIter) {
@@ -425,6 +425,7 @@ void ScriptManager::killSideFxType(ScriptingEffect::ScriptingEffectType type) {
 }
 
 void ScriptManager::onMouseDown(const Common::Point &screenSpacePos, const Common::Point &backgroundImageSpacePos) {
+  debug(1,"Mouse panorama/script coordinates %d x %d", backgroundImageSpacePos.x, backgroundImageSpacePos.y);
 	if (!_activeControls)
 		return;
 	for (ControlList::iterator iter = _activeControls->reverse_begin(); iter != _activeControls->end(); iter--) {
@@ -642,7 +643,9 @@ void ScriptManager::serialize(Common::WriteStream *stream) {
 	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); ++iter)
 		(*iter)->serialize(stream);
 	stream->writeUint32BE(MKTAG('F', 'L', 'A', 'G'));
-	int32 slots = _engine->getGameId() == GID_NEMESIS ? 30000 : 20000;
+	int32 slots = _engine->getGameId() == GID_NEMESIS ? 31000 : 21000;  
+	//Original games use key values up to 29500 and 19737, respectively
+	//Values 30001~31000 and 20001~21000 are now set aside for auxiliary scripting to add extra directional audio effects.
 	stream->writeUint32LE(slots * 2);
 	for (int32 i = 0; i < slots; i++)
 		stream->writeUint16LE(getStateFlag(i));
diff --git a/engines/zvision/sound/volume_manager.cpp b/engines/zvision/sound/volume_manager.cpp
index dcb50702806..a70c165e726 100644
--- a/engines/zvision/sound/volume_manager.cpp
+++ b/engines/zvision/sound/volume_manager.cpp
@@ -149,7 +149,7 @@ uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode, Math::Angle a
   uint8 index = abs(round(azimuth.getDegrees(-180)));
   output *= directionalAmplitude[index];
   output /= 255;
-  debug(2,"Azimuth-scaled converted output %d", output);
+  debug(4,"Azimuth-scaled converted output %d", output);
   return output;
 };
 
@@ -181,7 +181,7 @@ uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode) {
       output = scaledInput;
       break;
   }
-  debug(2,"Scripted volume %d, scaled volume %d, converted output %d", inputValue, scaledInput, output);
+  debug(4,"Scripted volume %d, scaled volume %d, converted output %d", inputValue, scaledInput, output);
   return output;
 };
 
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index e9318d3d693..bcc992bd12a 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -73,7 +73,7 @@ struct zvisionIniSettings {
 	{"debugcheats", StateKey_DebugCheats, -1, true, false},	// always start with the GOxxxx cheat enabled
 	// Editable settings
 	{"highquality", StateKey_HighQuality, -1, true, false},	// high panorama quality
-	{"qsoundenabled", StateKey_Qsound, -1, true, false},	// 1 = enable generic directional audio and non-linear volume scaling.  Genuine Qsound is copyright & unlikely to be implemented.
+	{"qsoundenabled", StateKey_Qsound, -1, true, true},	// 1 = enable generic directional audio and non-linear volume scaling.  Genuine Qsound is copyright & unlikely to be implemented.
 	{"keyboardturnspeed", StateKey_KbdRotateSpeed, 5, false, true},
 	{"panarotatespeed", StateKey_RotateSpeed, 540, false, true},	// checked by universe.scr
 	{"noanimwhileturning", StateKey_NoTurnAnim, -1, false, true},	// toggle playing animations during pana rotation


Commit: 9d87cfc5973a8d4829bbf559f486034fbbd9fdfa
    https://github.com/scummvm/scummvm/commit/9d87cfc5973a8d4829bbf559f486034fbbd9fdfa
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:56+02:00

Commit Message:
ZVISION: Alter ~PanTrackNode() to restore audio balance to centre.

Changed paths:
    engines/zvision/scripting/effects/music_effect.cpp


diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 3583282e78b..558249f00ff 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -181,6 +181,12 @@ PanTrackNode::PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos)
 }
 
 PanTrackNode::~PanTrackNode() {
+	ScriptManager * scriptManager = _engine->getScriptManager();
+	ScriptingEffect *fx = scriptManager->getSideFX(_slot);
+	if (fx && fx->getType() == SCRIPTING_EFFECT_AUDIO) {
+		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
+    mus->setBalance(0);
+  }
   debug(1,"Deleting PanTrackNode, key %d, slot %d", _key, _slot);
 }
 


Commit: c7ec0b989c6529e5fb6f598855a98c3589ac0041
    https://github.com/scummvm/scummvm/commit/c7ec0b989c6529e5fb6f598855a98c3589ac0041
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:56+02:00

Commit Message:
ZVISION: Added functionality to PanTrackNode() to support auxiliary scripts.
Code cleanup, additional comment details & additional debug messages for script development.
TODO: Add effect magnitude control functionality to volume manager & PanTrackNode.

Changed paths:
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/actions.h
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/effects/music_effect.h
    engines/zvision/scripting/scr_file_handling.cpp
    engines/zvision/sound/volume_manager.cpp


diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index 7eb1c89dc2f..8ac0ba15ad5 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -545,13 +545,28 @@ bool ActionMusic::execute() {
 ActionPanTrack::ActionPanTrack(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey),
 	_pos(0),
+	_mag(255),
+	_resetMusicNode(true),
+	_resetMixerOnDelete(false),
 	_musicSlot(0) {
-	sscanf(line.c_str(), "%u %d", &_musicSlot, &_pos);
-	if(_scriptManager->getStateValue(_musicSlot) != 2) {
-	  debug(2,"Setting musicSlot %d to 2", _musicSlot);
-    _scriptManager->setStateValue(_musicSlot, 2); //Pan_track scripts do not always trigger correctly unless this is set!
+	uint mag = 255;
+	uint resetMusicNode = 1;
+	uint resetMixerOnDelete = 0;
+	sscanf(line.c_str(), "%u %d %u %u %u", &_musicSlot, &_pos, &mag, &resetMusicNode, &resetMixerOnDelete);
+	_resetMusicNode = resetMusicNode > 0;
+  _resetMixerOnDelete = resetMixerOnDelete > 0;
+	_mag = mag;
+	if(_resetMusicNode) {
+	  if(_scriptManager->getStateValue(_musicSlot) != 2) {
+	    debug(2,"Forcing musicSlot %d to 2", _musicSlot);
+      _scriptManager->setStateValue(_musicSlot, 2); //Not all original game pan_track scripts trigger correctly unless this is set!
+    }
+    else
+      debug(2,"musicSlot %d already set to 2", _musicSlot);
   }
-  debug(2,"Created Action: PanTrack, slotkey %d, musicSlot %u, pos %d", _slotKey, _musicSlot, _pos);
+  else
+    debug(2,"NOT forcing musicSlot %d to 2", _musicSlot);
+  debug(2,"Created Action: PanTrack, slotkey %d, musicSlot %u, pos %d, mag %d", _slotKey, _musicSlot, _pos, _mag);
 }
 
 ActionPanTrack::~ActionPanTrack() {
@@ -560,10 +575,10 @@ ActionPanTrack::~ActionPanTrack() {
 }
 
 bool ActionPanTrack::execute() {
-  debug(2,"Executing Action: PanTrack, slotkey %d, musicSlot %u, pos %d", _slotKey, _musicSlot, _pos);
+  debug(2,"Executing Action: PanTrack, slotkey %d, musicSlot %u, pos %d, mag %d", _slotKey, _musicSlot, _pos, _mag);
 	if (_scriptManager->getSideFX(_slotKey))
 		return true;
-	_scriptManager->addSideFX(new PanTrackNode(_engine, _slotKey, _musicSlot, _pos));
+	_scriptManager->addSideFX(new PanTrackNode(_engine, _slotKey, _musicSlot, _pos, _mag, _resetMixerOnDelete));
 	return true;
 }
 
diff --git a/engines/zvision/scripting/actions.h b/engines/zvision/scripting/actions.h
index 4b552d23310..903de8dbbcb 100644
--- a/engines/zvision/scripting/actions.h
+++ b/engines/zvision/scripting/actions.h
@@ -240,6 +240,15 @@ public:
 
 private:
 	int32 _pos; //Sound source position in panorama
+	uint8  _mag; //Magnitude of effect (not used by original game scripts); 255 for fully directional sound, 0 for fully ambient
+	bool _resetMusicNode; //If true (default, original game scripts have no concept of this), associated music slot value is reset to a value of 2 upon creation of this object; 
+	/*
+	* this seems necessary to ensure all original game pan-track effects load correctly, though it is still unclear exactly what the original intent of these values was.
+	* So far, best guess for music slotkey values is: 0 = has never been loaded, 1 = loaded and actively playing now, 2 = has loaded & played & then subsequently been killed.
+	* Since there is literally nothing in the game scripts that sets some of these values to 2, and certain pan_tracks require it to be 2 for the puzzle that creates them to trigger,
+	* the original game engine code must have set these values to 2 manually somehow upon conditions being met to allow a pan_track to be created?
+	*/
+	bool _resetMixerOnDelete; //Unnecessary and should be set false for original scripts; useful in some cases in extra scripts to avoid brief volume spikes on location changes
 	uint32 _musicSlot;
 };
 
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 558249f00ff..5bbea165b48 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -172,22 +172,30 @@ void MusicNode::setVolume(uint8 newVolume) {
 }
 
 
-PanTrackNode::PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos)
-	: ScriptingEffect(engine, key, SCRIPTING_EFFECT_PANTRACK) {
-	_slot = slot;
-	sourcePos = pos;
+PanTrackNode::PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos, uint8 mag, bool resetMixerOnDelete)
+	: ScriptingEffect(engine, key, SCRIPTING_EFFECT_PANTRACK),
+	_slot(slot),
+	sourcePos(pos),
+	_mag(mag),
+	_resetMixerOnDelete(resetMixerOnDelete) {
+//	_slot = slot;
+//	sourcePos = pos;
+//	_mag = mag;
   debug(3,"Created PanTrackNode, key %d, slot %d", _key, _slot);
 	process(0); 	// Try to set pan value for music node immediately
 }
 
 PanTrackNode::~PanTrackNode() {
+  debug(1,"Deleting PanTrackNode, key %d, slot %d", _key, _slot);
 	ScriptManager * scriptManager = _engine->getScriptManager();
 	ScriptingEffect *fx = scriptManager->getSideFX(_slot);
-	if (fx && fx->getType() == SCRIPTING_EFFECT_AUDIO) {
-		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
+  if (fx && fx->getType() == SCRIPTING_EFFECT_AUDIO && _resetMixerOnDelete) {
+    debug(1,"Resetting mixer, slot %d", _slot);
+	  MusicNodeBASE *mus = (MusicNodeBASE *)fx;
     mus->setBalance(0);
   }
-  debug(1,"Deleting PanTrackNode, key %d, slot %d", _key, _slot);
+  else
+    debug(1,"NOT resetting mixer, slot %d", _slot);
 }
 
 bool PanTrackNode::process(uint32 deltaTimeInMillis) {
@@ -198,9 +206,6 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
 		int viewPos = scriptManager->getStateValue(StateKey_ViewPos);
 		int16 _width = _engine->getRenderManager()->getBkgSize().x;
-//		int16 _halfWidth = _width / 2;
-//		int16 _quarterWidth = _width / 4;
-
 		int deltaPos = 0;
 		if (viewPos <= sourcePos)
 			deltaPos = sourcePos - viewPos;
@@ -208,44 +213,7 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 			deltaPos = sourcePos - viewPos + _width;
 		debug(3,"soundPos: %d, viewPos: %d, deltaPos: %d, width: %d", sourcePos, viewPos, deltaPos, _width);
     //deltaPos is sound source position relative to player, clockwise from centre of camera axis to front when viewed top-down
-//*/
-    //NEW SYSTEM
     mus->setAzimuth(Math::Angle(360*deltaPos/_width));
-      
-/*/
-    //OLD SYSTEM;		
-		int balance = 0;
-		if (deltaPos > _halfWidth)  //Source to left
-			deltaPos -= _width; //Make angle negative relative to datum
-		if (deltaPos > _quarterWidth) {
-			balance = 1;
-			deltaPos = _halfWidth - deltaPos; //Make relative to right centre?
-		} else if (deltaPos < -_quarterWidth) {
-			balance = -1;
-			deltaPos = -_halfWidth - deltaPos;  //Make relative to left centre?
-		}
-
-		// Originally it's value -90...90 but we use -127...127 and therefore 360 replaced by 508
-		// Left = -127, centre = 0, right = +127
-		mus->setBalance( (508 * deltaPos) / _width );
-		deltaPos = (360 * deltaPos) / _width;
-		int deltaVol = balance;
-		debug(1,"Balance %d", balance);
-
-		// This value sets how fast volume goes off than sound source back of you
-		// By this value we can hack some "bugs" have place in original game engine like beat sound in ZGI-dc10
-		int volumeCorrection = 2;
-
-		if (_engine->getGameId() == GID_GRANDINQUISITOR) {
-			if (scriptManager->getCurrentLocation() == "dc10")
-				volumeCorrection = 5;
-		}
-		if (deltaVol != 0)
-			deltaVol = (mus->getVolume() * volumeCorrection) * (90 - deltaPos * balance) / 90;
-		if (deltaVol > 255)
-			deltaVol = 255;
-		mus->setDeltaVolume(deltaVol);
-//*/
 	}
 	return false;
 }
diff --git a/engines/zvision/scripting/effects/music_effect.h b/engines/zvision/scripting/effects/music_effect.h
index 2164d3e3199..8199e6c8591 100644
--- a/engines/zvision/scripting/effects/music_effect.h
+++ b/engines/zvision/scripting/effects/music_effect.h
@@ -119,13 +119,15 @@ private:
 
 class PanTrackNode : public ScriptingEffect {
 public:
-	PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos);
+	PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos, uint8 mag=255, bool resetMixerOnDelete=false);
 	~PanTrackNode() override;
 	bool process(uint32 deltaTimeInMillis) override;
 
 private:
 	uint32 _slot;
 	int16 sourcePos;
+	uint8 _mag;
+	bool _resetMixerOnDelete;
 };
 
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/scr_file_handling.cpp b/engines/zvision/scripting/scr_file_handling.cpp
index 06e06af7aab..82857ae6d8c 100644
--- a/engines/zvision/scripting/scr_file_handling.cpp
+++ b/engines/zvision/scripting/scr_file_handling.cpp
@@ -82,6 +82,7 @@ void ScriptManager::parseScrFile(const Common::Path &fileName, ScriptScope &scop
 	else {
     debug(1,"Parsing primary script file");
   	parse(mainFile);
+  	//TODO - add config option to disable/enable auxiliary scripting
 	  if (auxFile.exists(auxFilePath)) {
 	    debug(1,"Auxiliary script file found");
 	    if (auxFile.open(auxFilePath)) {
diff --git a/engines/zvision/sound/volume_manager.cpp b/engines/zvision/sound/volume_manager.cpp
index a70c165e726..844413c7894 100644
--- a/engines/zvision/sound/volume_manager.cpp
+++ b/engines/zvision/sound/volume_manager.cpp
@@ -109,7 +109,7 @@ static constexpr uint8 logAmplitude[256] = {
 /*
 Estimated relative amplitude of a point sound source as it circles the listener's head from front to rear, due to ear pinna shape.
 Maximum attenuation -5dB when fully to rear.  Seems to give a reasonably realistic effect when tested on the Nemesis cloister fountain.
-Ideally should be applied AFTER volume profile is applied to script files.
+Should be applied AFTER volume profile is applied to script files.
 Generating function:
   for 0 < theta < 90, amp = 255;
   for 90 < theta < 180, amp = 255*10^(1-(cos(2*(theta-90))/4))


Commit: ed0f25b7b981882636481bf9e221e5f02a2693d8
    https://github.com/scummvm/scummvm/commit/ed0f25b7b981882636481bf9e221e5f02a2693d8
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:56+02:00

Commit Message:
ZVISION: Add variable directionality to PanTrackNode & VolumeManager.
Add support for using PanTrackNode in static screens, specifying azimuth in degrees.
Rename setAzimuth() to setDirection() for clarity.

Changed paths:
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/actions.h
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/effects/music_effect.h
    engines/zvision/sound/volume_manager.cpp
    engines/zvision/sound/volume_manager.h


diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index 8ac0ba15ad5..ffb124b565f 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -549,9 +549,9 @@ ActionPanTrack::ActionPanTrack(ZVision *engine, int32 slotKey, const Common::Str
 	_resetMusicNode(true),
 	_resetMixerOnDelete(false),
 	_musicSlot(0) {
-	uint mag = 255;
-	uint resetMusicNode = 1;
-	uint resetMixerOnDelete = 0;
+	uint mag = 255;  //Original game scripts do not specify this, but require it to be 255 to work correctly.
+	uint resetMusicNode = 1;  //Original game scripts do not specify this, but require it to be true to work correctly.
+	uint resetMixerOnDelete = 0;  //Original game scripts do not specify this, but require it to be false to work correctly.
 	sscanf(line.c_str(), "%u %d %u %u %u", &_musicSlot, &_pos, &mag, &resetMusicNode, &resetMixerOnDelete);
 	_resetMusicNode = resetMusicNode > 0;
   _resetMixerOnDelete = resetMixerOnDelete > 0;
diff --git a/engines/zvision/scripting/actions.h b/engines/zvision/scripting/actions.h
index 903de8dbbcb..3ec117ea1c2 100644
--- a/engines/zvision/scripting/actions.h
+++ b/engines/zvision/scripting/actions.h
@@ -239,7 +239,7 @@ public:
 	bool execute() override;
 
 private:
-	int32 _pos; //Sound source position in panorama
+	int32 _pos; //Sound source position; NB in panoramas (all original game scripts), this is specified as the X background coordinate; otherwise it is specified in azimuth degrees.
 	uint8  _mag; //Magnitude of effect (not used by original game scripts); 255 for fully directional sound, 0 for fully ambient
 	bool _resetMusicNode; //If true (default, original game scripts have no concept of this), associated music slot value is reset to a value of 2 upon creation of this object; 
 	/*
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 5bbea165b48..c177702e1b6 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -40,10 +40,11 @@
 
 namespace ZVision {
 
-void MusicNodeBASE::setAzimuth(Math::Angle azimuth) {
+void MusicNodeBASE::setDirection(Math::Angle azimuth, uint8 magnitude) {
   if(_engine->getScriptManager()->getStateValue(StateKey_Qsound) >= 1) {
     _azimuth = azimuth;
-    _balance = (int)(127*_azimuth.getSine());
+    _directionality = magnitude;
+    _balance = ((int)(127*_azimuth.getSine())*_directionality)/255;
   }
 	updateMixer();
 }
@@ -51,12 +52,13 @@ void MusicNodeBASE::setAzimuth(Math::Angle azimuth) {
 void MusicNodeBASE::setBalance(int8 balance) {
   _balance = balance;
   _azimuth.setDegrees(0);
+  _directionality = 255;
 	updateMixer();
 }
 
 void MusicNodeBASE::updateMixer() {
   if(_engine->getScriptManager()->getStateValue(StateKey_Qsound) >= 1)
-    volumeOut = _engine->getVolumeManager()->convert(_volume, _azimuth);  //Apply volume profile and then attenuate according to azimuth
+    volumeOut = _engine->getVolumeManager()->convert(_volume, _azimuth, _directionality);  //Apply volume profile and then attenuate according to azimuth
   else
     volumeOut = _engine->getVolumeManager()->convert(_volume, kVolumeLinear);  //Apply linear volume profile and ignore azimuth
   outputMixer();
@@ -175,12 +177,22 @@ void MusicNode::setVolume(uint8 newVolume) {
 PanTrackNode::PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos, uint8 mag, bool resetMixerOnDelete)
 	: ScriptingEffect(engine, key, SCRIPTING_EFFECT_PANTRACK),
 	_slot(slot),
-	sourcePos(pos),
+	sourcePos(0),
+	viewPos(0),
 	_mag(mag),
+	_width(0),
 	_resetMixerOnDelete(resetMixerOnDelete) {
-//	_slot = slot;
-//	sourcePos = pos;
-//	_mag = mag;
+	switch(_engine->getRenderManager()->getRenderTable()->getRenderState()) {
+	  case RenderTable::PANORAMA :
+	    _width = _engine->getRenderManager()->getBkgSize().x;
+	    sourcePos.setDegrees(360*pos/_width);
+	    break;	
+	  case RenderTable::FLAT :
+	  case RenderTable::TILT :
+	  default :
+	    sourcePos.setDegrees(pos);
+	    break;
+	}
   debug(3,"Created PanTrackNode, key %d, slot %d", _key, _slot);
 	process(0); 	// Try to set pan value for music node immediately
 }
@@ -204,16 +216,21 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 	ScriptingEffect *fx = scriptManager->getSideFX(_slot);
 	if (fx && fx->getType() == SCRIPTING_EFFECT_AUDIO) {
 		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
-		int viewPos = scriptManager->getStateValue(StateKey_ViewPos);
-		int16 _width = _engine->getRenderManager()->getBkgSize().x;
-		int deltaPos = 0;
-		if (viewPos <= sourcePos)
-			deltaPos = sourcePos - viewPos;
-		else
-			deltaPos = sourcePos - viewPos + _width;
-		debug(3,"soundPos: %d, viewPos: %d, deltaPos: %d, width: %d", sourcePos, viewPos, deltaPos, _width);
-    //deltaPos is sound source position relative to player, clockwise from centre of camera axis to front when viewed top-down
-    mus->setAzimuth(Math::Angle(360*deltaPos/_width));
+	  switch(_engine->getRenderManager()->getRenderTable()->getRenderState()) {
+	    case RenderTable::PANORAMA :
+	      viewPos.setDegrees(360*scriptManager->getStateValue(StateKey_ViewPos)/_width);
+	      break;	
+	    case RenderTable::FLAT :
+	    case RenderTable::TILT :
+	    default :
+	      viewPos.setDegrees(0);
+	      break;
+	  }
+		Math::Angle azimuth;
+		azimuth = sourcePos - viewPos;
+		debug(3,"soundPos: %f, viewPos: %f, azimuth: %f, width %d", sourcePos.getDegrees(), viewPos.getDegrees(), azimuth.getDegrees(), _width);
+    //azimuth is sound source position relative to player, clockwise from centre of camera axis to front when viewed top-down
+    mus->setDirection(azimuth, _mag);
 	}
 	return false;
 }
diff --git a/engines/zvision/scripting/effects/music_effect.h b/engines/zvision/scripting/effects/music_effect.h
index 8199e6c8591..0ff730843fa 100644
--- a/engines/zvision/scripting/effects/music_effect.h
+++ b/engines/zvision/scripting/effects/music_effect.h
@@ -26,6 +26,7 @@
 #include "zvision/scripting/scripting_effect.h"
 #include "zvision/text/subtitle_manager.h"
 #include "zvision/sound/volume_manager.h"
+#include "math/angle.h"
 
 namespace Common {
 class String;
@@ -50,8 +51,8 @@ public:
 	virtual void setVolume(uint8 volume) = 0;
 	uint8 getVolume() {return _volume;};
 	virtual void setFade(int32 time, uint8 target) = 0;
-	virtual void setBalance(int8 balance);  //NB Overrides effects of setAzimuth()
-	void setAzimuth(Math::Angle azimuth);  //NB Overrides effects of setBalance()
+	virtual void setBalance(int8 balance);  //NB Overrides effects of setDirection()
+	void setDirection(Math::Angle azimuth, uint8 magnitude = 255);  //NB Overrides effects of setBalance()
 protected:
   void updateMixer();
   virtual void outputMixer() = 0;
@@ -59,6 +60,7 @@ protected:
   uint8 _volume = 0;
 	int8 _balance = 0;
   Math::Angle _azimuth;
+  uint8 _directionality;  //0 = fully ambient, 255 = fully directional
 	uint8 volumeOut = 0;
 };
 
@@ -125,9 +127,11 @@ public:
 
 private:
 	uint32 _slot;
-	int16 sourcePos;
+	int16 _width;
+  Math::Angle sourcePos, viewPos;
 	uint8 _mag;
 	bool _resetMixerOnDelete;
+	bool staticScreen;
 };
 
 } // End of namespace ZVision
diff --git a/engines/zvision/sound/volume_manager.cpp b/engines/zvision/sound/volume_manager.cpp
index 844413c7894..b28c47798f1 100644
--- a/engines/zvision/sound/volume_manager.cpp
+++ b/engines/zvision/sound/volume_manager.cpp
@@ -140,16 +140,18 @@ uint8 VolumeManager::convert(uint8 inputValue) {
   return convert(inputValue, _mode);
 };
   
-uint8 VolumeManager::convert(uint8 inputValue, Math::Angle azimuth) {
-  return convert(inputValue, _mode, azimuth);
+uint8 VolumeManager::convert(uint8 inputValue, Math::Angle azimuth, uint8 directionality) {
+  return convert(inputValue, _mode, azimuth, directionality);
 };
 
-uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode, Math::Angle azimuth) {
-  uint16 output = convert(inputValue, mode);
+uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode, Math::Angle azimuth, uint8 directionality) {
   uint8 index = abs(round(azimuth.getDegrees(-180)));
-  output *= directionalAmplitude[index];
-  output /= 255;
-  debug(4,"Azimuth-scaled converted output %d", output);
+  uint32 output = convert(inputValue, mode);
+  uint32 directionalOutput = (output * directionalAmplitude[index]) * directionality;
+  directionalOutput /= 255;
+  output *= (255-directionality);
+  output = (output + directionalOutput)/255;
+  debug(4,"Directionally converted output %d", output);
   return output;
 };
 
diff --git a/engines/zvision/sound/volume_manager.h b/engines/zvision/sound/volume_manager.h
index bdc95446e28..4bdd784aafb 100644
--- a/engines/zvision/sound/volume_manager.h
+++ b/engines/zvision/sound/volume_manager.h
@@ -46,8 +46,8 @@ public:
   void setMode(volumeScaling mode) {_mode = mode;};
   uint8 convert(uint8 inputValue);
   uint8 convert(uint8 inputValue, volumeScaling mode);
-  uint8 convert(uint8 inputValue, Math::Angle azimuth);
-  uint8 convert(uint8 inputValue, volumeScaling mode, Math::Angle azimuth);
+  uint8 convert(uint8 inputValue, Math::Angle azimuth, uint8 directionality=255);
+  uint8 convert(uint8 inputValue, volumeScaling mode, Math::Angle azimuth, uint8 directionality=255);
 private:
 	ZVision *_engine;
   uint scriptScale = 100; //Z-Vision scripts internally use a volume scale of 0-100; ScummVM uses a scale of 0-255.


Commit: 5f1b1591beba09ef17d932c6741f3cddc835ce80
    https://github.com/scummvm/scummvm/commit/5f1b1591beba09ef17d932c6741f3cddc835ce80
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:56+02:00

Commit Message:
ZVISION: First attempt at high quality panorama graphics filter.
Not functional, but data structures established for future development.

Changed paths:
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h


diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index f16409541e4..9b2936455d4 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -32,7 +32,7 @@ RenderTable::RenderTable(uint numColumns, uint numRows)
 	  _numColumns(numColumns),
 	  _renderState(FLAT) {
 	assert(numRows != 0 && numColumns != 0);
-	_internalBuffer = new Common::Point[numRows * numColumns];
+	_internalBuffer = new FilterPixel[numRows * numColumns];
 	memset(&_panoramaOptions, 0, sizeof(_panoramaOptions));
 	memset(&_tiltOptions, 0, sizeof(_tiltOptions));
 }
@@ -72,42 +72,93 @@ const Common::Point RenderTable::convertWarpedCoordToFlatCoord(const Common::Poi
 	}
 	uint32 index = point.y * _numColumns + point.x;
 	Common::Point newPoint(point);
-	newPoint.x += _internalBuffer[index].x;
-	newPoint.y += _internalBuffer[index].y;
+	newPoint.x += (_internalBuffer[index].fracX >= 128 ? _internalBuffer[index].Src.right : _internalBuffer[index].Src.left);
+	newPoint.y += (_internalBuffer[index].fracY >= 128 ? _internalBuffer[index].Src.bottom : _internalBuffer[index].Src.top);
 	return newPoint;
 }
 
 void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 destWidth, const Common::Rect &subRect) {
 	uint32 destOffset = 0;
-	for (int16 y = subRect.top; y < subRect.bottom; ++y) {
-		uint32 sourceOffset = y * _numColumns;
-		for (int16 x = subRect.left; x < subRect.right; ++x) {
-			uint32 normalizedX = x - subRect.left;
-			uint32 index = sourceOffset + x;
-			// RenderTable only stores offsets from the original coordinates
-			uint32 sourceYIndex = y + _internalBuffer[index].y;
-			uint32 sourceXIndex = x + _internalBuffer[index].x;
-			destBuffer[destOffset + normalizedX] = sourceBuffer[sourceYIndex * _numColumns + sourceXIndex];
-		}
-		destOffset += destWidth;
-	}
+  uint32 sourceXIndex = 0;
+  uint32 sourceYIndex = 0;
+  if(highQuality) {
+    //TODO - convert to high quality pixel filtering
+	  for (int16 y = subRect.top; y < subRect.bottom; ++y) {
+		  uint32 sourceOffset = y * _numColumns;
+		  for (int16 x = subRect.left; x < subRect.right; ++x) {
+			  uint32 normalizedX = x - subRect.left;
+			  uint32 index = sourceOffset + x;
+			  // RenderTable only stores offsets from the original coordinates
+			  sourceYIndex = y + _internalBuffer[index].Src.top;
+			  sourceXIndex = x + _internalBuffer[index].Src.left;
+			  destBuffer[destOffset + normalizedX] = sourceBuffer[sourceYIndex * _numColumns + sourceXIndex];
+		  }
+		  destOffset += destWidth;
+	  }
+  }
+  else {
+	  for (int16 y = subRect.top; y < subRect.bottom; ++y) {
+		  uint32 sourceOffset = y * _numColumns;
+		  for (int16 x = subRect.left; x < subRect.right; ++x) {
+			  uint32 normalizedX = x - subRect.left;
+			  uint32 index = sourceOffset + x;
+			  // RenderTable only stores offsets from the original coordinates
+			  sourceYIndex = y + _internalBuffer[index].Src.top;
+			  sourceXIndex = x + _internalBuffer[index].Src.left;
+			  destBuffer[destOffset + normalizedX] = sourceBuffer[sourceYIndex * _numColumns + sourceXIndex];
+		  }
+		  destOffset += destWidth;
+	  }
+  }
 }
 
 void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf) {
 	uint32 destOffset = 0;
+  uint32 srcIndexXL = 0;
+  uint32 srcIndexXR = 0;
+  uint32 srcIndexYT = 0;
+  uint32 srcIndexYB = 0;
 	uint16 *sourceBuffer = (uint16 *)srcBuf->getPixels();
 	uint16 *destBuffer = (uint16 *)dstBuf->getPixels();
-	for (int16 y = 0; y < srcBuf->h; ++y) {
-		uint32 sourceOffset = y * _numColumns;
-		for (int16 x = 0; x < srcBuf->w; ++x) {
-			uint32 index = sourceOffset + x;
-			// RenderTable only stores offsets from the original coordinates
-			uint32 sourceYIndex = y + _internalBuffer[index].y;
-			uint32 sourceXIndex = x + _internalBuffer[index].x;
-			destBuffer[destOffset] = sourceBuffer[sourceYIndex * _numColumns + sourceXIndex];
-			destOffset++;
-		}
-	}
+	uint32 averageBufferA = 0;
+	uint32 averageBufferB = 0;
+  if(highQuality) {
+    //TODO - convert to high quality pixel filtering
+	  for (int16 y = 0; y < srcBuf->h; ++y) {
+		  uint32 sourceOffset = y * _numColumns;
+		  for (int16 x = 0; x < srcBuf->w; ++x) {
+			  uint32 index = sourceOffset + x;
+			  // RenderTable only stores offsets from the original coordinates
+			  srcIndexYT = y + (_internalBuffer[index].fracY < 170 ? _internalBuffer[index].Src.top : _internalBuffer[index].Src.bottom);
+			  srcIndexYB = y + (_internalBuffer[index].fracY > 85 ? _internalBuffer[index].Src.bottom :  _internalBuffer[index].Src.top);
+			  srcIndexXL = x + (_internalBuffer[index].fracX < 170 ? _internalBuffer[index].Src.left :  _internalBuffer[index].Src.right);
+			  srcIndexXR = x + (_internalBuffer[index].fracX > 85 ? _internalBuffer[index].Src.right :  _internalBuffer[index].Src.left);
+			  
+			  averageBufferA = sourceBuffer[srcIndexYT * _numColumns + srcIndexXL];
+			  averageBufferA += sourceBuffer[srcIndexYT * _numColumns + srcIndexXR];
+			  averageBufferB = sourceBuffer[srcIndexYB * _numColumns + srcIndexXL];
+			  averageBufferB += sourceBuffer[srcIndexYB * _numColumns + srcIndexXR];
+			  
+        destBuffer[destOffset] = (averageBufferA/2 + averageBufferB/2)/2; //TODO - fix this; naive averaging not working properly.
+			  
+			  //destBuffer[destOffset] = sourceBuffer[sourceYIndex * _numColumns + sourceXIndex];
+			  destOffset++;
+		  }
+	  }
+  }
+  else {
+	  for (int16 y = 0; y < srcBuf->h; ++y) {
+		  uint32 sourceOffset = y * _numColumns;
+		  for (int16 x = 0; x < srcBuf->w; ++x) {
+			  uint32 index = sourceOffset + x;
+			  // RenderTable only stores offsets from the original coordinates
+			  srcIndexYT = y + _internalBuffer[index].Src.top;
+    		srcIndexXL = x + _internalBuffer[index].Src.left;
+			  destBuffer[destOffset] = sourceBuffer[srcIndexYT * _numColumns + srcIndexXL];
+			  destOffset++;
+		  }
+	  }
+  }
 }
 
 void RenderTable::generateRenderTable() {
@@ -126,18 +177,16 @@ void RenderTable::generateRenderTable() {
 	}
 }
 
-/*/
-Common::Point generatePanoramaLookupPoint() {
-
-  }
-//*/
-
 void RenderTable::generatePanoramaLookupTable() {
 	uint halfRows = ceil(_numRows/2);
 	uint halfColumns = ceil(_numColumns/2);
 	float halfWidth = (float)_numColumns / 2.0f;
 	float halfHeight = (float)_numRows / 2.0f;
 	float cylinderRadius = halfHeight / tan(_panoramaOptions.verticalFOV);
+	float xOffset = 0.0f;
+	float yOffset = 0.0f;
+	
+	FilterPixel currentFpixel;
 	
 	//Transformation is both horizontally and vertically symmetrical about the camera axis,
 	//We can thus save on trigonometric calculations by computing one quarter of the transformation matrix and then mirroring it in both X & Y
@@ -148,8 +197,7 @@ void RenderTable::generatePanoramaLookupTable() {
 
 		// To get x in cylinder coordinates, we just need to calculate the arc length
 		// We also scale it by _panoramaOptions.linearScale
-		int32 xInCylinderCoords = int32(round((cylinderRadius * _panoramaOptions.linearScale * alpha) + halfWidth));
-
+		float xInCylinderCoords = (cylinderRadius * _panoramaOptions.linearScale * alpha) + halfWidth;
 		float cosAlpha = cos(alpha);
 		uint32 columnIndexL = x;
 		uint32 columnIndexR = (_numColumns - 1) - x;
@@ -159,24 +207,23 @@ void RenderTable::generatePanoramaLookupTable() {
 		for (uint y = 0; y < halfRows; ++y) {
 			// To calculate y in cylinder coordinates, we can do similar triangles comparison,
 			// comparing the triangle from the center to the screen and from the center to the edge of the cylinder
-			int32 yInCylinderCoords = int32(round(halfHeight + ((float)y - halfHeight) * cosAlpha));
+			float yInCylinderCoords = halfHeight + ((float)y - halfHeight) * cosAlpha;
 			
 			uint32 indexTL = rowIndexT + columnIndexL;
 			uint32 indexBL = rowIndexB + columnIndexL;
 			uint32 indexTR = rowIndexT + columnIndexR;
 			uint32 indexBR = rowIndexB + columnIndexR;
-
+			
+			xOffset = xInCylinderCoords - x; 
+      yOffset = yInCylinderCoords - y;
+      
 			// Only store the (x,y) offsets instead of the absolute positions
-			_internalBuffer[indexTL].x = xInCylinderCoords - x;
-			_internalBuffer[indexTL].y = yInCylinderCoords - y;
+			_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, highQuality);
 			
 			//Store mirrored offset values
-			_internalBuffer[indexBL].x = _internalBuffer[indexTL].x;
-			_internalBuffer[indexBL].y = -_internalBuffer[indexTL].y;
-			_internalBuffer[indexTR].x = -_internalBuffer[indexTL].x;
-			_internalBuffer[indexTR].y = _internalBuffer[indexTL].y;
-			_internalBuffer[indexBR].x = -_internalBuffer[indexTL].x;
-			_internalBuffer[indexBR].y = -_internalBuffer[indexTL].y;
+			_internalBuffer[indexBL] = FilterPixel(xOffset, -yOffset, highQuality);
+			_internalBuffer[indexTR] = FilterPixel(-xOffset, yOffset, highQuality);
+			_internalBuffer[indexBR] = FilterPixel(-xOffset, -yOffset, highQuality);
 			
 			//Increment indices
 			rowIndexT += _numColumns;
@@ -191,6 +238,8 @@ void RenderTable::generateTiltLookupTable() {
 	float halfWidth = (float)_numColumns / 2.0f;
 	float halfHeight = (float)_numRows / 2.0f;
 	float cylinderRadius = halfWidth / tan(_tiltOptions.verticalFOV);
+	float xOffset = 0.0f;
+	float yOffset = 0.0f;
 	_tiltOptions.gap = cylinderRadius * atan2((float)(halfHeight / cylinderRadius), 1.0f) * _tiltOptions.linearScale;
 	
 	//Transformation is both horizontally and vertically symmetrical about the camera axis,
@@ -219,18 +268,17 @@ void RenderTable::generateTiltLookupTable() {
 			uint32 indexBL = columnIndexBL + x;
 			uint32 indexTR = columnIndexTR - x;
 			uint32 indexBR = columnIndexBR - x;
+			
+			xOffset = xInCylinderCoords - x;
+      yOffset = yInCylinderCoords - y;
 
 			// Only store the (x,y) offsets instead of the absolute positions
-			_internalBuffer[indexTL].x = xInCylinderCoords - x;
-			_internalBuffer[indexTL].y = yInCylinderCoords - y;
+			_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, highQuality);
 			
 			//Store mirrored offset values
-			_internalBuffer[indexBL].x = _internalBuffer[indexTL].x;
-			_internalBuffer[indexBL].y = -_internalBuffer[indexTL].y;
-			_internalBuffer[indexTR].x = -_internalBuffer[indexTL].x;
-			_internalBuffer[indexTR].y = _internalBuffer[indexTL].y;
-			_internalBuffer[indexBR].x = -_internalBuffer[indexTL].x;
-			_internalBuffer[indexBR].y = -_internalBuffer[indexTL].y;
+			_internalBuffer[indexBL] = FilterPixel(xOffset, -yOffset, highQuality);
+			_internalBuffer[indexTR] = FilterPixel(-xOffset, yOffset, highQuality);
+			_internalBuffer[indexBR] = FilterPixel(-xOffset, -yOffset, highQuality);
 		}
 	}
 }
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index 90f1a6eebc6..b8eda46ebe4 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -27,10 +27,28 @@
 
 namespace ZVision {
 
-struct MutationPoint {
-  uint8 Xweight = 0;
-  uint8 Yweight = 0;
-  Common::Rect PixelBlock = Common::Rect(0,0);
+class FilterPixel {
+public:
+  uint8 fracX = 0;  //Byte fraction of horizontal pixel position, 0 = left, 255 = right
+  uint8 fracY = 0;  //Byte fraction of vertical pixel position, 0 = top, 255 = bottom
+  Common::Rect Src = Common::Rect(0,0);  //Coordinates of four panorama image pixels around actual working window pixel
+  
+  FilterPixel() {};
+  FilterPixel(float x, float y, bool highQuality=false) {
+		if(highQuality) {
+	    Src.left = int16(floor(x));
+	    Src.right = int16(ceil(x));
+	    fracX = uint8((x-Src.left)*255);
+		  Src.top = int16(floor(y));
+		  Src.bottom = int16(ceil(y));
+		  fracY = uint8((y-Src.top)*255);
+	  }
+	  else {
+		  Src.left = int16(round(x));
+  		Src.top = int16(round(y));
+		}
+  };
+  ~FilterPixel() {};
 };
 
 class RenderTable {
@@ -47,10 +65,10 @@ public:
 
 private:
 	uint _numColumns, _numRows; //Working area width, height
-	Common::Point *_internalBuffer;
-//  MutationPoint *_internalBuffer;
+  FilterPixel *_internalBuffer;
 	RenderState _renderState;
 	bool highQuality = false;
+	const uint8 filterPasses = 2;
 
 	struct {
 		float verticalFOV;  //Radians


Commit: e4bb107b73c85dd4c676a7b8f52c07db5e8c7741
    https://github.com/scummvm/scummvm/commit/e4bb107b73c85dd4c676a7b8f52c07db5e8c7741
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:56+02:00

Commit Message:
ZVISION: Add single-pass bilinear panorama filter.
Add efficient RGB555 averaging function for use by filter.
Filter removes jagged edges & gives cleaner picture when not panning.
Unfortunately also causes noticeable moire effect during panning.
Limited improvement during tilt; further testing needed.

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index aff8d0b3851..9340ea4d1b0 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -56,7 +56,7 @@ RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const G
 	  _backgroundWidth(0),
 	  _backgroundHeight(0),
 	  _backgroundOffset(0),
-	  _renderTable(_layout.workingArea.width(), _layout.workingArea.height()),
+	  _renderTable(_layout.workingArea.width(), _layout.workingArea.height(), pixelFormat),
 	  _doubleFPS(doubleFPS),
 	  _widescreen(widescreen) {
 	debug(1,"creating render manager");
diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index 9b2936455d4..0f4fd92437a 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -27,10 +27,11 @@
 
 namespace ZVision {
 
-RenderTable::RenderTable(uint numColumns, uint numRows)
+RenderTable::RenderTable(uint numColumns, uint numRows, const Graphics::PixelFormat pixelFormat)
 	: _numRows(numRows),
 	  _numColumns(numColumns),
-	  _renderState(FLAT) {
+	  _renderState(FLAT),
+	  _pixelFormat(pixelFormat) {
 	assert(numRows != 0 && numColumns != 0);
 	_internalBuffer = new FilterPixel[numRows * numColumns];
 	memset(&_panoramaOptions, 0, sizeof(_panoramaOptions));
@@ -77,6 +78,7 @@ const Common::Point RenderTable::convertWarpedCoordToFlatCoord(const Common::Poi
 	return newPoint;
 }
 
+/*/
 void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 destWidth, const Common::Rect &subRect) {
 	uint32 destOffset = 0;
   uint32 sourceXIndex = 0;
@@ -111,6 +113,7 @@ void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 d
 	  }
   }
 }
+//*/
 
 void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf) {
 	uint32 destOffset = 0;
@@ -120,33 +123,28 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
   uint32 srcIndexYB = 0;
 	uint16 *sourceBuffer = (uint16 *)srcBuf->getPixels();
 	uint16 *destBuffer = (uint16 *)dstBuf->getPixels();
-	uint32 averageBufferA = 0;
-	uint32 averageBufferB = 0;
+	uint16 avgBufferT = 0;
+	uint16 avgBufferB = 0;
   if(highQuality) {
-    //TODO - convert to high quality pixel filtering
+    //Apply bilinear interpolation
 	  for (int16 y = 0; y < srcBuf->h; ++y) {
 		  uint32 sourceOffset = y * _numColumns;
 		  for (int16 x = 0; x < srcBuf->w; ++x) {
 			  uint32 index = sourceOffset + x;
 			  // RenderTable only stores offsets from the original coordinates
-			  srcIndexYT = y + (_internalBuffer[index].fracY < 170 ? _internalBuffer[index].Src.top : _internalBuffer[index].Src.bottom);
-			  srcIndexYB = y + (_internalBuffer[index].fracY > 85 ? _internalBuffer[index].Src.bottom :  _internalBuffer[index].Src.top);
-			  srcIndexXL = x + (_internalBuffer[index].fracX < 170 ? _internalBuffer[index].Src.left :  _internalBuffer[index].Src.right);
-			  srcIndexXR = x + (_internalBuffer[index].fracX > 85 ? _internalBuffer[index].Src.right :  _internalBuffer[index].Src.left);
-			  
-			  averageBufferA = sourceBuffer[srcIndexYT * _numColumns + srcIndexXL];
-			  averageBufferA += sourceBuffer[srcIndexYT * _numColumns + srcIndexXR];
-			  averageBufferB = sourceBuffer[srcIndexYB * _numColumns + srcIndexXL];
-			  averageBufferB += sourceBuffer[srcIndexYB * _numColumns + srcIndexXR];
-			  
-        destBuffer[destOffset] = (averageBufferA/2 + averageBufferB/2)/2; //TODO - fix this; naive averaging not working properly.
-			  
-			  //destBuffer[destOffset] = sourceBuffer[sourceYIndex * _numColumns + sourceXIndex];
+			  srcIndexYT = y + (_internalBuffer[index].fracY < 192 ? _internalBuffer[index].Src.top : _internalBuffer[index].Src.bottom);
+			  srcIndexYB = y + (_internalBuffer[index].fracY > 64 ? _internalBuffer[index].Src.bottom :  _internalBuffer[index].Src.top);
+			  srcIndexXL = x + (_internalBuffer[index].fracX < 192 ? _internalBuffer[index].Src.left :  _internalBuffer[index].Src.right);
+			  srcIndexXR = x + (_internalBuffer[index].fracX > 64 ? _internalBuffer[index].Src.right :  _internalBuffer[index].Src.left);		  
+			  avgBufferT = avgPixels(sourceBuffer[srcIndexYT * _numColumns + srcIndexXL], sourceBuffer[srcIndexYT * _numColumns + srcIndexXR]);
+			  avgBufferB = avgPixels(sourceBuffer[srcIndexYB * _numColumns + srcIndexXL], sourceBuffer[srcIndexYB * _numColumns + srcIndexXR]);
+        destBuffer[destOffset] = avgPixels(avgBufferT, avgBufferB);
 			  destOffset++;
 		  }
 	  }
   }
   else {
+    //Apply nearest-neighbour interpolation
 	  for (int16 y = 0; y < srcBuf->h; ++y) {
 		  uint32 sourceOffset = y * _numColumns;
 		  for (int16 x = 0; x < srcBuf->w; ++x) {
@@ -186,8 +184,6 @@ void RenderTable::generatePanoramaLookupTable() {
 	float xOffset = 0.0f;
 	float yOffset = 0.0f;
 	
-	FilterPixel currentFpixel;
-	
 	//Transformation is both horizontally and vertically symmetrical about the camera axis,
 	//We can thus save on trigonometric calculations by computing one quarter of the transformation matrix and then mirroring it in both X & Y
 	for (uint x = 0; x < halfColumns; ++x) {
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index b8eda46ebe4..50d3ee9f024 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -31,6 +31,8 @@ class FilterPixel {
 public:
   uint8 fracX = 0;  //Byte fraction of horizontal pixel position, 0 = left, 255 = right
   uint8 fracY = 0;  //Byte fraction of vertical pixel position, 0 = top, 255 = bottom
+  //TODO - make this a sequential list for recursive filtering.  
+  //TODO - Also include a recursion limit value so that we don't waste filtering operations on pixels that are already accurate enough.
   Common::Rect Src = Common::Rect(0,0);  //Coordinates of four panorama image pixels around actual working window pixel
   
   FilterPixel() {};
@@ -53,7 +55,7 @@ public:
 
 class RenderTable {
 public:
-	RenderTable(uint numRows, uint numColumns);
+	RenderTable(uint numRows, uint numColumns, const Graphics::PixelFormat pixelFormat);
 	~RenderTable();
 
 public:
@@ -67,8 +69,10 @@ private:
 	uint _numColumns, _numRows; //Working area width, height
   FilterPixel *_internalBuffer;
 	RenderState _renderState;
-	bool highQuality = false;
+	bool highQuality = true;
 	const uint8 filterPasses = 2;
+	const Graphics::PixelFormat _pixelFormat;
+	uint16 avgL, avgH;
 
 	struct {
 		float verticalFOV;  //Radians
@@ -93,8 +97,15 @@ public:
 
 	const Common::Point convertWarpedCoordToFlatCoord(const Common::Point &point);  //input point in working area coordinates
 
-	void mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 destWidth, const Common::Rect &subRect);
-	void mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf);
+//	void mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 destWidth, const Common::Rect &subRect);
+  void mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf);
+	
+	inline uint16 avgPixels(uint16 &PixelA, uint16 &PixelB) {
+	  //NB Optimised & valid for RGB555 only!
+  	avgL = (PixelA & 0x3def) + (PixelB & 0x3def);  //Add first 4 respective bits of eagh 5-bit R, G & B value
+	  avgH = (PixelA & 0x4210) + (PixelB & 0x4210);  //Add 5th respective bit of each 5-bit R, G & B value
+	  return (avgH + (avgL & 0x7bde)) >> 1; //Combine upper & lower bits, dropping 1st respective bit of each 5-bit R, G & B value, & then halve to get averages.
+	};
 	void generateRenderTable();
 
 	void setPanoramaFoV(float fov); //Degrees


Commit: 1e66fca9dcf10c41a0a6496634299beb1e1cbd04
    https://github.com/scummvm/scummvm/commit/1e66fca9dcf10c41a0a6496634299beb1e1cbd04
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:56+02:00

Commit Message:
ZVISION: Add ability to alter panorama quality from in-game and launcher options menus.

# Conflicts:
#	engines/zvision/zvision.cpp

Changed paths:
    engines/zvision/detection.h
    engines/zvision/detection_tables.h
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h
    engines/zvision/metaengine.cpp
    engines/zvision/zvision.cpp


diff --git a/engines/zvision/detection.h b/engines/zvision/detection.h
index 43d1bde63e8..405dbbc0207 100644
--- a/engines/zvision/detection.h
+++ b/engines/zvision/detection.h
@@ -45,6 +45,7 @@ struct ZVisionGameDescription {
 #define GAMEOPTION_DISABLE_ANIM_WHILE_TURNING GUIO_GAMEOPTIONS4
 #define GAMEOPTION_USE_HIRES_MPEG_MOVIES      GUIO_GAMEOPTIONS5
 #define GAMEOPTION_ENABLE_WIDESCREEN          GUIO_GAMEOPTIONS6
+#define GAMEOPTION_HQ_PANORAMA                GUIO_GAMEOPTIONS7
 
 } // End of namespace ZVision
 
diff --git a/engines/zvision/detection_tables.h b/engines/zvision/detection_tables.h
index 43e29337855..bb56fe3dff0 100644
--- a/engines/zvision/detection_tables.h
+++ b/engines/zvision/detection_tables.h
@@ -53,7 +53,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::EN_ANY,
 			Common::kPlatformDOS,
 			ADGF_NO_FLAGS,
-			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
+			GUIO6(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
 		},
 		GID_NEMESIS
 	},
@@ -68,7 +68,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::FR_FRA,
 			Common::kPlatformDOS,
 			ADGF_NO_FLAGS,
-			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
+			GUIO6(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
 		},
 		GID_NEMESIS
 	},
@@ -83,7 +83,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::DE_DEU,
 			Common::kPlatformDOS,
 			ADGF_NO_FLAGS,
-			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
+			GUIO6(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
 		},
 		GID_NEMESIS
 	},
@@ -98,7 +98,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::IT_ITA,
 			Common::kPlatformDOS,
 			ADGF_NO_FLAGS,
-			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
+			GUIO6(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
 		},
 		GID_NEMESIS
 	},
@@ -116,7 +116,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::KO_KOR,
 			Common::kPlatformDOS,
 			ADGF_NO_FLAGS,
-			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
+			GUIO6(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
 		},
 		GID_NEMESIS
 	},
@@ -135,7 +135,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::EN_ANY,
 			Common::kPlatformMacintosh,
 			ADGF_UNSUPPORTED,
-			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
+			GUIO6(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
 		},
 		GID_NEMESIS
 	},
@@ -149,7 +149,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::EN_ANY,
 			Common::kPlatformWindows,
 			ADGF_DEMO,
-			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
+			GUIO6(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_ENABLE_VENUS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
 		},
 		GID_NEMESIS
 	},
@@ -163,7 +163,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::EN_ANY,
 			Common::kPlatformWindows,
 			ADGF_NO_FLAGS,
-			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
+			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
 		},
 		GID_GRANDINQUISITOR
 	},
@@ -177,7 +177,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::FR_FRA,
 			Common::kPlatformWindows,
 			ADGF_NO_FLAGS,
-			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
+			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
 		},
 		GID_GRANDINQUISITOR
 	},
@@ -191,7 +191,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::DE_DEU,
 			Common::kPlatformWindows,
 			ADGF_NO_FLAGS,
-			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
+			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
 		},
 		GID_GRANDINQUISITOR
 	},
@@ -205,7 +205,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::ES_ESP,
 			Common::kPlatformWindows,
 			ADGF_NO_FLAGS,
-			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
+			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
 		},
 		GID_GRANDINQUISITOR
 	},
@@ -220,7 +220,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::EN_ANY,
 			Common::kPlatformMacintosh,
 			ADGF_NO_FLAGS,
-			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
+			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
 		},
 		GID_GRANDINQUISITOR
 	},
@@ -235,9 +235,9 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::kPlatformWindows,
 			ADGF_DVD,
 #if defined(USE_MPEG2) && defined(USE_A52)
-			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_USE_HIRES_MPEG_MOVIES, GAMEOPTION_ENABLE_WIDESCREEN)
+			GUIO6(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_USE_HIRES_MPEG_MOVIES, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
 #else
-			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
+			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
 #endif
 		},
 		GID_GRANDINQUISITOR
@@ -252,7 +252,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::EN_ANY,
 			Common::kPlatformWindows,
 			ADGF_DEMO,
-			GUIO4(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN)
+			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
 		},
 		GID_GRANDINQUISITOR
 	},
diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 9340ea4d1b0..f667d67d84d 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -213,7 +213,7 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
 	    case RenderTable::PANORAMA:
 	    case RenderTable::TILT:
 		    if (!_backgroundSurfaceDirtyRect.isEmpty()) {
-			    _renderTable.mutateImage(&_warpedSceneSurface, in);
+			    _renderTable.mutateImage(&_warpedSceneSurface, in, _engine->getScriptManager()->getStateValue(StateKey_HighQuality));
 			    out = &_warpedSceneSurface;
 			    outWndDirtyRect = Common::Rect(_workingArea.width(), _workingArea.height());
 		    }
diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index 0f4fd92437a..8ca9f68f188 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -115,7 +115,7 @@ void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 d
 }
 //*/
 
-void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf) {
+void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf, bool highQuality) {
 	uint32 destOffset = 0;
   uint32 srcIndexXL = 0;
   uint32 srcIndexXR = 0;
@@ -125,7 +125,11 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 	uint16 *destBuffer = (uint16 *)dstBuf->getPixels();
 	uint16 avgBufferT = 0;
 	uint16 avgBufferB = 0;
-  if(highQuality) {
+	if(highQuality != _highQuality) {
+	  _highQuality = highQuality;
+	  generateRenderTable();
+	}
+  if(_highQuality) {
     //Apply bilinear interpolation
 	  for (int16 y = 0; y < srcBuf->h; ++y) {
 		  uint32 sourceOffset = y * _numColumns;
@@ -214,12 +218,12 @@ void RenderTable::generatePanoramaLookupTable() {
       yOffset = yInCylinderCoords - y;
       
 			// Only store the (x,y) offsets instead of the absolute positions
-			_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, highQuality);
+			_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality);
 			
 			//Store mirrored offset values
-			_internalBuffer[indexBL] = FilterPixel(xOffset, -yOffset, highQuality);
-			_internalBuffer[indexTR] = FilterPixel(-xOffset, yOffset, highQuality);
-			_internalBuffer[indexBR] = FilterPixel(-xOffset, -yOffset, highQuality);
+			_internalBuffer[indexBL] = FilterPixel(xOffset, -yOffset, _highQuality);
+			_internalBuffer[indexTR] = FilterPixel(-xOffset, yOffset, _highQuality);
+			_internalBuffer[indexBR] = FilterPixel(-xOffset, -yOffset, _highQuality);
 			
 			//Increment indices
 			rowIndexT += _numColumns;
@@ -269,12 +273,12 @@ void RenderTable::generateTiltLookupTable() {
       yOffset = yInCylinderCoords - y;
 
 			// Only store the (x,y) offsets instead of the absolute positions
-			_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, highQuality);
+			_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality);
 			
 			//Store mirrored offset values
-			_internalBuffer[indexBL] = FilterPixel(xOffset, -yOffset, highQuality);
-			_internalBuffer[indexTR] = FilterPixel(-xOffset, yOffset, highQuality);
-			_internalBuffer[indexBR] = FilterPixel(-xOffset, -yOffset, highQuality);
+			_internalBuffer[indexBL] = FilterPixel(xOffset, -yOffset, _highQuality);
+			_internalBuffer[indexTR] = FilterPixel(-xOffset, yOffset, _highQuality);
+			_internalBuffer[indexBR] = FilterPixel(-xOffset, -yOffset, _highQuality);
 		}
 	}
 }
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index 50d3ee9f024..0c2577cf232 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -69,7 +69,7 @@ private:
 	uint _numColumns, _numRows; //Working area width, height
   FilterPixel *_internalBuffer;
 	RenderState _renderState;
-	bool highQuality = true;
+	bool _highQuality = false;
 	const uint8 filterPasses = 2;
 	const Graphics::PixelFormat _pixelFormat;
 	uint16 avgL, avgH;
@@ -98,7 +98,7 @@ public:
 	const Common::Point convertWarpedCoordToFlatCoord(const Common::Point &point);  //input point in working area coordinates
 
 //	void mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 destWidth, const Common::Rect &subRect);
-  void mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf);
+  void mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf, bool filter=false);
 	
 	inline uint16 avgPixels(uint16 &PixelA, uint16 &PixelB) {
 	  //NB Optimised & valid for RGB555 only!
diff --git a/engines/zvision/metaengine.cpp b/engines/zvision/metaengine.cpp
index 5a9cb7891d2..c839d442815 100644
--- a/engines/zvision/metaengine.cpp
+++ b/engines/zvision/metaengine.cpp
@@ -112,6 +112,17 @@ static const ADExtraGuiOptionsMap optionsList[] = {
 		}
 	},
 
+	{
+		GAMEOPTION_HQ_PANORAMA,
+		{
+			_s("Enable high quality panoramas"),
+			_s("Apply bilinear filtering to panoramic backgrounds."),
+			"highquality",
+			true,
+			0,
+			0
+		}
+	},
 
 	AD_EXTRA_GUI_OPTIONS_TERMINATOR
 };
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index bcc992bd12a..ef8698fa41e 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -72,11 +72,11 @@ struct zvisionIniSettings {
 	{"installlevel", StateKey_InstallLevel, 0, false, false},	// 0 = full, checked by universe.scr
 	{"debugcheats", StateKey_DebugCheats, -1, true, false},	// always start with the GOxxxx cheat enabled
 	// Editable settings
-	{"highquality", StateKey_HighQuality, -1, true, false},	// high panorama quality
 	{"qsoundenabled", StateKey_Qsound, -1, true, true},	// 1 = enable generic directional audio and non-linear volume scaling.  Genuine Qsound is copyright & unlikely to be implemented.
 	{"keyboardturnspeed", StateKey_KbdRotateSpeed, 5, false, true},
 	{"panarotatespeed", StateKey_RotateSpeed, 540, false, true},	// checked by universe.scr
 	{"noanimwhileturning", StateKey_NoTurnAnim, -1, false, true},	// toggle playing animations during pana rotation
+	{"highquality", StateKey_HighQuality, -1, true, false},	// high panorama quality; enables bilinear filtering in RenderTable
 	{"venusenabled", StateKey_VenusEnable, -1, true, true},
 	{"subtitles", StateKey_Subtitles, -1, true, true},
 	{"mpegmovies", StateKey_MPEGMovies, -1, true, true}		// Zork: Grand Inquisitor DVD hi-res MPEG movies (0 = normal, 1 = hires, 2 = disable option)
@@ -257,6 +257,9 @@ void ZVision::initialize() {
 
 	// Initialize FPS timer callback
 	getTimerManager()->installTimerProc(&fpsTimerCallback, 1000000, this, "zvisionFPS");
+
+  //Ensure a new game is launched with correct panorama quality setting
+  _scriptManager->setStateValue(StateKey_HighQuality, ConfMan.getBool("highquality"));
 }
 
 extern const FontStyle getSystemFont(int fontIndex);


Commit: 23c1c8e793977b26e6e8508e01ee9a6570c62507
    https://github.com/scummvm/scummvm/commit/23c1c8e793977b26e6e8508e01ee9a6570c62507
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:56+02:00

Commit Message:
ZVISION: Improve bilinear filter.
Fix cumulative rounding error in pixel averaging function.
Moire effect significantly reduced but not eliminated.
Additional debugging statements for testing pixel average function.
Further testing needed, filter tolerance needs optimising.
Video tearing effects at low tolerance values; need frame synchronisation.
Filter not working in tilt mode; review render table generation code.

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index f667d67d84d..aac94286e0d 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -213,7 +213,10 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
 	    case RenderTable::PANORAMA:
 	    case RenderTable::TILT:
 		    if (!_backgroundSurfaceDirtyRect.isEmpty()) {
+		      uint32 mutationTime = _system->getMillis();
 			    _renderTable.mutateImage(&_warpedSceneSurface, in, _engine->getScriptManager()->getStateValue(StateKey_HighQuality));
+          mutationTime = _system->getMillis() - mutationTime;
+          debug(1,"Panorama mutation time %dms, %s quality", mutationTime, _engine->getScriptManager()->getStateValue(StateKey_HighQuality) ? "high" : "low");
 			    out = &_warpedSceneSurface;
 			    outWndDirtyRect = Common::Rect(_workingArea.width(), _workingArea.height());
 		    }
diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index 8ca9f68f188..282e05c2ae3 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -73,8 +73,8 @@ const Common::Point RenderTable::convertWarpedCoordToFlatCoord(const Common::Poi
 	}
 	uint32 index = point.y * _numColumns + point.x;
 	Common::Point newPoint(point);
-	newPoint.x += (_internalBuffer[index].fracX >= 128 ? _internalBuffer[index].Src.right : _internalBuffer[index].Src.left);
-	newPoint.y += (_internalBuffer[index].fracY >= 128 ? _internalBuffer[index].Src.bottom : _internalBuffer[index].Src.top);
+	newPoint.x += (_internalBuffer[index].xDir & 0x01 ? _internalBuffer[index].Src.right : _internalBuffer[index].Src.left);
+	newPoint.y += (_internalBuffer[index].yDir & 0x01 ? _internalBuffer[index].Src.bottom : _internalBuffer[index].Src.top);
 	return newPoint;
 }
 
@@ -123,27 +123,370 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
   uint32 srcIndexYB = 0;
 	uint16 *sourceBuffer = (uint16 *)srcBuf->getPixels();
 	uint16 *destBuffer = (uint16 *)dstBuf->getPixels();
-	uint16 avgBufferT = 0;
-	uint16 avgBufferB = 0;
+	uint32 bufferTL = 0;
+	uint32 bufferBL = 0;
+	uint32 bufferTR = 0;
+	uint32 bufferBR = 0;
+	uint32 bufferTL_G = 0;
+	uint32 bufferBL_G = 0;
+	uint32 bufferTR_G = 0;
+	uint32 bufferBR_G = 0;
+
+
 	if(highQuality != _highQuality) {
 	  _highQuality = highQuality;
 	  generateRenderTable();
 	}
+	
   if(_highQuality) {
     //Apply bilinear interpolation
+	  FilterPixel _curP;
+	  uint8 xCount = 0;
+	  uint8 yCount = 0;
+	  uint8 xDir = 0;
+	  uint8 yDir = 0;
+	  
+    //Deb
+	  uint8 r = 0;
+	  uint8 g = 0;
+	  uint8 b = 0;
+	  
 	  for (int16 y = 0; y < srcBuf->h; ++y) {
 		  uint32 sourceOffset = y * _numColumns;
 		  for (int16 x = 0; x < srcBuf->w; ++x) {
+		    xCount = 0;
+		    yCount = 0;
 			  uint32 index = sourceOffset + x;
 			  // RenderTable only stores offsets from the original coordinates
-			  srcIndexYT = y + (_internalBuffer[index].fracY < 192 ? _internalBuffer[index].Src.top : _internalBuffer[index].Src.bottom);
-			  srcIndexYB = y + (_internalBuffer[index].fracY > 64 ? _internalBuffer[index].Src.bottom :  _internalBuffer[index].Src.top);
-			  srcIndexXL = x + (_internalBuffer[index].fracX < 192 ? _internalBuffer[index].Src.left :  _internalBuffer[index].Src.right);
-			  srcIndexXR = x + (_internalBuffer[index].fracX > 64 ? _internalBuffer[index].Src.right :  _internalBuffer[index].Src.left);		  
-			  avgBufferT = avgPixels(sourceBuffer[srcIndexYT * _numColumns + srcIndexXL], sourceBuffer[srcIndexYT * _numColumns + srcIndexXR]);
-			  avgBufferB = avgPixels(sourceBuffer[srcIndexYB * _numColumns + srcIndexXL], sourceBuffer[srcIndexYB * _numColumns + srcIndexXR]);
-        destBuffer[destOffset] = avgPixels(avgBufferT, avgBufferB);
-			  destOffset++;
+			  _curP = _internalBuffer[index];
+			  xDir = _curP.xDir;
+			  yDir = _curP.yDir;
+
+			  srcIndexYT = y + _curP.Src.top;
+			  srcIndexYB = y + _curP.Src.bottom;
+			  srcIndexXL = x + _curP.Src.left;
+			  srcIndexXR = x + _curP.Src.right;
+			  bufferTL = sourceBuffer[srcIndexYT * _numColumns + srcIndexXL];
+			  bufferTR = sourceBuffer[srcIndexYT * _numColumns + srcIndexXR];
+			  bufferBL = sourceBuffer[srcIndexYB * _numColumns + srcIndexXL];
+			  bufferBR = sourceBuffer[srcIndexYB * _numColumns + srcIndexXR];
+        if(_curP._printDebug) {
+          _pixelFormat.colorToRGB(bufferTL,r,g,b);
+          debug(2,"Original pixel value TL %s, RGB: %d,%d,%d", pixelToBinary(bufferTL).c_str(),r,g,b);
+          _pixelFormat.colorToRGB(bufferTR,r,g,b);
+          debug(2,"Original pixel value TR %s, RGB: %d,%d,%d", pixelToBinary(bufferTR).c_str(),r,g,b);
+          _pixelFormat.colorToRGB(bufferBL,r,g,b);
+          debug(2,"Original pixel value BL %s, RGB: %d,%d,%d", pixelToBinary(bufferBL).c_str(),r,g,b);
+          _pixelFormat.colorToRGB(bufferBR,r,g,b);
+          debug(2,"Original pixel value BR %s, RGB: %d,%d,%d", pixelToBinary(bufferBR).c_str(),r,g,b);
+			  }
+			  //Extract green values
+			  bufferTL_G = bufferTL & 0x03e0;
+			  bufferBL_G = bufferBL & 0x03e0;
+			  bufferTR_G = bufferTR & 0x03e0;
+			  bufferBR_G = bufferBR & 0x03e0;
+		    //Mask for red & blue values
+			  bufferTL &= 0x7c1f;
+			  bufferBL &= 0x7c1f;
+			  bufferTR &= 0x7c1f;
+			  bufferBR &= 0x7c1f;
+			  
+			  if(_curP._printDebug) {
+  			  debug(2,"\tTest pixel %d,%d", x, y);
+  			  debug(2,"\tX byte fraction %d, Y byte fraction %d", _curP.fracX, _curP.fracY);
+  			  debug(2,"\tX steps %d, Y steps %d", _curP.xSteps, _curP.ySteps);
+  			  debug(2,"\tXdir 0x%X, Ydir 0x%X", xDir, _curP.yDir);
+			  }
+			  
+        if(_curP._printDebug) {
+          _pixelFormat.colorToRGB(bufferTL,r,g,b);
+          debug(2,"Separated pixel value TL   %s, RGB: %d,%d,%d", pixelToBinary(bufferTL).c_str(), r,g,b);
+          _pixelFormat.colorToRGB(bufferTR,r,g,b);
+          debug(2,"Separated pixel value TR   %s, RGB: %d,%d,%d", pixelToBinary(bufferTR).c_str(),r,g,b);
+          _pixelFormat.colorToRGB(bufferBL,r,g,b);
+          debug(2,"Separated pixel value BL   %s, RGB: %d,%d,%d", pixelToBinary(bufferBL).c_str(),r,g,b);
+          _pixelFormat.colorToRGB(bufferBR,r,g,b);
+          debug(2,"Separated pixel value BR   %s, RGB: %d,%d,%d", pixelToBinary(bufferBR).c_str(),r,g,b);
+          _pixelFormat.colorToRGB(bufferTL_G,r,g,b);
+          debug(2,"Separated pixel value TL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTL_G).c_str(),r,g,b);
+          _pixelFormat.colorToRGB(bufferTR_G,r,g,b);
+          debug(2,"Separated pixel value TR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTR_G).c_str(),r,g,b);
+          _pixelFormat.colorToRGB(bufferBL_G,r,g,b);
+          debug(2,"Separated pixel value BL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBL_G).c_str(),r,g,b);
+          _pixelFormat.colorToRGB(bufferBR_G,r,g,b);
+          debug(2,"Separated pixel value BR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBR_G).c_str(),r,g,b);
+		    }
+			  
+        //Horizontal contraction
+		    if(_curP.ySteps > 1) {
+          while(_curP.xSteps > xCount+1) {
+            xCount++;
+            if(_curP.xDir & 0x01) {
+			        if(_curP._printDebug)
+			          debug(2,"\t\tContracting right, T&B");
+		          contractLeft(bufferTR, bufferTL);
+		          contractLeft(bufferBR, bufferBL);
+		          contractLeft(bufferTR_G, bufferTL_G);
+		          contractLeft(bufferBR_G, bufferBL_G);
+            }
+            else {
+			        if(_curP._printDebug)
+			          debug(2,"\t\tContracting left, T&B");
+		          contractLeft(bufferTL, bufferTR);
+		          contractLeft(bufferBL, bufferBR);
+		          contractLeft(bufferTL_G, bufferTR_G);
+		          contractLeft(bufferBL_G, bufferBR_G);
+            }
+            _curP.xDir >>= 1;
+            		          
+            if(_curP._printDebug) {
+		          debug(2,"\t\txDir 0x%X", _curP.xDir);	   
+              _pixelFormat.colorToRGB(bufferTL,r,g,b);
+              debug(2,"Contracted pixel value TL   %s, RGB: %d,%d,%d", pixelToBinary(bufferTL).c_str(), r,g,b);
+              _pixelFormat.colorToRGB(bufferTR,r,g,b);
+              debug(2,"Contracted pixel value TR   %s, RGB: %d,%d,%d", pixelToBinary(bufferTR).c_str(),r,g,b);
+              _pixelFormat.colorToRGB(bufferBL,r,g,b);
+              debug(2,"Contracted pixel value BL   %s, RGB: %d,%d,%d", pixelToBinary(bufferBL).c_str(),r,g,b);
+              _pixelFormat.colorToRGB(bufferBR,r,g,b);
+              debug(2,"Contracted pixel value BR   %s, RGB: %d,%d,%d", pixelToBinary(bufferBR).c_str(),r,g,b);
+              _pixelFormat.colorToRGB(bufferTL_G,r,g,b);
+              debug(2,"Contracted pixel value TL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTL_G).c_str(),r,g,b);
+              _pixelFormat.colorToRGB(bufferTR_G,r,g,b);
+              debug(2,"Contracted pixel value TR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTR_G).c_str(),r,g,b);
+              _pixelFormat.colorToRGB(bufferBL_G,r,g,b);
+              debug(2,"Contracted pixel value BL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBL_G).c_str(),r,g,b);
+              _pixelFormat.colorToRGB(bufferBR_G,r,g,b);
+              debug(2,"Contracted pixel value BR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBR_G).c_str(),r,g,b);
+			      }
+          }
+//*/
+          if(_curP.xDir & 0x01) {
+            bufferBR = (bufferBR >> xCount) & 0x7c1f;
+            bufferBR_G = (bufferBR_G >> xCount) & 0x03e0;
+            bufferTR = (bufferTR >> xCount) & 0x7c1f;
+            bufferTR_G = (bufferTR_G >> xCount) & 0x03e0;
+          }
+          else {
+            bufferBL = (bufferBL >> xCount) & 0x7c1f;
+            bufferBL_G = (bufferBL_G >> xCount) & 0x03e0;
+            bufferTL = (bufferTL >> xCount) & 0x7c1f;
+            bufferTL_G = (bufferTL_G >> xCount) & 0x03e0;
+          }
+          if(_curP._printDebug) {
+            debug(2,"\tShifted back %d places", xCount);
+            _pixelFormat.colorToRGB(bufferTL,r,g,b);
+            debug(2,"Shifted pixel value TL   %s, RGB: %d,%d,%d", pixelToBinary(bufferTL).c_str(), r,g,b);
+            _pixelFormat.colorToRGB(bufferTR,r,g,b);
+            debug(2,"Shifted pixel value TR   %s, RGB: %d,%d,%d", pixelToBinary(bufferTR).c_str(),r,g,b);
+            _pixelFormat.colorToRGB(bufferBL,r,g,b);
+            debug(2,"Shifted pixel value BL   %s, RGB: %d,%d,%d", pixelToBinary(bufferBL).c_str(),r,g,b);
+            _pixelFormat.colorToRGB(bufferBR,r,g,b);
+            debug(2,"Shifted pixel value BR   %s, RGB: %d,%d,%d", pixelToBinary(bufferBR).c_str(),r,g,b);
+            _pixelFormat.colorToRGB(bufferTL_G,r,g,b);
+            debug(2,"Shifted pixel value TL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTL_G).c_str(),r,g,b);
+            _pixelFormat.colorToRGB(bufferTR_G,r,g,b);
+            debug(2,"Shifted pixel value TR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTR_G).c_str(),r,g,b);
+            _pixelFormat.colorToRGB(bufferBL_G,r,g,b);
+            debug(2,"Shifted pixel value BL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBL_G).c_str(),r,g,b);
+            _pixelFormat.colorToRGB(bufferBR_G,r,g,b);
+            debug(2,"Shifted pixel value BR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBR_G).c_str(),r,g,b);
+			    }
+//*/
+        }
+        else if (_curP.yDir) {
+          while(_curP.xSteps > xCount+1) {
+            xCount++;
+            if(_curP.xDir & 0x01) {
+			        if(_curP._printDebug)
+			          debug(2,"\t\tContracting right, B");
+		          contractLeft(bufferBR, bufferBL);
+		          contractLeft(bufferBR_G, bufferBL_G);
+            }
+            else {
+			        if(_curP._printDebug)
+			          debug(2,"\t\tContracting left, B");
+		          contractLeft(bufferBL, bufferBR);
+		          contractLeft(bufferBL_G, bufferBR_G);
+            }
+            _curP.xDir >>= 1;
+            
+            if(_curP._printDebug) {
+              _pixelFormat.colorToRGB(bufferBL,r,g,b);
+              debug(2,"Contracted pixel value BL   %s, RGB: %d,%d,%d", pixelToBinary(bufferBL).c_str(),r,g,b);
+              _pixelFormat.colorToRGB(bufferBR,r,g,b);
+              debug(2,"Contracted pixel value BR   %s, RGB: %d,%d,%d", pixelToBinary(bufferBR).c_str(),r,g,b);
+              _pixelFormat.colorToRGB(bufferBL_G,r,g,b);
+              debug(2,"Contracted pixel value BL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBL_G).c_str(),r,g,b);
+              _pixelFormat.colorToRGB(bufferBR_G,r,g,b);
+              debug(2,"Contracted pixel value BR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBR_G).c_str(),r,g,b);
+			      }
+          }
+//*/
+          if(_curP.xDir & 0x01) {
+            bufferBR = (bufferBR >> xCount) & 0x7c1f;
+            bufferBR_G = (bufferBR_G >> xCount) & 0x03e0;
+          }
+          else {
+            bufferBL = (bufferBL >> xCount) & 0x7c1f;
+            bufferBL_G = (bufferBL_G >> xCount) & 0x03e0;
+          }
+          if(_curP._printDebug) {
+            debug(2,"\tShifted back %d places", xCount);
+            _pixelFormat.colorToRGB(bufferBL,r,g,b);
+            debug(2,"Shifted pixel value BL   %s, RGB: %d,%d,%d", pixelToBinary(bufferBL).c_str(),r,g,b);
+            _pixelFormat.colorToRGB(bufferBR,r,g,b);
+            debug(2,"Shifted pixel value BR   %s, RGB: %d,%d,%d", pixelToBinary(bufferBR).c_str(),r,g,b);
+            _pixelFormat.colorToRGB(bufferBL_G,r,g,b);
+            debug(2,"Shifted pixel value BL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBL_G).c_str(),r,g,b);
+            _pixelFormat.colorToRGB(bufferBR_G,r,g,b);
+            debug(2,"Shifted pixel value BR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBR_G).c_str(),r,g,b);
+			    }
+//*/
+        }
+        else {
+          while(_curP.xSteps > xCount+1) {
+            xCount++;
+            if(_curP.xDir & 0x01) {
+			        if(_curP._printDebug)
+			          debug(2,"\t\tContracting right, T");
+		          contractLeft(bufferTR, bufferTL);
+		          contractLeft(bufferTR_G, bufferTL_G);
+            }
+            else {
+			        if(_curP._printDebug)
+			          debug(2,"\t\tContracting left, T");
+		          contractLeft(bufferTL, bufferTR);
+		          contractLeft(bufferTL_G, bufferTR_G);
+            }
+            _curP.xDir >>= 1;
+            
+            if(_curP._printDebug) {
+              _pixelFormat.colorToRGB(bufferTL,r,g,b);
+              debug(2,"Contracted pixel value TL   %s, RGB: %d,%d,%d", pixelToBinary(bufferTL).c_str(), r,g,b);
+              _pixelFormat.colorToRGB(bufferTR,r,g,b);
+              debug(2,"Contracted pixel value TR   %s, RGB: %d,%d,%d", pixelToBinary(bufferTR).c_str(),r,g,b);
+              _pixelFormat.colorToRGB(bufferTL_G,r,g,b);
+              debug(2,"Contracted pixel value TL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTL_G).c_str(),r,g,b);
+              _pixelFormat.colorToRGB(bufferTR_G,r,g,b);
+              debug(2,"Contracted pixel value TR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTR_G).c_str(),r,g,b);
+			      }
+          }
+//*/
+          if(_curP.xDir & 0x01) {
+            bufferTR = (bufferTR >> xCount) & 0x7c1f;
+            bufferTR_G = (bufferTR_G >> xCount) & 0x03e0;
+          }
+          else {
+            bufferTL = (bufferTL >> xCount) & 0x7c1f;
+            bufferTL_G = (bufferTL_G >> xCount) & 0x03e0;
+          }
+          if(_curP._printDebug) {
+            debug(2,"\tShifted back %d places", xCount);
+            _pixelFormat.colorToRGB(bufferTL,r,g,b);
+            debug(2,"Shifted pixel value TL   %s, RGB: %d,%d,%d", pixelToBinary(bufferTL).c_str(), r,g,b);
+            _pixelFormat.colorToRGB(bufferTR,r,g,b);
+            debug(2,"Shifted pixel value TR   %s, RGB: %d,%d,%d", pixelToBinary(bufferTR).c_str(),r,g,b);
+            _pixelFormat.colorToRGB(bufferTL_G,r,g,b);
+            debug(2,"Shifted pixel value TL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTL_G).c_str(),r,g,b);
+            _pixelFormat.colorToRGB(bufferTR_G,r,g,b);
+            debug(2,"Shifted pixel value TR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTR_G).c_str(),r,g,b);
+			    }
+//*/
+        }
+        
+        //Vertical contraction
+        if(_curP.xDir & 0x01) {
+          while(_curP.ySteps > yCount+1) {
+            yCount++;
+            if(_curP.yDir & 0x01) {
+			        if(_curP._printDebug)
+			          debug(2,"\t\tContracting downward, R");
+		          contractLeft(bufferBR, bufferTR);
+		          contractLeft(bufferBR_G, bufferTR_G);
+            }
+            else {
+			        if(_curP._printDebug)
+			          debug(2,"\t\tContracting upward, R");
+		          contractLeft(bufferTR, bufferBR);
+		          contractLeft(bufferTR_G, bufferBR_G);
+            }
+            _curP.yDir >>= 1;
+            
+            if(_curP._printDebug) {
+              _pixelFormat.colorToRGB(bufferTR,r,g,b);
+              debug(2,"Contracted pixel value TR   %s, RGB: %d,%d,%d", pixelToBinary(bufferTR).c_str(), r,g,b);
+              _pixelFormat.colorToRGB(bufferBR,r,g,b);
+              debug(2,"Contracted pixel value BR   %s, RGB: %d,%d,%d", pixelToBinary(bufferBR).c_str(),r,g,b);
+              _pixelFormat.colorToRGB(bufferTR_G,r,g,b);
+              debug(2,"Contracted pixel value TR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTR_G).c_str(),r,g,b);
+              _pixelFormat.colorToRGB(bufferBR_G,r,g,b);
+              debug(2,"Contracted pixel value BR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBR_G).c_str(),r,g,b);
+			      }
+          }
+        }
+        else {
+          while(_curP.ySteps > yCount+1) {
+            yCount++;
+		        if(_curP._printDebug)
+		          debug(2,"yDir %x", _curP.yDir);
+            if(_curP.yDir & 0x01) {
+			        if(_curP._printDebug)
+			          debug(2,"\t\tContracting downward, L");
+		          contractLeft(bufferBL, bufferTL);
+		          contractLeft(bufferBL_G, bufferTL_G);
+            }
+            else {
+			        if(_curP._printDebug)
+			          debug(2,"\t\tContracting upward, L");
+		          contractLeft(bufferTL, bufferBL);
+		          contractLeft(bufferTL_G, bufferBL_G);
+            }
+            _curP.yDir >>= 1;
+            
+            if(_curP._printDebug) {
+              _pixelFormat.colorToRGB(bufferTL,r,g,b);
+              debug(2,"Contracted pixel value TL   %s, RGB: %d,%d,%d", pixelToBinary(bufferTL).c_str(), r,g,b);
+              _pixelFormat.colorToRGB(bufferBL,r,g,b);
+              debug(2,"Contracted pixel value BL   %s, RGB: %d,%d,%d", pixelToBinary(bufferBL).c_str(),r,g,b);
+              _pixelFormat.colorToRGB(bufferTL_G,r,g,b);
+              debug(2,"Contracted pixel value TL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTL_G).c_str(),r,g,b);
+              _pixelFormat.colorToRGB(bufferBL_G,r,g,b);
+              debug(2,"Contracted pixel value BL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBL_G).c_str(),r,g,b);
+			      }
+          }
+        }
+        if(_curP._printDebug)
+          debug(2,"yCount %d", yCount);
+        //Final value
+        if(_curP.yDir & 0x01) {
+          if(_curP.xDir & 0x01) {
+		        if(_curP._printDebug)
+		          debug(2,"\t\tPicking final value, BR");
+            destBuffer[destOffset] = ((bufferBR >> yCount) & 0x7c1f) | ((bufferBR_G >> yCount) & 0x03e0);
+          }
+          else {
+		        if(_curP._printDebug)
+		          debug(2,"\t\tPicking final value, BL");
+            destBuffer[destOffset] = ((bufferBL >> yCount) & 0x7c1f) | ((bufferBL_G >> yCount) & 0x03e0);
+          }
+        }
+        else {
+          if(_curP.xDir & 0x01) {
+		        if(_curP._printDebug)
+		          debug(2,"\t\tPicking final value, TR");
+            destBuffer[destOffset] = ((bufferTR >> yCount) & 0x7c1f) | ((bufferTR_G >> yCount) & 0x03e0);
+          }
+          else {
+		        if(_curP._printDebug)
+		          debug(2,"\t\tPicking final value, TL");
+            destBuffer[destOffset] = ((bufferTL >> yCount) & 0x7c1f) | ((bufferTL_G >> yCount) & 0x03e0);
+          }
+        }        
+        if(_curP._printDebug) { 
+          _pixelFormat.colorToRGB(destBuffer[destOffset],r,g,b);
+          debug(2,"Final pixel value %s, RGB: %d,%d,%d", pixelToBinary(bufferBR).c_str(),r,g,b);
+        }    
+		    destOffset++;     
 		  }
 	  }
   }
@@ -154,8 +497,8 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 		  for (int16 x = 0; x < srcBuf->w; ++x) {
 			  uint32 index = sourceOffset + x;
 			  // RenderTable only stores offsets from the original coordinates
-			  srcIndexYT = y + _internalBuffer[index].Src.top;
-    		srcIndexXL = x + _internalBuffer[index].Src.left;
+    		srcIndexXL = x + (_internalBuffer[index].xDir ? _internalBuffer[index].Src.right : _internalBuffer[index].Src.left);			  
+			  srcIndexYT = y + (_internalBuffer[index].yDir ? _internalBuffer[index].Src.bottom : _internalBuffer[index].Src.top);
 			  destBuffer[destOffset] = sourceBuffer[srcIndexYT * _numColumns + srcIndexXL];
 			  destOffset++;
 		  }
@@ -180,6 +523,7 @@ void RenderTable::generateRenderTable() {
 }
 
 void RenderTable::generatePanoramaLookupTable() {
+  debug(1,"Generating panorama lookup table.");
 	uint halfRows = ceil(_numRows/2);
 	uint halfColumns = ceil(_numColumns/2);
 	float halfWidth = (float)_numColumns / 2.0f;
@@ -188,6 +532,11 @@ void RenderTable::generatePanoramaLookupTable() {
 	float xOffset = 0.0f;
 	float yOffset = 0.0f;
 	
+	debug(1,"halfWidth %f, halfHeight %f", halfWidth, halfHeight);
+	debug(1,"halfRows %d, halfColumns %d", halfRows, halfColumns);
+	
+	uint pixelAverageCount = 0;
+	
 	//Transformation is both horizontally and vertically symmetrical about the camera axis,
 	//We can thus save on trigonometric calculations by computing one quarter of the transformation matrix and then mirroring it in both X & Y
 	for (uint x = 0; x < halfColumns; ++x) {
@@ -217,19 +566,29 @@ void RenderTable::generatePanoramaLookupTable() {
 			xOffset = xInCylinderCoords - x; 
       yOffset = yInCylinderCoords - y;
       
+      bool _printDebug = (Common::Point(x,y)==testPixel);
+      if(_printDebug) {
+        debug(2,"\tGenerating test pixel %d, %d", x, y);
+        debug(2,"\tCylinder coordinates %f, %f", xInCylinderCoords, yInCylinderCoords);
+        debug(2,"\tOffsets %f,%f", xOffset, yOffset);
+      }
+      
 			// Only store the (x,y) offsets instead of the absolute positions
-			_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality);
+			_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality, _printDebug);
 			
 			//Store mirrored offset values
 			_internalBuffer[indexBL] = FilterPixel(xOffset, -yOffset, _highQuality);
 			_internalBuffer[indexTR] = FilterPixel(-xOffset, yOffset, _highQuality);
 			_internalBuffer[indexBR] = FilterPixel(-xOffset, -yOffset, _highQuality);
 			
+			pixelAverageCount += _internalBuffer[indexTL].xSteps + _internalBuffer[indexTL].ySteps;
+			
 			//Increment indices
 			rowIndexT += _numColumns;
 			rowIndexB -= _numColumns;
 		}
 	}
+	debug(1,"Render table generated, %s quality, filter tolerance %d, total pixel averaging operations per frame %e", _highQuality ? "high" : "low", _internalBuffer[0].tol, (float)pixelAverageCount*4);
 }
 
 void RenderTable::generateTiltLookupTable() {
@@ -259,6 +618,8 @@ void RenderTable::generateTiltLookupTable() {
 		uint32 columnIndexTR = columnIndexTL + (_numColumns - 1);
 		uint32 columnIndexBR = columnIndexBL + (_numColumns - 1);
 
+  //TODO - all four pixel values are always the same; find out why & fix.
+
 		for (uint x = 0; x < halfColumns; ++x) {
 			// To calculate x in cylinder coordinates, we can do similar triangles comparison,
 			// comparing the triangle from the center to the screen and from the center to the edge of the cylinder
@@ -271,9 +632,16 @@ void RenderTable::generateTiltLookupTable() {
 			
 			xOffset = xInCylinderCoords - x;
       yOffset = yInCylinderCoords - y;
+      
+      bool _printDebug = (Common::Point(x,y)==testPixel);
+      if(_printDebug) {
+        debug(2,"\tGenerating test pixel %d, %d", x, y);
+        debug(2,"\tCylinder coordinates %f, %f", xInCylinderCoords, yInCylinderCoords);
+        debug(2,"\tOffsets %f,%f", xOffset, yOffset);
+      }
 
 			// Only store the (x,y) offsets instead of the absolute positions
-			_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality);
+			_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality, _printDebug);
 			
 			//Store mirrored offset values
 			_internalBuffer[indexBL] = FilterPixel(xOffset, -yOffset, _highQuality);
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index 0c2577cf232..90a7a011065 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -29,26 +29,99 @@ namespace ZVision {
 
 class FilterPixel {
 public:
-  uint8 fracX = 0;  //Byte fraction of horizontal pixel position, 0 = left, 255 = right
-  uint8 fracY = 0;  //Byte fraction of vertical pixel position, 0 = top, 255 = bottom
-  //TODO - make this a sequential list for recursive filtering.  
+  const static uint8 colorBits = 5;
+  const static uint8 tol = 1;
+  const static uint8 pFrac = 0xff;
+  //Bitfields representing sequential direction of contraction
+  uint8 xDir = 0; //0 contract left, 1 contract right
+  uint8 yDir = 0; //0 contract up, 1 contract down
+  uint8 xSteps = 0; //Number of X-contractions carried out
+  uint8 ySteps = 0; //Number of y-contractions carried out
+  //TODO - make this a sequential list for recursive filtering.
   //TODO - Also include a recursion limit value so that we don't waste filtering operations on pixels that are already accurate enough.
   Common::Rect Src = Common::Rect(0,0);  //Coordinates of four panorama image pixels around actual working window pixel
   
+  uint8 fracX = 0;
+  uint8 fracY = 0;
+  
+  bool _printDebug = false;
+  
   FilterPixel() {};
-  FilterPixel(float x, float y, bool highQuality=false) {
-		if(highQuality) {
-	    Src.left = int16(floor(x));
-	    Src.right = int16(ceil(x));
-	    fracX = uint8((x-Src.left)*255);
-		  Src.top = int16(floor(y));
-		  Src.bottom = int16(ceil(y));
-		  fracY = uint8((y-Src.top)*255);
+  FilterPixel(float x, float y, bool highQuality=false, bool printDebug=false) {
+    Src.left = int16(floor(x));
+    Src.right = int16(ceil(x));
+	  Src.top = int16(floor(y));
+	  Src.bottom = int16(ceil(y));
+
+	  _printDebug = printDebug;
+
+    if(_printDebug)
+      debug(1,"\tTarget pixel offset: %f, %f", x, y);
+
+		//Bilinear
+	  if(highQuality) {
+      fracX = uint8((x-Src.left)*pFrac);  //Fraction of horizontal pixel position, 0 = left, pFrac = right
+      fracY = uint8((y-Src.top)*pFrac); //Fraction of vertical pixel position, 0 = top, pFrac = bottom
+	    uint xBound = pFrac >> 1;
+	    uint yBound = pFrac >> 1;
+      if(_printDebug) {
+        debug(1,"\tBilinear, xBound: %d, yBound: %d, tol: %d", xBound, yBound, tol);
+        debug(1,"\tByte fractions, fracX: %d, fracY: %d", fracX, fracY);
+      }
+	    for(uint8 i = (pFrac >> 2); i > tol; i >>= 1) {
+        if(_printDebug)
+          debug(1,"\txBound %d, yBound %d, i %d", xBound, yBound, i);
+	      if(fracX >= xBound) {
+  	      if(fracX-xBound > tol) {
+    	      xDir += 0x80;
+    	      xDir >>= 1;
+    	      xBound += i;
+    	      xSteps++;
+            if(_printDebug)
+              debug(1,"		Contract right, xDir: 0x%X, xSteps: %d", xDir, xSteps);
+  	      }
+	      }
+	      else {
+  	      if(xBound-fracX > tol) {
+    	      xDir >>= 1;
+    	      xBound -= i;
+    	      xSteps++;
+            if(_printDebug)
+              debug(1,"		Contract left, xDir: 0x%X, xSteps: %d", xDir, xSteps);
+  	      }
+	      }
+	      if(fracY >= yBound) {
+  	      if(fracY-yBound > tol) {
+    	      yDir += 0x80;
+    	      yDir >>= 1;
+    	      yBound += i;
+    	      ySteps++;
+            if(_printDebug)
+              debug(1,"		Contract downward, yDir: 0x%X, ySteps: %d", yDir, ySteps);
+  	      }  
+	      }
+	      else {
+  	      if(yBound-fracY > tol) {
+    	      yDir >>= 1;
+    	      yBound -= i;
+    	      ySteps++;
+            if(_printDebug)
+              debug(1,"		Contract upward, yDir: 0x%X, ySteps: %d", yDir, ySteps);
+  	      }
+	      }
+	    }
+	    xDir >>= (7-xSteps);
+	    yDir >>= (7-ySteps);
+      if(_printDebug)
+		    debug(2,"Xdir 0x%X, Ydir 0x%X, xSteps %d, ySteps %d", xDir, yDir, xSteps, ySteps);
 	  }
 	  else {
-		  Src.left = int16(round(x));
-  		Src.top = int16(round(y));
-		}
+    //Nearest neighbour
+		xDir = (x-Src.left) > 0.5f ? 0x01 : 0x00;
+		yDir = (y-Src.top) > 0.5f ? 0x01 : 0x00;
+    if(_printDebug)
+      debug(1,"\tNearest neighbour, xDir: 0x%X, yDir: 0x%X", xDir, yDir);
+	  }
   };
   ~FilterPixel() {};
 };
@@ -57,6 +130,8 @@ class RenderTable {
 public:
 	RenderTable(uint numRows, uint numColumns, const Graphics::PixelFormat pixelFormat);
 	~RenderTable();
+	
+	Common::Point testPixel = Common::Point(30,120);
 
 public:
 	enum RenderState {
@@ -72,7 +147,8 @@ private:
 	bool _highQuality = false;
 	const uint8 filterPasses = 2;
 	const Graphics::PixelFormat _pixelFormat;
-	uint16 avgL, avgH;
+	uint32 avgRB, avgG;
+	uint8 _tol = 10;  //TODO - allow different optimised values for ZGI & Nemesis
 
 	struct {
 		float verticalFOV;  //Radians
@@ -100,12 +176,38 @@ public:
 //	void mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 destWidth, const Common::Rect &subRect);
   void mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf, bool filter=false);
 	
-	inline uint16 avgPixels(uint16 &PixelA, uint16 &PixelB) {
-	  //NB Optimised & valid for RGB555 only!
-  	avgL = (PixelA & 0x3def) + (PixelB & 0x3def);  //Add first 4 respective bits of eagh 5-bit R, G & B value
-	  avgH = (PixelA & 0x4210) + (PixelB & 0x4210);  //Add 5th respective bit of each 5-bit R, G & B value
-	  return (avgH + (avgL & 0x7bde)) >> 1; //Combine upper & lower bits, dropping 1st respective bit of each 5-bit R, G & B value, & then halve to get averages.
+	template <typename I>
+	Common::String pixelToBinary(I &pixel, bool splitColors=true) {
+	  uint8 bits = sizeof(pixel) << 3;
+    Common::String str("0b");
+    I spaceMask = 0;
+    for(uint8 i = 0; i < 3; i++)
+      spaceMask = (spaceMask << 5) + 0x10;
+	  for(I mask = 0x01 << (bits-1); mask; mask >>= 1) {
+	    if(splitColors && (spaceMask & mask))
+	      str += " ";
+      str += mask & pixel ? "1" : "0";
+    }
+    return str;
+	}
+	
+//Old version
+/*/
+	inline void contractLeft(uint32 &LeftPixel, uint32 &RightPixel) {
+	  //NB Optimised & valid for RGB555 only; ALWAYS ROUNDS DOWN, WILL CAUSE CUMULATIVE ERRORS
+  	avgG = ((LeftPixel & 0x03e0) + (RightPixel & 0x03e0)) & 0x07c0;
+	  RightPixel = ((LeftPixel & 0x7c1f) + (RightPixel & 0x7c1f)) & 0xf83e;
+    RightPixel = (RightPixel | avgG) >> 1;
+	};
+	
+//New version
+/*/
+	inline void contractLeft(uint32 &LeftPixel, uint32 &RightPixel) {
+	  RightPixel = LeftPixel + RightPixel;
+	  LeftPixel <<= 1;
 	};
+//*/
+	
 	void generateRenderTable();
 
 	void setPanoramaFoV(float fov); //Degrees


Commit: 30a190c0974675689bcdd07b3a43284c0480ecc2
    https://github.com/scummvm/scummvm/commit/30a190c0974675689bcdd07b3a43284c0480ecc2
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:56+02:00

Commit Message:
ZVISION: Replace bilinear filter with simpler code.
Naive algorithm proves faster than integer juggling.
Still needs optimisation to maximise framerate.
Odd vertical artifact at centreline of screen; investigate.
Bugs remaining: previous scene shown for one frame at end of location transition videos.
Bilinear filter still not working in tilt mode.

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index aac94286e0d..5ece97df656 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -56,7 +56,7 @@ RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const G
 	  _backgroundWidth(0),
 	  _backgroundHeight(0),
 	  _backgroundOffset(0),
-	  _renderTable(_layout.workingArea.width(), _layout.workingArea.height(), pixelFormat),
+	  _renderTable(engine, _layout.workingArea.width(), _layout.workingArea.height(), pixelFormat),
 	  _doubleFPS(doubleFPS),
 	  _widescreen(widescreen) {
 	debug(1,"creating render manager");
@@ -213,10 +213,7 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
 	    case RenderTable::PANORAMA:
 	    case RenderTable::TILT:
 		    if (!_backgroundSurfaceDirtyRect.isEmpty()) {
-		      uint32 mutationTime = _system->getMillis();
 			    _renderTable.mutateImage(&_warpedSceneSurface, in, _engine->getScriptManager()->getStateValue(StateKey_HighQuality));
-          mutationTime = _system->getMillis() - mutationTime;
-          debug(1,"Panorama mutation time %dms, %s quality", mutationTime, _engine->getScriptManager()->getStateValue(StateKey_HighQuality) ? "high" : "low");
 			    out = &_warpedSceneSurface;
 			    outWndDirtyRect = Common::Rect(_workingArea.width(), _workingArea.height());
 		    }
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index ca91e053468..fd84865906f 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -22,7 +22,6 @@
 #ifndef ZVISION_RENDER_MANAGER_H
 #define ZVISION_RENDER_MANAGER_H
 
-#include "zvision/graphics/render_table.h"
 #include "zvision/text/truetype_font.h"
 
 #include "common/rect.h"
@@ -35,6 +34,8 @@
 
 #include "zvision/graphics/graphics_effect.h"
 
+#include "zvision/graphics/render_table.h"
+
 class OSystem;
 
 namespace Common {
diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index 282e05c2ae3..6a1c62df8a2 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -19,17 +19,22 @@
  *
  */
 
-#include "zvision/graphics/render_table.h"
-
 #include "common/rect.h"
 #include "common/scummsys.h"
 #include "math/utils.h"
+#include "zvision/zvision.h"
+#include "common/system.h"
+
+#include "zvision/graphics/render_table.h"
+#include "zvision/scripting/script_manager.h"
 
 namespace ZVision {
 
-RenderTable::RenderTable(uint numColumns, uint numRows, const Graphics::PixelFormat pixelFormat)
-	: _numRows(numRows),
-	  _numColumns(numColumns),
+RenderTable::RenderTable(ZVision *engine, uint numColumns, uint numRows, const Graphics::PixelFormat pixelFormat)
+	: _engine(engine),
+	  _system(engine->_system),
+	  _numRows(numRows),
+    _numColumns(numColumns),
 	  _renderState(FLAT),
 	  _pixelFormat(pixelFormat) {
 	assert(numRows != 0 && numColumns != 0);
@@ -73,8 +78,8 @@ const Common::Point RenderTable::convertWarpedCoordToFlatCoord(const Common::Poi
 	}
 	uint32 index = point.y * _numColumns + point.x;
 	Common::Point newPoint(point);
-	newPoint.x += (_internalBuffer[index].xDir & 0x01 ? _internalBuffer[index].Src.right : _internalBuffer[index].Src.left);
-	newPoint.y += (_internalBuffer[index].yDir & 0x01 ? _internalBuffer[index].Src.bottom : _internalBuffer[index].Src.top);
+	newPoint.x += (_internalBuffer[index].xDir ? _internalBuffer[index].Src.right : _internalBuffer[index].Src.left);
+	newPoint.y += (_internalBuffer[index].yDir ? _internalBuffer[index].Src.bottom : _internalBuffer[index].Src.top);
 	return newPoint;
 }
 
@@ -127,41 +132,23 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 	uint32 bufferBL = 0;
 	uint32 bufferTR = 0;
 	uint32 bufferBR = 0;
-	uint32 bufferTL_G = 0;
-	uint32 bufferBL_G = 0;
-	uint32 bufferTR_G = 0;
-	uint32 bufferBR_G = 0;
-
-
 	if(highQuality != _highQuality) {
 	  _highQuality = highQuality;
 	  generateRenderTable();
 	}
-	
+  uint32 mutationTime = _system->getMillis();
   if(_highQuality) {
     //Apply bilinear interpolation
 	  FilterPixel _curP;
-	  uint8 xCount = 0;
-	  uint8 yCount = 0;
-	  uint8 xDir = 0;
-	  uint8 yDir = 0;
-	  
-    //Deb
-	  uint8 r = 0;
-	  uint8 g = 0;
-	  uint8 b = 0;
-	  
+	  uint32 index;
+	  uint8 rTL,rTR,rBL,rBR,rF;
+	  uint8 gTL,gTR,gBL,gBR,gF;
+	  uint8 bTL,bTR,bBL,bBR,bF;
 	  for (int16 y = 0; y < srcBuf->h; ++y) {
 		  uint32 sourceOffset = y * _numColumns;
 		  for (int16 x = 0; x < srcBuf->w; ++x) {
-		    xCount = 0;
-		    yCount = 0;
-			  uint32 index = sourceOffset + x;
-			  // RenderTable only stores offsets from the original coordinates
+			  index = sourceOffset + x;
 			  _curP = _internalBuffer[index];
-			  xDir = _curP.xDir;
-			  yDir = _curP.yDir;
-
 			  srcIndexYT = y + _curP.Src.top;
 			  srcIndexYB = y + _curP.Src.bottom;
 			  srcIndexXL = x + _curP.Src.left;
@@ -170,326 +157,18 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 			  bufferTR = sourceBuffer[srcIndexYT * _numColumns + srcIndexXR];
 			  bufferBL = sourceBuffer[srcIndexYB * _numColumns + srcIndexXL];
 			  bufferBR = sourceBuffer[srcIndexYB * _numColumns + srcIndexXR];
-        if(_curP._printDebug) {
-          _pixelFormat.colorToRGB(bufferTL,r,g,b);
-          debug(2,"Original pixel value TL %s, RGB: %d,%d,%d", pixelToBinary(bufferTL).c_str(),r,g,b);
-          _pixelFormat.colorToRGB(bufferTR,r,g,b);
-          debug(2,"Original pixel value TR %s, RGB: %d,%d,%d", pixelToBinary(bufferTR).c_str(),r,g,b);
-          _pixelFormat.colorToRGB(bufferBL,r,g,b);
-          debug(2,"Original pixel value BL %s, RGB: %d,%d,%d", pixelToBinary(bufferBL).c_str(),r,g,b);
-          _pixelFormat.colorToRGB(bufferBR,r,g,b);
-          debug(2,"Original pixel value BR %s, RGB: %d,%d,%d", pixelToBinary(bufferBR).c_str(),r,g,b);
-			  }
-			  //Extract green values
-			  bufferTL_G = bufferTL & 0x03e0;
-			  bufferBL_G = bufferBL & 0x03e0;
-			  bufferTR_G = bufferTR & 0x03e0;
-			  bufferBR_G = bufferBR & 0x03e0;
-		    //Mask for red & blue values
-			  bufferTL &= 0x7c1f;
-			  bufferBL &= 0x7c1f;
-			  bufferTR &= 0x7c1f;
-			  bufferBR &= 0x7c1f;
-			  
-			  if(_curP._printDebug) {
-  			  debug(2,"\tTest pixel %d,%d", x, y);
-  			  debug(2,"\tX byte fraction %d, Y byte fraction %d", _curP.fracX, _curP.fracY);
-  			  debug(2,"\tX steps %d, Y steps %d", _curP.xSteps, _curP.ySteps);
-  			  debug(2,"\tXdir 0x%X, Ydir 0x%X", xDir, _curP.yDir);
-			  }
-			  
-        if(_curP._printDebug) {
-          _pixelFormat.colorToRGB(bufferTL,r,g,b);
-          debug(2,"Separated pixel value TL   %s, RGB: %d,%d,%d", pixelToBinary(bufferTL).c_str(), r,g,b);
-          _pixelFormat.colorToRGB(bufferTR,r,g,b);
-          debug(2,"Separated pixel value TR   %s, RGB: %d,%d,%d", pixelToBinary(bufferTR).c_str(),r,g,b);
-          _pixelFormat.colorToRGB(bufferBL,r,g,b);
-          debug(2,"Separated pixel value BL   %s, RGB: %d,%d,%d", pixelToBinary(bufferBL).c_str(),r,g,b);
-          _pixelFormat.colorToRGB(bufferBR,r,g,b);
-          debug(2,"Separated pixel value BR   %s, RGB: %d,%d,%d", pixelToBinary(bufferBR).c_str(),r,g,b);
-          _pixelFormat.colorToRGB(bufferTL_G,r,g,b);
-          debug(2,"Separated pixel value TL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTL_G).c_str(),r,g,b);
-          _pixelFormat.colorToRGB(bufferTR_G,r,g,b);
-          debug(2,"Separated pixel value TR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTR_G).c_str(),r,g,b);
-          _pixelFormat.colorToRGB(bufferBL_G,r,g,b);
-          debug(2,"Separated pixel value BL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBL_G).c_str(),r,g,b);
-          _pixelFormat.colorToRGB(bufferBR_G,r,g,b);
-          debug(2,"Separated pixel value BR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBR_G).c_str(),r,g,b);
-		    }
-			  
-        //Horizontal contraction
-		    if(_curP.ySteps > 1) {
-          while(_curP.xSteps > xCount+1) {
-            xCount++;
-            if(_curP.xDir & 0x01) {
-			        if(_curP._printDebug)
-			          debug(2,"\t\tContracting right, T&B");
-		          contractLeft(bufferTR, bufferTL);
-		          contractLeft(bufferBR, bufferBL);
-		          contractLeft(bufferTR_G, bufferTL_G);
-		          contractLeft(bufferBR_G, bufferBL_G);
-            }
-            else {
-			        if(_curP._printDebug)
-			          debug(2,"\t\tContracting left, T&B");
-		          contractLeft(bufferTL, bufferTR);
-		          contractLeft(bufferBL, bufferBR);
-		          contractLeft(bufferTL_G, bufferTR_G);
-		          contractLeft(bufferBL_G, bufferBR_G);
-            }
-            _curP.xDir >>= 1;
-            		          
-            if(_curP._printDebug) {
-		          debug(2,"\t\txDir 0x%X", _curP.xDir);	   
-              _pixelFormat.colorToRGB(bufferTL,r,g,b);
-              debug(2,"Contracted pixel value TL   %s, RGB: %d,%d,%d", pixelToBinary(bufferTL).c_str(), r,g,b);
-              _pixelFormat.colorToRGB(bufferTR,r,g,b);
-              debug(2,"Contracted pixel value TR   %s, RGB: %d,%d,%d", pixelToBinary(bufferTR).c_str(),r,g,b);
-              _pixelFormat.colorToRGB(bufferBL,r,g,b);
-              debug(2,"Contracted pixel value BL   %s, RGB: %d,%d,%d", pixelToBinary(bufferBL).c_str(),r,g,b);
-              _pixelFormat.colorToRGB(bufferBR,r,g,b);
-              debug(2,"Contracted pixel value BR   %s, RGB: %d,%d,%d", pixelToBinary(bufferBR).c_str(),r,g,b);
-              _pixelFormat.colorToRGB(bufferTL_G,r,g,b);
-              debug(2,"Contracted pixel value TL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTL_G).c_str(),r,g,b);
-              _pixelFormat.colorToRGB(bufferTR_G,r,g,b);
-              debug(2,"Contracted pixel value TR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTR_G).c_str(),r,g,b);
-              _pixelFormat.colorToRGB(bufferBL_G,r,g,b);
-              debug(2,"Contracted pixel value BL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBL_G).c_str(),r,g,b);
-              _pixelFormat.colorToRGB(bufferBR_G,r,g,b);
-              debug(2,"Contracted pixel value BR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBR_G).c_str(),r,g,b);
-			      }
-          }
-//*/
-          if(_curP.xDir & 0x01) {
-            bufferBR = (bufferBR >> xCount) & 0x7c1f;
-            bufferBR_G = (bufferBR_G >> xCount) & 0x03e0;
-            bufferTR = (bufferTR >> xCount) & 0x7c1f;
-            bufferTR_G = (bufferTR_G >> xCount) & 0x03e0;
-          }
-          else {
-            bufferBL = (bufferBL >> xCount) & 0x7c1f;
-            bufferBL_G = (bufferBL_G >> xCount) & 0x03e0;
-            bufferTL = (bufferTL >> xCount) & 0x7c1f;
-            bufferTL_G = (bufferTL_G >> xCount) & 0x03e0;
-          }
-          if(_curP._printDebug) {
-            debug(2,"\tShifted back %d places", xCount);
-            _pixelFormat.colorToRGB(bufferTL,r,g,b);
-            debug(2,"Shifted pixel value TL   %s, RGB: %d,%d,%d", pixelToBinary(bufferTL).c_str(), r,g,b);
-            _pixelFormat.colorToRGB(bufferTR,r,g,b);
-            debug(2,"Shifted pixel value TR   %s, RGB: %d,%d,%d", pixelToBinary(bufferTR).c_str(),r,g,b);
-            _pixelFormat.colorToRGB(bufferBL,r,g,b);
-            debug(2,"Shifted pixel value BL   %s, RGB: %d,%d,%d", pixelToBinary(bufferBL).c_str(),r,g,b);
-            _pixelFormat.colorToRGB(bufferBR,r,g,b);
-            debug(2,"Shifted pixel value BR   %s, RGB: %d,%d,%d", pixelToBinary(bufferBR).c_str(),r,g,b);
-            _pixelFormat.colorToRGB(bufferTL_G,r,g,b);
-            debug(2,"Shifted pixel value TL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTL_G).c_str(),r,g,b);
-            _pixelFormat.colorToRGB(bufferTR_G,r,g,b);
-            debug(2,"Shifted pixel value TR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTR_G).c_str(),r,g,b);
-            _pixelFormat.colorToRGB(bufferBL_G,r,g,b);
-            debug(2,"Shifted pixel value BL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBL_G).c_str(),r,g,b);
-            _pixelFormat.colorToRGB(bufferBR_G,r,g,b);
-            debug(2,"Shifted pixel value BR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBR_G).c_str(),r,g,b);
-			    }
-//*/
-        }
-        else if (_curP.yDir) {
-          while(_curP.xSteps > xCount+1) {
-            xCount++;
-            if(_curP.xDir & 0x01) {
-			        if(_curP._printDebug)
-			          debug(2,"\t\tContracting right, B");
-		          contractLeft(bufferBR, bufferBL);
-		          contractLeft(bufferBR_G, bufferBL_G);
-            }
-            else {
-			        if(_curP._printDebug)
-			          debug(2,"\t\tContracting left, B");
-		          contractLeft(bufferBL, bufferBR);
-		          contractLeft(bufferBL_G, bufferBR_G);
-            }
-            _curP.xDir >>= 1;
-            
-            if(_curP._printDebug) {
-              _pixelFormat.colorToRGB(bufferBL,r,g,b);
-              debug(2,"Contracted pixel value BL   %s, RGB: %d,%d,%d", pixelToBinary(bufferBL).c_str(),r,g,b);
-              _pixelFormat.colorToRGB(bufferBR,r,g,b);
-              debug(2,"Contracted pixel value BR   %s, RGB: %d,%d,%d", pixelToBinary(bufferBR).c_str(),r,g,b);
-              _pixelFormat.colorToRGB(bufferBL_G,r,g,b);
-              debug(2,"Contracted pixel value BL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBL_G).c_str(),r,g,b);
-              _pixelFormat.colorToRGB(bufferBR_G,r,g,b);
-              debug(2,"Contracted pixel value BR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBR_G).c_str(),r,g,b);
-			      }
-          }
-//*/
-          if(_curP.xDir & 0x01) {
-            bufferBR = (bufferBR >> xCount) & 0x7c1f;
-            bufferBR_G = (bufferBR_G >> xCount) & 0x03e0;
-          }
-          else {
-            bufferBL = (bufferBL >> xCount) & 0x7c1f;
-            bufferBL_G = (bufferBL_G >> xCount) & 0x03e0;
-          }
-          if(_curP._printDebug) {
-            debug(2,"\tShifted back %d places", xCount);
-            _pixelFormat.colorToRGB(bufferBL,r,g,b);
-            debug(2,"Shifted pixel value BL   %s, RGB: %d,%d,%d", pixelToBinary(bufferBL).c_str(),r,g,b);
-            _pixelFormat.colorToRGB(bufferBR,r,g,b);
-            debug(2,"Shifted pixel value BR   %s, RGB: %d,%d,%d", pixelToBinary(bufferBR).c_str(),r,g,b);
-            _pixelFormat.colorToRGB(bufferBL_G,r,g,b);
-            debug(2,"Shifted pixel value BL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBL_G).c_str(),r,g,b);
-            _pixelFormat.colorToRGB(bufferBR_G,r,g,b);
-            debug(2,"Shifted pixel value BR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBR_G).c_str(),r,g,b);
-			    }
-//*/
-        }
-        else {
-          while(_curP.xSteps > xCount+1) {
-            xCount++;
-            if(_curP.xDir & 0x01) {
-			        if(_curP._printDebug)
-			          debug(2,"\t\tContracting right, T");
-		          contractLeft(bufferTR, bufferTL);
-		          contractLeft(bufferTR_G, bufferTL_G);
-            }
-            else {
-			        if(_curP._printDebug)
-			          debug(2,"\t\tContracting left, T");
-		          contractLeft(bufferTL, bufferTR);
-		          contractLeft(bufferTL_G, bufferTR_G);
-            }
-            _curP.xDir >>= 1;
-            
-            if(_curP._printDebug) {
-              _pixelFormat.colorToRGB(bufferTL,r,g,b);
-              debug(2,"Contracted pixel value TL   %s, RGB: %d,%d,%d", pixelToBinary(bufferTL).c_str(), r,g,b);
-              _pixelFormat.colorToRGB(bufferTR,r,g,b);
-              debug(2,"Contracted pixel value TR   %s, RGB: %d,%d,%d", pixelToBinary(bufferTR).c_str(),r,g,b);
-              _pixelFormat.colorToRGB(bufferTL_G,r,g,b);
-              debug(2,"Contracted pixel value TL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTL_G).c_str(),r,g,b);
-              _pixelFormat.colorToRGB(bufferTR_G,r,g,b);
-              debug(2,"Contracted pixel value TR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTR_G).c_str(),r,g,b);
-			      }
-          }
-//*/
-          if(_curP.xDir & 0x01) {
-            bufferTR = (bufferTR >> xCount) & 0x7c1f;
-            bufferTR_G = (bufferTR_G >> xCount) & 0x03e0;
-          }
-          else {
-            bufferTL = (bufferTL >> xCount) & 0x7c1f;
-            bufferTL_G = (bufferTL_G >> xCount) & 0x03e0;
-          }
-          if(_curP._printDebug) {
-            debug(2,"\tShifted back %d places", xCount);
-            _pixelFormat.colorToRGB(bufferTL,r,g,b);
-            debug(2,"Shifted pixel value TL   %s, RGB: %d,%d,%d", pixelToBinary(bufferTL).c_str(), r,g,b);
-            _pixelFormat.colorToRGB(bufferTR,r,g,b);
-            debug(2,"Shifted pixel value TR   %s, RGB: %d,%d,%d", pixelToBinary(bufferTR).c_str(),r,g,b);
-            _pixelFormat.colorToRGB(bufferTL_G,r,g,b);
-            debug(2,"Shifted pixel value TL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTL_G).c_str(),r,g,b);
-            _pixelFormat.colorToRGB(bufferTR_G,r,g,b);
-            debug(2,"Shifted pixel value TR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTR_G).c_str(),r,g,b);
-			    }
-//*/
-        }
-        
-        //Vertical contraction
-        if(_curP.xDir & 0x01) {
-          while(_curP.ySteps > yCount+1) {
-            yCount++;
-            if(_curP.yDir & 0x01) {
-			        if(_curP._printDebug)
-			          debug(2,"\t\tContracting downward, R");
-		          contractLeft(bufferBR, bufferTR);
-		          contractLeft(bufferBR_G, bufferTR_G);
-            }
-            else {
-			        if(_curP._printDebug)
-			          debug(2,"\t\tContracting upward, R");
-		          contractLeft(bufferTR, bufferBR);
-		          contractLeft(bufferTR_G, bufferBR_G);
-            }
-            _curP.yDir >>= 1;
-            
-            if(_curP._printDebug) {
-              _pixelFormat.colorToRGB(bufferTR,r,g,b);
-              debug(2,"Contracted pixel value TR   %s, RGB: %d,%d,%d", pixelToBinary(bufferTR).c_str(), r,g,b);
-              _pixelFormat.colorToRGB(bufferBR,r,g,b);
-              debug(2,"Contracted pixel value BR   %s, RGB: %d,%d,%d", pixelToBinary(bufferBR).c_str(),r,g,b);
-              _pixelFormat.colorToRGB(bufferTR_G,r,g,b);
-              debug(2,"Contracted pixel value TR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTR_G).c_str(),r,g,b);
-              _pixelFormat.colorToRGB(bufferBR_G,r,g,b);
-              debug(2,"Contracted pixel value BR_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBR_G).c_str(),r,g,b);
-			      }
-          }
-        }
-        else {
-          while(_curP.ySteps > yCount+1) {
-            yCount++;
-		        if(_curP._printDebug)
-		          debug(2,"yDir %x", _curP.yDir);
-            if(_curP.yDir & 0x01) {
-			        if(_curP._printDebug)
-			          debug(2,"\t\tContracting downward, L");
-		          contractLeft(bufferBL, bufferTL);
-		          contractLeft(bufferBL_G, bufferTL_G);
-            }
-            else {
-			        if(_curP._printDebug)
-			          debug(2,"\t\tContracting upward, L");
-		          contractLeft(bufferTL, bufferBL);
-		          contractLeft(bufferTL_G, bufferBL_G);
-            }
-            _curP.yDir >>= 1;
-            
-            if(_curP._printDebug) {
-              _pixelFormat.colorToRGB(bufferTL,r,g,b);
-              debug(2,"Contracted pixel value TL   %s, RGB: %d,%d,%d", pixelToBinary(bufferTL).c_str(), r,g,b);
-              _pixelFormat.colorToRGB(bufferBL,r,g,b);
-              debug(2,"Contracted pixel value BL   %s, RGB: %d,%d,%d", pixelToBinary(bufferBL).c_str(),r,g,b);
-              _pixelFormat.colorToRGB(bufferTL_G,r,g,b);
-              debug(2,"Contracted pixel value TL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferTL_G).c_str(),r,g,b);
-              _pixelFormat.colorToRGB(bufferBL_G,r,g,b);
-              debug(2,"Contracted pixel value BL_G %s, RGB: %d,%d,%d", pixelToBinary(bufferBL_G).c_str(),r,g,b);
-			      }
-          }
-        }
-        if(_curP._printDebug)
-          debug(2,"yCount %d", yCount);
-        //Final value
-        if(_curP.yDir & 0x01) {
-          if(_curP.xDir & 0x01) {
-		        if(_curP._printDebug)
-		          debug(2,"\t\tPicking final value, BR");
-            destBuffer[destOffset] = ((bufferBR >> yCount) & 0x7c1f) | ((bufferBR_G >> yCount) & 0x03e0);
-          }
-          else {
-		        if(_curP._printDebug)
-		          debug(2,"\t\tPicking final value, BL");
-            destBuffer[destOffset] = ((bufferBL >> yCount) & 0x7c1f) | ((bufferBL_G >> yCount) & 0x03e0);
-          }
-        }
-        else {
-          if(_curP.xDir & 0x01) {
-		        if(_curP._printDebug)
-		          debug(2,"\t\tPicking final value, TR");
-            destBuffer[destOffset] = ((bufferTR >> yCount) & 0x7c1f) | ((bufferTR_G >> yCount) & 0x03e0);
-          }
-          else {
-		        if(_curP._printDebug)
-		          debug(2,"\t\tPicking final value, TL");
-            destBuffer[destOffset] = ((bufferTL >> yCount) & 0x7c1f) | ((bufferTL_G >> yCount) & 0x03e0);
-          }
-        }        
-        if(_curP._printDebug) { 
-          _pixelFormat.colorToRGB(destBuffer[destOffset],r,g,b);
-          debug(2,"Final pixel value %s, RGB: %d,%d,%d", pixelToBinary(bufferBR).c_str(),r,g,b);
-        }    
-		    destOffset++;     
-		  }
-	  }
-  }
+        _pixelFormat.colorToRGB(bufferTL,rTL,gTL,bTL);
+        _pixelFormat.colorToRGB(bufferTR,rTR,gTR,bTR);
+        _pixelFormat.colorToRGB(bufferBL,rBL,gBL,bBL);
+        _pixelFormat.colorToRGB(bufferBR,rBR,gBR,bBR);
+        rF = round(_curP.fTL*rTL + _curP.fTR*rTR + _curP.fBL*rBL + _curP.fBR*rBR);
+        gF = round(_curP.fTL*gTL + _curP.fTR*gTR + _curP.fBL*gBL + _curP.fBR*gBR);
+        bF = round(_curP.fTL*bTL + _curP.fTR*bTR + _curP.fBL*bBL + _curP.fBR*bBR);
+        destBuffer[destOffset] = _pixelFormat.RGBToColor(rF,gF,bF);
+		    destOffset++;
+      }
+    }
+	}
   else {
     //Apply nearest-neighbour interpolation
 	  for (int16 y = 0; y < srcBuf->h; ++y) {
@@ -504,17 +183,23 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 		  }
 	  }
   }
+  mutationTime = _system->getMillis() - mutationTime;
+  debug(1,"\tPanorama mutation time %dms, %s quality", mutationTime, _engine->getScriptManager()->getStateValue(StateKey_HighQuality) ? "high" : "low");
 }
 
 void RenderTable::generateRenderTable() {
 	switch (_renderState) {
-	  case ZVision::RenderTable::PANORAMA:
+	  case RenderTable::PANORAMA: {
+      uint32 generationTime = _system->getMillis();
 		  generatePanoramaLookupTable();
+      generationTime = _system->getMillis() - generationTime;		  
+      debug(1,"\tRender table generation time %dms, %s quality", generationTime, _engine->getScriptManager()->getStateValue(StateKey_HighQuality) ? "high" : "low");
 		  break;
-	  case ZVision::RenderTable::TILT:
+	  }
+	  case RenderTable::TILT:
 		  generateTiltLookupTable();
 		  break;
-	  case ZVision::RenderTable::FLAT:
+	  case RenderTable::FLAT:
 		  // Intentionally left empty
 		  break;
 	  default:
@@ -535,8 +220,6 @@ void RenderTable::generatePanoramaLookupTable() {
 	debug(1,"halfWidth %f, halfHeight %f", halfWidth, halfHeight);
 	debug(1,"halfRows %d, halfColumns %d", halfRows, halfColumns);
 	
-	uint pixelAverageCount = 0;
-	
 	//Transformation is both horizontally and vertically symmetrical about the camera axis,
 	//We can thus save on trigonometric calculations by computing one quarter of the transformation matrix and then mirroring it in both X & Y
 	for (uint x = 0; x < halfColumns; ++x) {
@@ -581,14 +264,12 @@ void RenderTable::generatePanoramaLookupTable() {
 			_internalBuffer[indexTR] = FilterPixel(-xOffset, yOffset, _highQuality);
 			_internalBuffer[indexBR] = FilterPixel(-xOffset, -yOffset, _highQuality);
 			
-			pixelAverageCount += _internalBuffer[indexTL].xSteps + _internalBuffer[indexTL].ySteps;
-			
 			//Increment indices
 			rowIndexT += _numColumns;
 			rowIndexB -= _numColumns;
 		}
 	}
-	debug(1,"Render table generated, %s quality, filter tolerance %d, total pixel averaging operations per frame %e", _highQuality ? "high" : "low", _internalBuffer[0].tol, (float)pixelAverageCount*4);
+	debug(1,"Render table generated, %s quality", _highQuality ? "high" : "low");
 }
 
 void RenderTable::generateTiltLookupTable() {
@@ -636,13 +317,11 @@ void RenderTable::generateTiltLookupTable() {
       bool _printDebug = (Common::Point(x,y)==testPixel);
       if(_printDebug) {
         debug(2,"\tGenerating test pixel %d, %d", x, y);
-        debug(2,"\tCylinder coordinates %f, %f", xInCylinderCoords, yInCylinderCoords);
+        debug(2,"\tCylinder coordinates %d, %d", xInCylinderCoords, yInCylinderCoords);
         debug(2,"\tOffsets %f,%f", xOffset, yOffset);
       }
-
 			// Only store the (x,y) offsets instead of the absolute positions
-			_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality, _printDebug);
-			
+			_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality, _printDebug);			
 			//Store mirrored offset values
 			_internalBuffer[indexBL] = FilterPixel(xOffset, -yOffset, _highQuality);
 			_internalBuffer[indexTR] = FilterPixel(-xOffset, yOffset, _highQuality);
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index 90a7a011065..d4b3da6b726 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -25,24 +25,18 @@
 #include "common/rect.h"
 #include "graphics/surface.h"
 
+class OSystem;
+
 namespace ZVision {
 
 class FilterPixel {
 public:
-  const static uint8 colorBits = 5;
-  const static uint8 tol = 1;
-  const static uint8 pFrac = 0xff;
   //Bitfields representing sequential direction of contraction
-  uint8 xDir = 0; //0 contract left, 1 contract right
-  uint8 yDir = 0; //0 contract up, 1 contract down
-  uint8 xSteps = 0; //Number of X-contractions carried out
-  uint8 ySteps = 0; //Number of y-contractions carried out
-  //TODO - make this a sequential list for recursive filtering.
-  //TODO - Also include a recursion limit value so that we don't waste filtering operations on pixels that are already accurate enough.
+  bool xDir = 0; //0 left, 1 right
+  bool yDir = 0; //0 up, 1 down
   Common::Rect Src = Common::Rect(0,0);  //Coordinates of four panorama image pixels around actual working window pixel
   
-  uint8 fracX = 0;
-  uint8 fracY = 0;
+  float fX, fY, fTL, fTR, fBL, fBR;
   
   bool _printDebug = false;
   
@@ -52,75 +46,25 @@ public:
     Src.right = int16(ceil(x));
 	  Src.top = int16(floor(y));
 	  Src.bottom = int16(ceil(y));
-
 	  _printDebug = printDebug;
-
     if(_printDebug)
       debug(1,"\tTarget pixel offset: %f, %f", x, y);
-
-		//Bilinear
-	  if(highQuality) {
-      fracX = uint8((x-Src.left)*pFrac);  //Fraction of horizontal pixel position, 0 = left, pFrac = right
-      fracY = uint8((y-Src.top)*pFrac); //Fraction of vertical pixel position, 0 = top, pFrac = bottom
-	    uint xBound = pFrac >> 1;
-	    uint yBound = pFrac >> 1;
-      if(_printDebug) {
-        debug(1,"\tBilinear, xBound: %d, yBound: %d, tol: %d", xBound, yBound, tol);
-        debug(1,"\tByte fractions, fracX: %d, fracY: %d", fracX, fracY);
-      }
-	    for(uint8 i = (pFrac >> 2); i > tol; i >>= 1) {
-        if(_printDebug)
-          debug(1,"\txBound %d, yBound %d, i %d", xBound, yBound, i);
-	      if(fracX >= xBound) {
-  	      if(fracX-xBound > tol) {
-    	      xDir += 0x80;
-    	      xDir >>= 1;
-    	      xBound += i;
-    	      xSteps++;
-            if(_printDebug)
-              debug(1,"		Contract right, xDir: 0x%X, xSteps: %d", xDir, xSteps);
-  	      }
-	      }
-	      else {
-  	      if(xBound-fracX > tol) {
-    	      xDir >>= 1;
-    	      xBound -= i;
-    	      xSteps++;
-            if(_printDebug)
-              debug(1,"		Contract left, xDir: 0x%X, xSteps: %d", xDir, xSteps);
-  	      }
-	      }
-	      if(fracY >= yBound) {
-  	      if(fracY-yBound > tol) {
-    	      yDir += 0x80;
-    	      yDir >>= 1;
-    	      yBound += i;
-    	      ySteps++;
-            if(_printDebug)
-              debug(1,"		Contract downward, yDir: 0x%X, ySteps: %d", yDir, ySteps);
-  	      }  
-	      }
-	      else {
-  	      if(yBound-fracY > tol) {
-    	      yDir >>= 1;
-    	      yBound -= i;
-    	      ySteps++;
-            if(_printDebug)
-              debug(1,"		Contract upward, yDir: 0x%X, ySteps: %d", yDir, ySteps);
-  	      }
-	      }
-	    }
-	    xDir >>= (7-xSteps);
-	    yDir >>= (7-ySteps);
+    if(highQuality) {
+      fX = x-(float)Src.left;
+      fY = y-(float)Src.top;
+      fTL = (1-fX)*(1-fY);
+      fTR = fX*(1-fY);
+      fBL = (1-fX)*fY;
+      fBR = fX*fY;
       if(_printDebug)
-		    debug(2,"Xdir 0x%X, Ydir 0x%X, xSteps %d, ySteps %d", xDir, yDir, xSteps, ySteps);
-	  }
+        debug(1,"fX: %f, fY: %f, fTL:%f, fTR:%f, fBL:%f, fBR:%f", fX, fY, fTL, fTR, fBL, fBR);
+    }
 	  else {
-    //Nearest neighbour
-		xDir = (x-Src.left) > 0.5f ? 0x01 : 0x00;
-		yDir = (y-Src.top) > 0.5f ? 0x01 : 0x00;
-    if(_printDebug)
-      debug(1,"\tNearest neighbour, xDir: 0x%X, yDir: 0x%X", xDir, yDir);
+      //Nearest neighbour
+		  xDir = (x-Src.left) > 0.5f;
+		  yDir = (y-Src.top) > 0.5f;
+      if(_printDebug)
+        debug(1,"\tNearest neighbour, xDir: 0x%X, yDir: 0x%X", xDir, yDir);
 	  }
   };
   ~FilterPixel() {};
@@ -128,7 +72,7 @@ public:
 
 class RenderTable {
 public:
-	RenderTable(uint numRows, uint numColumns, const Graphics::PixelFormat pixelFormat);
+	RenderTable(ZVision *engine, uint numRows, uint numColumns, const Graphics::PixelFormat pixelFormat);
 	~RenderTable();
 	
 	Common::Point testPixel = Common::Point(30,120);
@@ -141,6 +85,8 @@ public:
 	};
 
 private:
+	ZVision *_engine;
+	OSystem *_system;
 	uint _numColumns, _numRows; //Working area width, height
   FilterPixel *_internalBuffer;
 	RenderState _renderState;


Commit: 72862da3796e4b515347f1647ac148e14f2c48f9
    https://github.com/scummvm/scummvm/commit/72862da3796e4b515347f1647ac148e14f2c48f9
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:56+02:00

Commit Message:
ZVISION: Refine bilinear filter code; considerable speed improvement.

Changed paths:
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h


diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index 6a1c62df8a2..bb2bf1f25a1 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -128,10 +128,6 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
   uint32 srcIndexYB = 0;
 	uint16 *sourceBuffer = (uint16 *)srcBuf->getPixels();
 	uint16 *destBuffer = (uint16 *)dstBuf->getPixels();
-	uint32 bufferTL = 0;
-	uint32 bufferBL = 0;
-	uint32 bufferTR = 0;
-	uint32 bufferBR = 0;
 	if(highQuality != _highQuality) {
 	  _highQuality = highQuality;
 	  generateRenderTable();
@@ -141,9 +137,9 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
     //Apply bilinear interpolation
 	  FilterPixel _curP;
 	  uint32 index;
-	  uint8 rTL,rTR,rBL,rBR,rF;
-	  uint8 gTL,gTR,gBL,gBR,gF;
-	  uint8 bTL,bTR,bBL,bBR,bF;
+	  uint32 rTL,rTR,rBL,rBR,rF;
+	  uint32 gTL,gTR,gBL,gBR,gF;
+	  uint32 bTL,bTR,bBL,bBR,bF;
 	  for (int16 y = 0; y < srcBuf->h; ++y) {
 		  uint32 sourceOffset = y * _numColumns;
 		  for (int16 x = 0; x < srcBuf->w; ++x) {
@@ -153,18 +149,14 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 			  srcIndexYB = y + _curP.Src.bottom;
 			  srcIndexXL = x + _curP.Src.left;
 			  srcIndexXR = x + _curP.Src.right;
-			  bufferTL = sourceBuffer[srcIndexYT * _numColumns + srcIndexXL];
-			  bufferTR = sourceBuffer[srcIndexYT * _numColumns + srcIndexXR];
-			  bufferBL = sourceBuffer[srcIndexYB * _numColumns + srcIndexXL];
-			  bufferBR = sourceBuffer[srcIndexYB * _numColumns + srcIndexXR];
-        _pixelFormat.colorToRGB(bufferTL,rTL,gTL,bTL);
-        _pixelFormat.colorToRGB(bufferTR,rTR,gTR,bTR);
-        _pixelFormat.colorToRGB(bufferBL,rBL,gBL,bBL);
-        _pixelFormat.colorToRGB(bufferBR,rBR,gBR,bBR);
+        splitColor(sourceBuffer[srcIndexYT * _numColumns + srcIndexXL], rTL, gTL, bTL);
+        splitColor(sourceBuffer[srcIndexYT * _numColumns + srcIndexXR], rTR, gTR, bTR);
+        splitColor(sourceBuffer[srcIndexYB * _numColumns + srcIndexXL], rBL, gBL, bBL);
+        splitColor(sourceBuffer[srcIndexYB * _numColumns + srcIndexXR], rBR, gBR, bBR);      
         rF = round(_curP.fTL*rTL + _curP.fTR*rTR + _curP.fBL*rBL + _curP.fBR*rBR);
         gF = round(_curP.fTL*gTL + _curP.fTR*gTR + _curP.fBL*gBL + _curP.fBR*gBR);
         bF = round(_curP.fTL*bTL + _curP.fTR*bTR + _curP.fBL*bBL + _curP.fBR*bBR);
-        destBuffer[destOffset] = _pixelFormat.RGBToColor(rF,gF,bF);
+        destBuffer[destOffset] = mergeColor(rF,gF,bF);
 		    destOffset++;
       }
     }
@@ -222,6 +214,7 @@ void RenderTable::generatePanoramaLookupTable() {
 	
 	//Transformation is both horizontally and vertically symmetrical about the camera axis,
 	//We can thus save on trigonometric calculations by computing one quarter of the transformation matrix and then mirroring it in both X & Y
+	//TODO - find & fix cause of vertial "seam" in Nemesis.
 	for (uint x = 0; x < halfColumns; ++x) {
 		// Add an offset of 0.01 to overcome zero tan/atan issue (vertical line on half of screen)
 		// Alpha represents the horizontal angle between the viewer at the center of a cylinder and x
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index d4b3da6b726..abff02d1e48 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -93,8 +93,17 @@ private:
 	bool _highQuality = false;
 	const uint8 filterPasses = 2;
 	const Graphics::PixelFormat _pixelFormat;
-	uint32 avgRB, avgG;
-	uint8 _tol = 10;  //TODO - allow different optimised values for ZGI & Nemesis
+	
+  inline void splitColor(uint16 &color, uint32 &r, uint32 &g, uint32 &b) {
+    //NB Left & right shifting unnecessary for interpolating & recombining, so not bothering in order to save cycles
+    r = color & 0x001f;
+    g = color & 0x03e0;
+    b = color & 0x7c00;
+  };
+  inline uint16 mergeColor(uint32 &r, uint32 &g, uint32 &b) const {
+    return (r & 0x001f) | (g & 0x03e0) | (b & 0x7c00);
+  };
+
 
 	struct {
 		float verticalFOV;  //Radians
@@ -137,23 +146,6 @@ public:
     return str;
 	}
 	
-//Old version
-/*/
-	inline void contractLeft(uint32 &LeftPixel, uint32 &RightPixel) {
-	  //NB Optimised & valid for RGB555 only; ALWAYS ROUNDS DOWN, WILL CAUSE CUMULATIVE ERRORS
-  	avgG = ((LeftPixel & 0x03e0) + (RightPixel & 0x03e0)) & 0x07c0;
-	  RightPixel = ((LeftPixel & 0x7c1f) + (RightPixel & 0x7c1f)) & 0xf83e;
-    RightPixel = (RightPixel | avgG) >> 1;
-	};
-	
-//New version
-/*/
-	inline void contractLeft(uint32 &LeftPixel, uint32 &RightPixel) {
-	  RightPixel = LeftPixel + RightPixel;
-	  LeftPixel <<= 1;
-	};
-//*/
-	
 	void generateRenderTable();
 
 	void setPanoramaFoV(float fov); //Degrees


Commit: 7b74779090714b772b58021df09b2116c0700166
    https://github.com/scummvm/scummvm/commit/7b74779090714b772b58021df09b2116c0700166
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:57+02:00

Commit Message:
ZVISION: Refine render table generation code; considerable speed improvement.

Changed paths:
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h


diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index bb2bf1f25a1..c3111be6769 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -247,16 +247,16 @@ void RenderTable::generatePanoramaLookupTable() {
         debug(2,"\tGenerating test pixel %d, %d", x, y);
         debug(2,"\tCylinder coordinates %f, %f", xInCylinderCoords, yInCylinderCoords);
         debug(2,"\tOffsets %f,%f", xOffset, yOffset);
-      }
-      
+      } 
 			// Only store the (x,y) offsets instead of the absolute positions
 			_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality, _printDebug);
-			
 			//Store mirrored offset values
-			_internalBuffer[indexBL] = FilterPixel(xOffset, -yOffset, _highQuality);
-			_internalBuffer[indexTR] = FilterPixel(-xOffset, yOffset, _highQuality);
-			_internalBuffer[indexBR] = FilterPixel(-xOffset, -yOffset, _highQuality);
-			
+			_internalBuffer[indexBL] = _internalBuffer[indexTL];
+			_internalBuffer[indexBL].flipV();
+			_internalBuffer[indexTR] = _internalBuffer[indexTL];
+			_internalBuffer[indexTR].flipH();
+			_internalBuffer[indexBR] = _internalBuffer[indexBL];
+			_internalBuffer[indexBR].flipH();
 			//Increment indices
 			rowIndexT += _numColumns;
 			rowIndexB -= _numColumns;
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index abff02d1e48..f7e30ab85af 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -68,6 +68,14 @@ public:
 	  }
   };
   ~FilterPixel() {};
+  inline void flipH() {
+    Src.left = -Src.left;
+    Src.right = -Src.right;
+  };
+  inline void flipV() {
+    Src.top = -Src.top;
+    Src.bottom = -Src.bottom;
+  };
 };
 
 class RenderTable {


Commit: 9e887ac6e2a852e7077d16525861d969d34860ed
    https://github.com/scummvm/scummvm/commit/9e887ac6e2a852e7077d16525861d969d34860ed
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:57+02:00

Commit Message:
ZVISION: Improve panorama mutation code.
Lessens vertical "seam" artefact in Nemesis.
Better, but still faintly noticeable in some scenes.

Changed paths:
    engines/zvision/graphics/render_table.cpp


diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index c3111be6769..291b9f5e620 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -143,7 +143,7 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 	  for (int16 y = 0; y < srcBuf->h; ++y) {
 		  uint32 sourceOffset = y * _numColumns;
 		  for (int16 x = 0; x < srcBuf->w; ++x) {
-			  index = sourceOffset + x;
+		    index = sourceOffset + x;
 			  _curP = _internalBuffer[index];
 			  srcIndexYT = y + _curP.Src.top;
 			  srcIndexYB = y + _curP.Src.bottom;
@@ -158,6 +158,11 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
         bF = round(_curP.fTL*bTL + _curP.fTR*bTR + _curP.fBL*bBL + _curP.fBR*bBR);
         destBuffer[destOffset] = mergeColor(rF,gF,bF);
 		    destOffset++;
+        if(Common::Point(x,y)==testPixel) {
+          debug(2,"\tMutated test pixel %d, %d", x, y);
+          debug(2,"\tfX: %f, fY: %f", _curP.fX, _curP.fY);
+          debug(2,"\tYT: %d, YB: %d, XL: %d XR: %d", srcIndexYT, srcIndexYB, srcIndexXL, srcIndexXR);
+        } 
       }
     }
 	}
@@ -201,11 +206,11 @@ void RenderTable::generateRenderTable() {
 
 void RenderTable::generatePanoramaLookupTable() {
   debug(1,"Generating panorama lookup table.");
-	uint halfRows = ceil(_numRows/2);
-	uint halfColumns = ceil(_numColumns/2);
-	float halfWidth = (float)_numColumns / 2.0f;
-	float halfHeight = (float)_numRows / 2.0f;
-	float cylinderRadius = halfHeight / tan(_panoramaOptions.verticalFOV);
+	uint halfRows = floor((_numRows-1)/2);
+	uint halfColumns = floor((_numColumns-1)/2);
+	float halfWidth = (float)_numColumns / 2.0f - 0.5f; //Centre axis to midpoint of outermost pixel
+	float halfHeight = (float)_numRows / 2.0f - 0.5f; //Centre axis to midpoint of outermost pixel
+	float cylinderRadius = (halfHeight + 0.5f) / tan(_panoramaOptions.verticalFOV);
 	float xOffset = 0.0f;
 	float yOffset = 0.0f;
 	
@@ -215,10 +220,9 @@ void RenderTable::generatePanoramaLookupTable() {
 	//Transformation is both horizontally and vertically symmetrical about the camera axis,
 	//We can thus save on trigonometric calculations by computing one quarter of the transformation matrix and then mirroring it in both X & Y
 	//TODO - find & fix cause of vertial "seam" in Nemesis.
-	for (uint x = 0; x < halfColumns; ++x) {
-		// Add an offset of 0.01 to overcome zero tan/atan issue (vertical line on half of screen)
-		// Alpha represents the horizontal angle between the viewer at the center of a cylinder and x
-		float alpha = atan(((float)x - halfWidth + 0.01f) / cylinderRadius);
+	for (uint x = 0; x <= halfColumns; ++x) {
+		// Alpha represents the horizontal angle between the viewer at the center of a cylinder and the centre of pixel index (x,y)
+		float alpha = atan(((float)x - halfWidth) / cylinderRadius);
 
 		// To get x in cylinder coordinates, we just need to calculate the arc length
 		// We also scale it by _panoramaOptions.linearScale
@@ -229,7 +233,7 @@ void RenderTable::generatePanoramaLookupTable() {
 		uint32 rowIndexT = 0;
 		uint32 rowIndexB = _numColumns * (_numRows - 1);
 
-		for (uint y = 0; y < halfRows; ++y) {
+		for (uint y = 0; y <= halfRows; ++y) {
 			// To calculate y in cylinder coordinates, we can do similar triangles comparison,
 			// comparing the triangle from the center to the screen and from the center to the edge of the cylinder
 			float yInCylinderCoords = halfHeight + ((float)y - halfHeight) * cosAlpha;


Commit: 1b6891c338f04bdb06100061f522c28dbab109bb
    https://github.com/scummvm/scummvm/commit/1b6891c338f04bdb06100061f522c28dbab109bb
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:57+02:00

Commit Message:
ZVISION: Clean up framerate limiter code a bit.

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/text/subtitle_manager.cpp
    engines/zvision/zvision.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 5ece97df656..77b6c4d7caf 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -37,6 +37,7 @@
 #include "image/tga.h"
 
 #include "graphics/blit.h"
+#include "graphics/framelimiter.h"
 
 //FOR BUG TEST ONLY
 #include "common/debug.h"
diff --git a/engines/zvision/text/subtitle_manager.cpp b/engines/zvision/text/subtitle_manager.cpp
index a648d04277e..829e56b1ca7 100644
--- a/engines/zvision/text/subtitle_manager.cpp
+++ b/engines/zvision/text/subtitle_manager.cpp
@@ -216,9 +216,9 @@ void SubtitleManager::delayedMessage(const Common::String &str, uint16 milsecs)
 		}
 	  _renderManager->renderSceneToScreen(true);
 		if (_doubleFPS)
-			_system->delayMillis(33);
+			_system->delayMillis(17);
 		else
-			_system->delayMillis(66);
+			_system->delayMillis(33);
 	}
 	destroy(msgid);
 	_engine->startClock();
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index ef8698fa41e..74a9341e681 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -200,6 +200,8 @@ void ZVision::initialize() {
 	
 	//Graphics
 	_widescreen = ConfMan.getBool("widescreen");
+	_doubleFPS = ConfMan.getBool("doublefps");
+	_desiredFrameTime = _doubleFPS ? 17 : 33;
 	
   //Keymaps
 	Common::Keymapper *keymapper = _system->getEventManager()->getKeymapper();
@@ -253,7 +255,6 @@ void ZVision::initialize() {
 
 	// Create debugger console. It requires GFX to be initialized
 	setDebugger(new Console(this));
-	_doubleFPS = ConfMan.getBool("doublefps");
 
 	// Initialize FPS timer callback
 	getTimerManager()->installTimerProc(&fpsTimerCallback, 1000000, this, "zvisionFPS");
@@ -359,6 +360,8 @@ Common::Error ZVision::run() {
 		_subtitleManager->process(deltaTime);
 	  debug(5,"Render");
 		// Render the backBuffer to the screen
+		//TODO - figure out _doubleFPS effect, apply framerate limiter to get smoother rendering of panorama
+		//Current framerate limiter implementation is buggy, delay is applied based on previous frame time
 		_renderManager->prepareBackground();
 		if(_renderManager->renderSceneToScreen())
 			_renderedFrameCount++;
@@ -369,8 +372,6 @@ Common::Error ZVision::run() {
 		int delay = _desiredFrameTime - int32(_system->getMillis() - currentTime);
 		// Ensure non-negative
 		delay = delay < 0 ? 0 : delay;
-		if (_doubleFPS)
-			delay >>= 1;
 		_system->delayMillis(delay);
 	}
 	return Common::kNoError;
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index 44a96318eb7..0152ebddbc8 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -165,7 +165,7 @@ public:
 private:
 	const ZVisionGameDescription *_gameDescription;
 
-	const int _desiredFrameTime;
+	int _desiredFrameTime;
 
 	// We need random numbers
 	Common::RandomSource *_rnd;


Commit: 536737ae9f4d796211f355fc7d1f690cbed95379
    https://github.com/scummvm/scummvm/commit/536737ae9f4d796211f355fc7d1f690cbed95379
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:57+02:00

Commit Message:
ZVISION: Overhaul of render table generation code.
High quality bilinear filtering now works for both pan and tilt.
Code redundancy eliminated via use of lambdas.

Changed paths:
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h


diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index 291b9f5e620..04b34198591 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -41,6 +41,10 @@ RenderTable::RenderTable(ZVision *engine, uint numColumns, uint numRows, const G
 	_internalBuffer = new FilterPixel[numRows * numColumns];
 	memset(&_panoramaOptions, 0, sizeof(_panoramaOptions));
 	memset(&_tiltOptions, 0, sizeof(_tiltOptions));
+	halfRows = floor((_numRows-1)/2);
+	halfColumns = floor((_numColumns-1)/2);
+	halfWidth = (float)_numColumns / 2.0f - 0.5f;
+	halfHeight = (float)_numRows / 2.0f - 0.5f;
 }
 
 RenderTable::~RenderTable() {
@@ -187,14 +191,11 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 void RenderTable::generateRenderTable() {
 	switch (_renderState) {
 	  case RenderTable::PANORAMA: {
-      uint32 generationTime = _system->getMillis();
-		  generatePanoramaLookupTable();
-      generationTime = _system->getMillis() - generationTime;		  
-      debug(1,"\tRender table generation time %dms, %s quality", generationTime, _engine->getScriptManager()->getStateValue(StateKey_HighQuality) ? "high" : "low");
+      generateLookupTable(false);
 		  break;
 	  }
 	  case RenderTable::TILT:
-		  generateTiltLookupTable();
+	    generateLookupTable(true);
 		  break;
 	  case RenderTable::FLAT:
 		  // Intentionally left empty
@@ -204,127 +205,89 @@ void RenderTable::generateRenderTable() {
 	}
 }
 
-void RenderTable::generatePanoramaLookupTable() {
-  debug(1,"Generating panorama lookup table.");
-	uint halfRows = floor((_numRows-1)/2);
-	uint halfColumns = floor((_numColumns-1)/2);
-	float halfWidth = (float)_numColumns / 2.0f - 0.5f; //Centre axis to midpoint of outermost pixel
-	float halfHeight = (float)_numRows / 2.0f - 0.5f; //Centre axis to midpoint of outermost pixel
-	float cylinderRadius = (halfHeight + 0.5f) / tan(_panoramaOptions.verticalFOV);
-	float xOffset = 0.0f;
-	float yOffset = 0.0f;
-	
+void RenderTable::generateLookupTable(bool tilt) {
+  debug(1,"Generating %s lookup table.", tilt ? "tilt" : "panorama");
 	debug(1,"halfWidth %f, halfHeight %f", halfWidth, halfHeight);
 	debug(1,"halfRows %d, halfColumns %d", halfRows, halfColumns);
-	
-	//Transformation is both horizontally and vertically symmetrical about the camera axis,
-	//We can thus save on trigonometric calculations by computing one quarter of the transformation matrix and then mirroring it in both X & Y
-	//TODO - find & fix cause of vertial "seam" in Nemesis.
-	for (uint x = 0; x <= halfColumns; ++x) {
-		// Alpha represents the horizontal angle between the viewer at the center of a cylinder and the centre of pixel index (x,y)
-		float alpha = atan(((float)x - halfWidth) / cylinderRadius);
-
-		// To get x in cylinder coordinates, we just need to calculate the arc length
-		// We also scale it by _panoramaOptions.linearScale
-		float xInCylinderCoords = (cylinderRadius * _panoramaOptions.linearScale * alpha) + halfWidth;
-		float cosAlpha = cos(alpha);
-		uint32 columnIndexL = x;
-		uint32 columnIndexR = (_numColumns - 1) - x;
-		uint32 rowIndexT = 0;
-		uint32 rowIndexB = _numColumns * (_numRows - 1);
-
-		for (uint y = 0; y <= halfRows; ++y) {
-			// To calculate y in cylinder coordinates, we can do similar triangles comparison,
-			// comparing the triangle from the center to the screen and from the center to the edge of the cylinder
-			float yInCylinderCoords = halfHeight + ((float)y - halfHeight) * cosAlpha;
-			
-			uint32 indexTL = rowIndexT + columnIndexL;
-			uint32 indexBL = rowIndexB + columnIndexL;
-			uint32 indexTR = rowIndexT + columnIndexR;
-			uint32 indexBR = rowIndexB + columnIndexR;
-			
-			xOffset = xInCylinderCoords - x; 
-      yOffset = yInCylinderCoords - y;
-      
-      bool _printDebug = (Common::Point(x,y)==testPixel);
-      if(_printDebug) {
-        debug(2,"\tGenerating test pixel %d, %d", x, y);
-        debug(2,"\tCylinder coordinates %f, %f", xInCylinderCoords, yInCylinderCoords);
-        debug(2,"\tOffsets %f,%f", xOffset, yOffset);
-      } 
-			// Only store the (x,y) offsets instead of the absolute positions
-			_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality, _printDebug);
-			//Store mirrored offset values
-			_internalBuffer[indexBL] = _internalBuffer[indexTL];
-			_internalBuffer[indexBL].flipV();
-			_internalBuffer[indexTR] = _internalBuffer[indexTL];
-			_internalBuffer[indexTR].flipH();
-			_internalBuffer[indexBR] = _internalBuffer[indexBL];
-			_internalBuffer[indexBR].flipH();
-			//Increment indices
-			rowIndexT += _numColumns;
-			rowIndexB -= _numColumns;
-		}
-	}
-	debug(1,"Render table generated, %s quality", _highQuality ? "high" : "low");
-}
-
-void RenderTable::generateTiltLookupTable() {
-	uint halfRows = ceil(_numRows/2);
-	uint halfColumns = ceil(_numColumns/2);
-	float halfWidth = (float)_numColumns / 2.0f;
-	float halfHeight = (float)_numRows / 2.0f;
-	float cylinderRadius = halfWidth / tan(_tiltOptions.verticalFOV);
-	float xOffset = 0.0f;
-	float yOffset = 0.0f;
-	_tiltOptions.gap = cylinderRadius * atan2((float)(halfHeight / cylinderRadius), 1.0f) * _tiltOptions.linearScale;
-	
-	//Transformation is both horizontally and vertically symmetrical about the camera axis,
-	//We can thus save on trigonometric calculations by computing one quarter of the transformation matrix and then mirroring it in both X & Y
-	for (uint y = 0; y < halfRows; ++y) {
-		// Add an offset of 0.01 to overcome zero tan/atan issue (horizontal line on half of screen)
-		// Alpha represents the vertical angle between the viewer at the center of a cylinder and y
-		float alpha = atan(((float)y - halfHeight + 0.01f) / cylinderRadius);
-
-		// To get y in cylinder coordinates, we just need to calculate the arc length
-		// We also scale it by _tiltOptions.linearScale
-		int32 yInCylinderCoords = int32(round((cylinderRadius * _tiltOptions.linearScale * alpha) + halfHeight));
-
-		float cosAlpha = cos(alpha);
-		uint32 columnIndexTL = y * _numColumns;
-		uint32 columnIndexBL = (_numRows-(y+1)) * _numColumns;
-		uint32 columnIndexTR = columnIndexTL + (_numColumns - 1);
-		uint32 columnIndexBR = columnIndexBL + (_numColumns - 1);
-
-  //TODO - all four pixel values are always the same; find out why & fix.
-
-		for (uint x = 0; x < halfColumns; ++x) {
-			// To calculate x in cylinder coordinates, we can do similar triangles comparison,
-			// comparing the triangle from the center to the screen and from the center to the edge of the cylinder
-			int32 xInCylinderCoords = int32(round(halfWidth + ((float)x - halfWidth) * cosAlpha));
-
-			uint32 indexTL = columnIndexTL + x;
-			uint32 indexBL = columnIndexBL + x;
-			uint32 indexTR = columnIndexTR - x;
-			uint32 indexBR = columnIndexBR - x;
-			
-			xOffset = xInCylinderCoords - x;
-      yOffset = yInCylinderCoords - y;
-      
-      bool _printDebug = (Common::Point(x,y)==testPixel);
-      if(_printDebug) {
-        debug(2,"\tGenerating test pixel %d, %d", x, y);
-        debug(2,"\tCylinder coordinates %d, %d", xInCylinderCoords, yInCylinderCoords);
-        debug(2,"\tOffsets %f,%f", xOffset, yOffset);
+  uint32 generationTime = _system->getMillis();
+	float alpha, cosAlpha, polarCoordInCylinderCoords, linearCoordInCylinderCoords, cylinderRadius, xOffset, yOffset;
+	uint32 indexTL, indexBL, indexTR, indexBR;
+	uint x=0;
+	uint y=0;
+	auto outerLoop = [&](uint &polarCoord, float &halfPolarSize, float &scale) {
+    //polarCoord is the coordinate of the working window pixel parallel to the direction of camera rotation
+    //halfPolarSize is the distance from the central axis to the outermost working window pixel in the direction of camera rotation
+		//alpha represents the angle in the direction of camera rotation between the view axis and the centre of a pixel at the given polar coordinate
+		alpha = atan(((float)polarCoord - halfPolarSize) / cylinderRadius);
+		// To map the polar coordinate to the cylinder surface coordinates, we just need to calculate the arc length
+		// We also scale it by linearScale
+		polarCoordInCylinderCoords = (cylinderRadius * scale * alpha) + halfPolarSize;
+		cosAlpha = cos(alpha);
+  };	  
+  auto innerLoop = [&](uint &polarCoord, uint &linearCoord, float &halfLinearSize,  float &polarOffset, float &linearOffset) {
+		// To calculate linear coordinate in cylinder coordinates, we can do similar triangles comparison,
+		// comparing the triangle from the center to the screen and from the center to the edge of the cylinder
+		linearCoordInCylinderCoords = halfLinearSize + ((float)linearCoord - halfLinearSize) * cosAlpha;
+		linearOffset = linearCoordInCylinderCoords - linearCoord;
+    polarOffset = polarCoordInCylinderCoords - polarCoord;
+    bool _printDebug = (Common::Point(x,y)==testPixel);
+    if(_printDebug) {
+      debug(2,"\tGenerating test pixel %d, %d", x, y);
+      debug(2,"\tOffsets %f,%f", xOffset, yOffset);
+    } 
+		// Only store the (x,y) offsets instead of the absolute positions
+		_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality, _printDebug);
+    //Transformation is both horizontally and vertically symmetrical about the camera axis,
+    //We can thus save on trigonometric calculations by computing one quarter of the transformation matrix and then mirroring it in both X & Y:
+		_internalBuffer[indexBL] = _internalBuffer[indexTL];
+		_internalBuffer[indexBL].flipV();
+		_internalBuffer[indexTR] = _internalBuffer[indexTL];
+		_internalBuffer[indexTR].flipH();
+		_internalBuffer[indexBR] = _internalBuffer[indexBL];
+		_internalBuffer[indexBR].flipH();
+  };
+  if(tilt) {
+    uint32 columnIndexTL, columnIndexBL, columnIndexTR, columnIndexBR;
+	  cylinderRadius = (halfWidth + 0.5f) / tan(_tiltOptions.verticalFOV);
+	  _tiltOptions.gap = cylinderRadius * atan2((float)(halfHeight / cylinderRadius), 1.0f) * _tiltOptions.linearScale;
+	  for (y = 0; y <= halfRows; ++y) {
+	    outerLoop(y, halfHeight, _tiltOptions.linearScale);
+		  columnIndexTL = y * _numColumns;
+		  columnIndexBL = (_numRows-(y+1)) * _numColumns;
+		  columnIndexTR = columnIndexTL + (_numColumns - 1);
+		  columnIndexBR = columnIndexBL + (_numColumns - 1);
+	    for (x = 0; x <= halfColumns; ++x) {
+			  indexTL = columnIndexTL + x;
+			  indexBL = columnIndexBL + x;
+			  indexTR = columnIndexTR - x;
+			  indexBR = columnIndexBR - x;
+	      innerLoop(y, x, halfWidth, yOffset, xOffset);
       }
-			// Only store the (x,y) offsets instead of the absolute positions
-			_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality, _printDebug);			
-			//Store mirrored offset values
-			_internalBuffer[indexBL] = FilterPixel(xOffset, -yOffset, _highQuality);
-			_internalBuffer[indexTR] = FilterPixel(-xOffset, yOffset, _highQuality);
-			_internalBuffer[indexBR] = FilterPixel(-xOffset, -yOffset, _highQuality);
-		}
+    }
 	}
+  else {
+    uint32 rowIndexT, rowIndexB, columnIndexL, columnIndexR;
+    cylinderRadius = (halfHeight + 0.5f) / tan(_panoramaOptions.verticalFOV);
+	  for (x = 0; x <= halfColumns; ++x) {
+  		columnIndexL = x;
+		  columnIndexR = (_numColumns - 1) - x;
+		  rowIndexT = 0;
+		  rowIndexB = _numColumns * (_numRows - 1);
+	    outerLoop(x, halfWidth, _panoramaOptions.linearScale);
+		  for (y = 0; y <= halfRows; ++y) {
+		    indexTL = rowIndexT + columnIndexL;
+		    indexBL = rowIndexB + columnIndexL;
+		    indexTR = rowIndexT + columnIndexR;
+		    indexBR = rowIndexB + columnIndexR;
+		    innerLoop(x, y, halfHeight, xOffset, yOffset);
+		    rowIndexT += _numColumns;
+		    rowIndexB -= _numColumns;
+	    }
+	  }
+  }
+  generationTime = _system->getMillis() - generationTime;		  
+	debug(1,"Render table generated, %s quality", _highQuality ? "high" : "low");
+  debug(1,"\tRender table generation time %dms, %s quality", generationTime, _engine->getScriptManager()->getStateValue(StateKey_HighQuality) ? "high" : "low");
 }
 
 void RenderTable::setPanoramaFoV(float fov) {
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index f7e30ab85af..4e0446ff0a0 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -83,7 +83,7 @@ public:
 	RenderTable(ZVision *engine, uint numRows, uint numColumns, const Graphics::PixelFormat pixelFormat);
 	~RenderTable();
 	
-	Common::Point testPixel = Common::Point(30,120);
+	Common::Point testPixel = Common::Point(255,0);
 
 public:
 	enum RenderState {
@@ -95,11 +95,11 @@ public:
 private:
 	ZVision *_engine;
 	OSystem *_system;
-	uint _numColumns, _numRows; //Working area width, height
+	uint _numRows, _numColumns, halfRows, halfColumns; //Working area width, height; half width, half height, in whole pixels
+	float halfWidth, halfHeight;  //Centre axis to midpoint of outermost pixel
   FilterPixel *_internalBuffer;
 	RenderState _renderState;
 	bool _highQuality = false;
-	const uint8 filterPasses = 2;
 	const Graphics::PixelFormat _pixelFormat;
 	
   inline void splitColor(uint16 &color, uint32 &r, uint32 &g, uint32 &b) {
@@ -172,6 +172,7 @@ public:
 	float getLinscale();
 
 private:
+  void generateLookupTable(bool tilt = false);
 	void generatePanoramaLookupTable();
 //	Common::Point generatePanoramaLookupPoint();
 	void generateTiltLookupTable();


Commit: 7f94d1186da90a037f73f3299728547cb12058b8
    https://github.com/scummvm/scummvm/commit/7f94d1186da90a037f73f3299728547cb12058b8
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:57+02:00

Commit Message:
ZVISION: Adapted render manager to use standard Gsystem frame limiter.

# Conflicts:
#	engines/zvision/zvision.h

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/zvision.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 77b6c4d7caf..29a083fbe04 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -37,7 +37,6 @@
 #include "image/tga.h"
 
 #include "graphics/blit.h"
-#include "graphics/framelimiter.h"
 
 //FOR BUG TEST ONLY
 #include "common/debug.h"
@@ -59,7 +58,8 @@ RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const G
 	  _backgroundOffset(0),
 	  _renderTable(engine, _layout.workingArea.width(), _layout.workingArea.height(), pixelFormat),
 	  _doubleFPS(doubleFPS),
-	  _widescreen(widescreen) {
+	  _widescreen(widescreen),
+	  frameLimiter(engine->_system, doubleFPS ? 60 : 30) {
 	debug(1,"creating render manager");
   //Define graphics modes & screen subarea geometry
 	Graphics::ModeList modes;
@@ -228,16 +228,23 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
 	}
 	_menuManagedSurface.transBlitFrom(_menuSurface, -1);
   _textManagedSurface.transBlitFrom(_textSurface, -1);
-  if(_engine->canRender() || immediate) {
+  if(immediate) {
+    frameLimiter.startFrame();
     _screen.update();
-    debug(10,"~renderSceneToScreen");
+    debug(10,"~renderSceneToScreen, immediate");
+    return true;
+  }
+  else if (_engine->canRender()) {
+    frameLimiter.delayBeforeSwap();
+    frameLimiter.startFrame();
+    _screen.update();
+    debug(10,"~renderSceneToScreen, frame limited");
     return true;
   }
   else {
     debug(4,"Skipping screen update; engine forbids rendering at this time.");
-    debug(10,"~renderSceneToScreen");
     return false;
-  }
+  };
 }
 
 Graphics::ManagedSurface &RenderManager::getVidSurface(Common::Rect &dstRect) {
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index fd84865906f..749679fb233 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -28,14 +28,15 @@
 #include "common/hashmap.h"
 
 #include "graphics/surface.h"
-
 #include "graphics/managed_surface.h"
 #include "graphics/screen.h"
+#include "graphics/framelimiter.h"
 
 #include "zvision/graphics/graphics_effect.h"
 
 #include "zvision/graphics/render_table.h"
 
+
 class OSystem;
 
 namespace Common {
@@ -61,6 +62,7 @@ private:
 	const Graphics::PixelFormat _pixelFormat;
 	const ScreenLayout _layout;
 	bool _hiRes = false;
+	Graphics::FrameLimiter frameLimiter;
 
 	/**
 	 * A Rectangle representing the screen/window resolution.
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index 74a9341e681..fd3da86c8a7 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -91,7 +91,6 @@ ZVision::ZVision(OSystem *syst, const ZVisionGameDescription *gameDesc)
 	  _gameDescription(gameDesc),
 	  _resourcePixelFormat(2, 5, 5, 5, 0, 10, 5, 0, 0), /* RGB 555 */
 	  _screenPixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0), /* RGB 565 */
-	  _desiredFrameTime(33), /* ~30 fps */
 	  _clock(_system),
 	  _scriptManager(nullptr),
 	  _renderManager(nullptr),
@@ -201,7 +200,6 @@ void ZVision::initialize() {
 	//Graphics
 	_widescreen = ConfMan.getBool("widescreen");
 	_doubleFPS = ConfMan.getBool("doublefps");
-	_desiredFrameTime = _doubleFPS ? 17 : 33;
 	
   //Keymaps
 	Common::Keymapper *keymapper = _system->getEventManager()->getKeymapper();
@@ -342,7 +340,7 @@ Common::Error ZVision::run() {
 	  debug(5,"Timers");
 	  //Timers
 		_clock.update();
-		uint32 currentTime = _clock.getLastMeasuredTime();
+		//uint32 currentTime = _clock.getLastMeasuredTime();
 		uint32 deltaTime = _clock.getDeltaTime();
 	  debug(5,"Logic");
     //Process game logic & update backbuffers as necessary
@@ -360,19 +358,11 @@ Common::Error ZVision::run() {
 		_subtitleManager->process(deltaTime);
 	  debug(5,"Render");
 		// Render the backBuffer to the screen
-		//TODO - figure out _doubleFPS effect, apply framerate limiter to get smoother rendering of panorama
-		//Current framerate limiter implementation is buggy, delay is applied based on previous frame time
 		_renderManager->prepareBackground();
 		if(_renderManager->renderSceneToScreen())
 			_renderedFrameCount++;
 		else
 			_frameRenderDelay--;
-	  debug(5,"Frame delay");
-		// Calculate the frame delay based off a desired frame time
-		int delay = _desiredFrameTime - int32(_system->getMillis() - currentTime);
-		// Ensure non-negative
-		delay = delay < 0 ? 0 : delay;
-		_system->delayMillis(delay);
 	}
 	return Common::kNoError;
 }
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index 0152ebddbc8..649aa7cb391 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -164,9 +164,7 @@ public:
 
 private:
 	const ZVisionGameDescription *_gameDescription;
-
-	int _desiredFrameTime;
-
+	
 	// We need random numbers
 	Common::RandomSource *_rnd;
 


Commit: 860e56aa24b44e597ac1c56bb2feaa516bc696a3
    https://github.com/scummvm/scummvm/commit/860e56aa24b44e597ac1c56bb2feaa516bc696a3
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:57+02:00

Commit Message:
ZVISION: Improve efficiency of panorama mutation code.  Increases FPS.
Bugs remaining: stuttering of panorama.
Had suspected mutation code was to blame, but this seems not to be the case.

# Conflicts:
#	engines/zvision/scripting/script_manager.cpp

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h
    engines/zvision/zvision.cpp


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 29a083fbe04..ebfc251a1bc 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -173,13 +173,15 @@ void RenderManager::initialize(bool hiRes) {
 }
 
 bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
-  debug(10,"renderSceneToScreen");
+  debug(5,"\nrenderSceneToScreen");
+  uint32 startTime = _system->getMillis();
   if(!overlayOnly) {
 	  Graphics::Surface *out = &_warpedSceneSurface;
 	  Graphics::Surface *in = &_backgroundSurface;
 	  Common::Rect outWndDirtyRect;
 	  //Apply graphical effects to temporary effects buffer and/or directly to current background image, as appropriate
 	  if (!_effects.empty()) {
+	    debug(5,"Rendering effects");
 		  bool copied = false;
 		  const Common::Rect windowRect(_workingArea.width(), _workingArea.height());
 		  for (EffectsList::iterator it = _effects.begin(); it != _effects.end(); it++) {
@@ -208,11 +210,13 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
 					  _backgroundSurfaceDirtyRect.extend(screenSpaceLocation);
 			  }
 		  }
+	    debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
 	  }
     //Apply panorama/tilt warp to background image
 	  switch(_renderTable.getRenderState()) {
 	    case RenderTable::PANORAMA:
 	    case RenderTable::TILT:
+	      debug(5,"Rendering panorama");
 		    if (!_backgroundSurfaceDirtyRect.isEmpty()) {
 			    _renderTable.mutateImage(&_warpedSceneSurface, in, _engine->getScriptManager()->getStateValue(StateKey_HighQuality));
 			    out = &_warpedSceneSurface;
@@ -223,21 +227,32 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
 		    out = in;
 		    outWndDirtyRect = _backgroundSurfaceDirtyRect;
 		    break;
+      debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
     }
+    debug(5,"Rendering working area");
 	  _workingManagedSurface.simpleBlitFrom(*out); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
+    debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
 	}
+  debug(5,"Rendering menu");
 	_menuManagedSurface.transBlitFrom(_menuSurface, -1);
+  debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
+  debug(5,"Rendering text");
   _textManagedSurface.transBlitFrom(_textSurface, -1);
+  debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
   if(immediate) {
     frameLimiter.startFrame();
+    debug(5,"Updating screen");
     _screen.update();
+    debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
     debug(10,"~renderSceneToScreen, immediate");
     return true;
   }
   else if (_engine->canRender()) {
     frameLimiter.delayBeforeSwap();
     frameLimiter.startFrame();
+    debug(5,"Updating screen");
     _screen.update();
+    debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
     debug(10,"~renderSceneToScreen, frame limited");
     return true;
   }
@@ -716,7 +731,7 @@ Graphics::Surface *RenderManager::loadImage(const Common::Path &file, bool trans
 }
 
 void RenderManager::prepareBackground() {
-  debug(11,"prepareBackground()");
+  debug(5,"prepareBackground()");
 	_backgroundDirtyRect.clip(_backgroundWidth, _backgroundHeight);
   switch(_renderTable.getRenderState()) {
 	  case RenderTable::PANORAMA: {
diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index 04b34198591..635889a1c19 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -80,7 +80,7 @@ const Common::Point RenderTable::convertWarpedCoordToFlatCoord(const Common::Poi
 		int16 y = CLIP<int16>(point.y, 0, (int16)_numRows);
 		return Common::Point(x, y);
 	}
-	uint32 index = point.y * _numColumns + point.x;
+	index = point.y * _numColumns + point.x;
 	Common::Point newPoint(point);
 	newPoint.x += (_internalBuffer[index].xDir ? _internalBuffer[index].Src.right : _internalBuffer[index].Src.left);
 	newPoint.y += (_internalBuffer[index].yDir ? _internalBuffer[index].Src.bottom : _internalBuffer[index].Src.top);
@@ -125,11 +125,7 @@ void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 d
 //*/
 
 void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf, bool highQuality) {
-	uint32 destOffset = 0;
-  uint32 srcIndexXL = 0;
-  uint32 srcIndexXR = 0;
-  uint32 srcIndexYT = 0;
-  uint32 srcIndexYB = 0;
+	destOffset = 0;
 	uint16 *sourceBuffer = (uint16 *)srcBuf->getPixels();
 	uint16 *destBuffer = (uint16 *)dstBuf->getPixels();
 	if(highQuality != _highQuality) {
@@ -140,15 +136,10 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
   if(_highQuality) {
     //Apply bilinear interpolation
 	  FilterPixel _curP;
-	  uint32 index;
-	  uint32 rTL,rTR,rBL,rBR,rF;
-	  uint32 gTL,gTR,gBL,gBR,gF;
-	  uint32 bTL,bTR,bBL,bBR,bF;
 	  for (int16 y = 0; y < srcBuf->h; ++y) {
-		  uint32 sourceOffset = y * _numColumns;
+		  sourceOffset = y * _numColumns;
 		  for (int16 x = 0; x < srcBuf->w; ++x) {
-		    index = sourceOffset + x;
-			  _curP = _internalBuffer[index];
+			  _curP = _internalBuffer[sourceOffset + x];
 			  srcIndexYT = y + _curP.Src.top;
 			  srcIndexYB = y + _curP.Src.bottom;
 			  srcIndexXL = x + _curP.Src.left;
@@ -156,26 +147,28 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
         splitColor(sourceBuffer[srcIndexYT * _numColumns + srcIndexXL], rTL, gTL, bTL);
         splitColor(sourceBuffer[srcIndexYT * _numColumns + srcIndexXR], rTR, gTR, bTR);
         splitColor(sourceBuffer[srcIndexYB * _numColumns + srcIndexXL], rBL, gBL, bBL);
-        splitColor(sourceBuffer[srcIndexYB * _numColumns + srcIndexXR], rBR, gBR, bBR);      
-        rF = round(_curP.fTL*rTL + _curP.fTR*rTR + _curP.fBL*rBL + _curP.fBR*rBR);
-        gF = round(_curP.fTL*gTL + _curP.fTR*gTR + _curP.fBL*gBL + _curP.fBR*gBR);
-        bF = round(_curP.fTL*bTL + _curP.fTR*bTR + _curP.fBL*bBL + _curP.fBR*bBR);
+        splitColor(sourceBuffer[srcIndexYB * _numColumns + srcIndexXR], rBR, gBR, bBR);
+        rF = _curP.fTL*rTL + _curP.fTR*rTR + _curP.fBL*rBL + _curP.fBR*rBR;
+        gF = _curP.fTL*gTL + _curP.fTR*gTR + _curP.fBL*gBL + _curP.fBR*gBR;
+        bF = _curP.fTL*bTL + _curP.fTR*bTR + _curP.fBL*bBL + _curP.fBR*bBR;
         destBuffer[destOffset] = mergeColor(rF,gF,bF);
 		    destOffset++;
+	      /*/
         if(Common::Point(x,y)==testPixel) {
           debug(2,"\tMutated test pixel %d, %d", x, y);
           debug(2,"\tfX: %f, fY: %f", _curP.fX, _curP.fY);
           debug(2,"\tYT: %d, YB: %d, XL: %d XR: %d", srcIndexYT, srcIndexYB, srcIndexXL, srcIndexXR);
         } 
+        //*/
       }
     }
 	}
   else {
     //Apply nearest-neighbour interpolation
 	  for (int16 y = 0; y < srcBuf->h; ++y) {
-		  uint32 sourceOffset = y * _numColumns;
+		  sourceOffset = y * _numColumns;
 		  for (int16 x = 0; x < srcBuf->w; ++x) {
-			  uint32 index = sourceOffset + x;
+			  index = sourceOffset + x;
 			  // RenderTable only stores offsets from the original coordinates
     		srcIndexXL = x + (_internalBuffer[index].xDir ? _internalBuffer[index].Src.right : _internalBuffer[index].Src.left);			  
 			  srcIndexYT = y + (_internalBuffer[index].yDir ? _internalBuffer[index].Src.bottom : _internalBuffer[index].Src.top);
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index 4e0446ff0a0..079791bda8d 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -102,6 +102,13 @@ private:
 	bool _highQuality = false;
 	const Graphics::PixelFormat _pixelFormat;
 	
+	uint32 index;
+  uint32 sourceOffset, destOffset;
+  uint32 srcIndexXL, srcIndexXR, srcIndexYT, srcIndexYB;
+  uint32 rTL,rTR,rBL,rBR,rF;
+  uint32 gTL,gTR,gBL,gBR,gF;
+  uint32 bTL,bTR,bBL,bBR,bF;
+	
   inline void splitColor(uint16 &color, uint32 &r, uint32 &g, uint32 &b) {
     //NB Left & right shifting unnecessary for interpolating & recombining, so not bothering in order to save cycles
     r = color & 0x001f;
@@ -109,7 +116,8 @@ private:
     b = color & 0x7c00;
   };
   inline uint16 mergeColor(uint32 &r, uint32 &g, uint32 &b) const {
-    return (r & 0x001f) | (g & 0x03e0) | (b & 0x7c00);
+    //NB Red uses the lowest bits in RGB555 and so doesn't need its fractional bits masked away after averaging
+    return r | (g & 0x03e0) | (b & 0x7c00);
   };
 
 
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index fd3da86c8a7..4bbdc96e222 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -337,28 +337,28 @@ Common::Error ZVision::run() {
 
 	// Main loop
 	while (!shouldQuit()) {
+	  debug(5,"\nInitiating new game cycle");
 	  debug(5,"Timers");
 	  //Timers
 		_clock.update();
-		//uint32 currentTime = _clock.getLastMeasuredTime();
-		uint32 deltaTime = _clock.getDeltaTime();
+		uint32 deltaTime = _clock.getDeltaTime();		
 	  debug(5,"Logic");
-    //Process game logic & update backbuffers as necessary
+    //Process game logic & update backbuffers as necessary   
     debug(5,"Cursor");
-		_cursorManager->setItemID(_scriptManager->getStateValue(StateKey_InventoryItem));
+		_cursorManager->setItemID(_scriptManager->getStateValue(StateKey_InventoryItem));	
     debug(5,"Events");
-		processEvents();  //NB rotateTo or playVideo event will pause clock & call renderSceneToScreen() directly.
+		processEvents();  //NB rotateTo or playVideo event will pause clock & call renderSceneToScreen() directly.		
     debug(5,"Rotation");
-		_renderManager->updateRotation();
+		_renderManager->updateRotation();	
     debug(5,"Scripts");
-		_scriptManager->update(deltaTime);
+		_scriptManager->update(deltaTime);		
     debug(5,"Menu");
 		_menu->process(deltaTime);
     debug(5,"Subtitles");
-		_subtitleManager->process(deltaTime);
+		_subtitleManager->process(deltaTime);		
 	  debug(5,"Render");
 		// Render the backBuffer to the screen
-		_renderManager->prepareBackground();
+  	_renderManager->prepareBackground();
 		if(_renderManager->renderSceneToScreen())
 			_renderedFrameCount++;
 		else


Commit: 52f61a4b0eb210f6da5ffa6d1e2b1a3584852a8e
    https://github.com/scummvm/scummvm/commit/52f61a4b0eb210f6da5ffa6d1e2b1a3584852a8e
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:57+02:00

Commit Message:
ZVISION: Ensure Nemesis saved games don't override current panorama settings.

Changed paths:
    engines/zvision/file/save_manager.cpp


diff --git a/engines/zvision/file/save_manager.cpp b/engines/zvision/file/save_manager.cpp
index 897ba55c052..972e16c3e48 100644
--- a/engines/zvision/file/save_manager.cpp
+++ b/engines/zvision/file/save_manager.cpp
@@ -35,6 +35,8 @@
 #include "gui/message.h"
 #include "gui/saveload.h"
 
+#include "common/config-manager.h"
+
 namespace ZVision {
 
 const uint32 SaveManager::SAVEGAME_ID = MKTAG('Z', 'E', 'N', 'G');
@@ -134,25 +136,31 @@ Common::Error SaveManager::loadGame(int slot) {
 	// Update the state table values
 	scriptManager->deserialize(saveFile);
 	delete saveFile;
-	if (_engine->getGameId() == GID_NEMESIS && scriptManager->getCurrentLocation() == "tv2f") {
-		// WORKAROUND for script bug #6793: location tv2f (stairs) has two states:
-		// one at the top of the stairs, and one at the bottom. When the player
-		// goes to the bottom of the stairs, the screen changes, and hotspot
-		// 4652 (exit opposite the stairs) is enabled. However, the variable that
-		// controls the state (2408) is reset when the player goes down the stairs.
-		// Furthermore, the room's initialization script disables the stair exit
-		// control (4652). This leads to an impossible situation, where all the
-		// exit controls are disabled, and the player can't more anywhere. Thus,
-		// when loading a game in that room, we check for that impossible
-		// situation, which only occurs after the player has moved down the stairs,
-		// and fix it here by setting the correct background, and enabling the
-		// stair exit hotspot.
-		if ((scriptManager->getStateFlag(2411) & Puzzle::DISABLED) &&
-			(scriptManager->getStateFlag(2408) & Puzzle::DISABLED) &&
-			(scriptManager->getStateFlag(4652) & Puzzle::DISABLED)) {
-			_engine->getRenderManager()->setBackgroundImage("tv2fb21c.tga");
-			scriptManager->unsetStateFlag(4652, Puzzle::DISABLED);
-		}
+	if (_engine->getGameId() == GID_NEMESIS)  {
+    //Zork Nemesis has no in-game option to select panorama quality or animation options
+    //We set them here to ensure loaded games don't override current game configuration
+    scriptManager->setStateValue(StateKey_HighQuality, ConfMan.getBool("highquality"));
+    scriptManager->setStateValue(StateKey_NoTurnAnim, ConfMan.getBool("noanimwhileturning"));
+	  if(scriptManager->getCurrentLocation() == "tv2f") {
+		  // WORKAROUND for script bug #6793: location tv2f (stairs) has two states:
+		  // one at the top of the stairs, and one at the bottom. When the player
+		  // goes to the bottom of the stairs, the screen changes, and hotspot
+		  // 4652 (exit opposite the stairs) is enabled. However, the variable that
+		  // controls the state (2408) is reset when the player goes down the stairs.
+		  // Furthermore, the room's initialization script disables the stair exit
+		  // control (4652). This leads to an impossible situation, where all the
+		  // exit controls are disabled, and the player can't more anywhere. Thus,
+		  // when loading a game in that room, we check for that impossible
+		  // situation, which only occurs after the player has moved down the stairs,
+		  // and fix it here by setting the correct background, and enabling the
+		  // stair exit hotspot.
+		  if ((scriptManager->getStateFlag(2411) & Puzzle::DISABLED) &&
+			  (scriptManager->getStateFlag(2408) & Puzzle::DISABLED) &&
+			  (scriptManager->getStateFlag(4652) & Puzzle::DISABLED)) {
+			  _engine->getRenderManager()->setBackgroundImage("tv2fb21c.tga");
+			  scriptManager->unsetStateFlag(4652, Puzzle::DISABLED);
+		  }
+	  }
 	}
 	g_engine->setTotalPlayTime(header.playTime * 1000);
 	return Common::kNoError;


Commit: 346474f1e8fcd263d8ad131af4d4af8b67550d79
    https://github.com/scummvm/scummvm/commit/346474f1e8fcd263d8ad131af4d4af8b67550d79
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:57+02:00

Commit Message:
ZVISION: Code cleanup.

Changed paths:
    engines/zvision/common/scroller.cpp
    engines/zvision/core/events.cpp
    engines/zvision/graphics/render_table.cpp


diff --git a/engines/zvision/common/scroller.cpp b/engines/zvision/common/scroller.cpp
index 72160433baa..d1b6eeec0a1 100644
--- a/engines/zvision/common/scroller.cpp
+++ b/engines/zvision/common/scroller.cpp
@@ -41,12 +41,10 @@ bool LinearScroller::update(uint32 deltatime) {
     {
     int16 targetPos;
 	  float dPos=0;
-	  
 	  if (_active)
 	    targetPos = _activePos;
     else
     	targetPos = _idlePos;
-
     if (Pos != targetPos) {
       dPos = (float)((int32)deltatime * (int32)deltaPos) / _period;
       if((int16)dPos == 0) {
@@ -55,11 +53,9 @@ bool LinearScroller::update(uint32 deltatime) {
         else
           dPos = -1;
       }
-    }
-    
+    }   
     if(!_active)
       dPos = -dPos;
-    
     Pos += (int16)dPos;
     if( (dPos == 0) || ( (dPos > 0) && (Pos > targetPos) ) || ( (dPos < 0) && (Pos < targetPos) ) )
       Pos = targetPos;
diff --git a/engines/zvision/core/events.cpp b/engines/zvision/core/events.cpp
index d7eafc9d13e..9f0764bbd8a 100644
--- a/engines/zvision/core/events.cpp
+++ b/engines/zvision/core/events.cpp
@@ -289,7 +289,6 @@ void ZVision::onMouseMove(const Common::Point &pos) {
 	_menu->onMouseMove(pos);
 	Common::Point imageCoord(_renderManager->screenSpaceToImageSpace(pos));
 	Common::Rect _workingArea = _renderManager->getWorkingArea();
-
 	bool cursorWasChanged = false;
 
 	// Graph of the function governing rotation velocity:
@@ -326,70 +325,60 @@ void ZVision::onMouseMove(const Common::Point &pos) {
 	debug(6,"Mouse pos.x, %d, clipping with %d+1, %d+1", pos.x, _workingArea.left, _workingArea.right);
 	Common::Point clippedPos = pos;
 	clippedPos.x = CLIP<int16>(pos.x, _workingArea.left + 1, _workingArea.right - 1);
-
 	if (_workingArea.contains(clippedPos) && !_menu->inMenu()) {
 		cursorWasChanged = _scriptManager->onMouseMove(clippedPos, imageCoord);
-
 		RenderTable::RenderState renderState = _renderManager->getRenderTable()->getRenderState();
-		if (renderState == RenderTable::PANORAMA) {
-			if (clippedPos.x >= _workingArea.left && clippedPos.x < _workingArea.left + ROTATION_SCREEN_EDGE_OFFSET) {
-
-				int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
-				if (mspeed <= 0) {
-					mspeed = 25;
-				}
-				_mouseVelocity  = MIN(((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (clippedPos.x - _workingArea.left)) - mspeed).toInt(), -1);
-
-
-				_cursorManager->changeCursor(CursorIndex_Left);
-				cursorWasChanged = true;
-			} else if (clippedPos.x <= _workingArea.right && clippedPos.x > _workingArea.right - ROTATION_SCREEN_EDGE_OFFSET) {
-
-				int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
-				if (mspeed <= 0) {
-					mspeed = 25;
-				}
-				_mouseVelocity  = MAX((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (clippedPos.x - _workingArea.right + ROTATION_SCREEN_EDGE_OFFSET)).toInt(), 1);
-
-				_cursorManager->changeCursor(CursorIndex_Right);
-				cursorWasChanged = true;
-			} else {
-				_mouseVelocity = 0;
-			}
-		} else if (renderState == RenderTable::TILT) {
-			if (clippedPos.y >= _workingArea.top && clippedPos.y < _workingArea.top + ROTATION_SCREEN_EDGE_OFFSET) {
-
-				int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
-				if (mspeed <= 0) {
-					mspeed = 25;
-				}
-				_mouseVelocity  = MIN(((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (pos.y - _workingArea.top)) - mspeed).toInt(), -1);
-
-				_cursorManager->changeCursor(CursorIndex_UpArr);
-				cursorWasChanged = true;
-			} else if (clippedPos.y <= _workingArea.bottom && clippedPos.y > _workingArea.bottom - ROTATION_SCREEN_EDGE_OFFSET) {
-
-				int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
-				if (mspeed <= 0) {
-					mspeed = 25;
-				}
-				_mouseVelocity = MAX((Common::Rational(MAX_ROTATION_SPEED, ROTATION_SCREEN_EDGE_OFFSET) * (pos.y - _workingArea.bottom + ROTATION_SCREEN_EDGE_OFFSET)).toInt(), 1);
-
-				_cursorManager->changeCursor(CursorIndex_DownArr);
-				cursorWasChanged = true;
-			} else {
-				_mouseVelocity = 0;
-			}
-		} else {
-			_mouseVelocity = 0;
-		}
-	} else {
+		switch(renderState) {
+		  case RenderTable::PANORAMA:
+			  if (clippedPos.x >= _workingArea.left && clippedPos.x < _workingArea.left + ROTATION_SCREEN_EDGE_OFFSET) {
+				  int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
+				  if (mspeed <= 0)
+					  mspeed = 25;
+				  _mouseVelocity  = MIN(((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (clippedPos.x - _workingArea.left)) - mspeed).toInt(), -1);
+				  _cursorManager->changeCursor(CursorIndex_Left);
+				  cursorWasChanged = true;
+			  } 
+			  else if (clippedPos.x <= _workingArea.right && clippedPos.x > _workingArea.right - ROTATION_SCREEN_EDGE_OFFSET) {
+				  int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
+				  if (mspeed <= 0)
+					  mspeed = 25;
+				  _mouseVelocity  = MAX((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (clippedPos.x - _workingArea.right + ROTATION_SCREEN_EDGE_OFFSET)).toInt(), 1);
+				  _cursorManager->changeCursor(CursorIndex_Right);
+				  cursorWasChanged = true;
+			  } 
+			  else
+				  _mouseVelocity = 0;
+	      break;
+      case RenderTable::TILT:
+		    if (clippedPos.y >= _workingArea.top && clippedPos.y < _workingArea.top + ROTATION_SCREEN_EDGE_OFFSET) {
+			    int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
+			    if (mspeed <= 0)
+				    mspeed = 25;
+			    _mouseVelocity  = MIN(((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (pos.y - _workingArea.top)) - mspeed).toInt(), -1);
+			    _cursorManager->changeCursor(CursorIndex_UpArr);
+			    cursorWasChanged = true;
+		    } 
+		    else if (clippedPos.y <= _workingArea.bottom && clippedPos.y > _workingArea.bottom - ROTATION_SCREEN_EDGE_OFFSET) {
+			    int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
+			    if (mspeed <= 0)
+				    mspeed = 25;
+			    _mouseVelocity = MAX((Common::Rational(MAX_ROTATION_SPEED, ROTATION_SCREEN_EDGE_OFFSET) * (pos.y - _workingArea.bottom + ROTATION_SCREEN_EDGE_OFFSET)).toInt(), 1);
+			    _cursorManager->changeCursor(CursorIndex_DownArr);
+			    cursorWasChanged = true;
+		    } 
+		    else
+			    _mouseVelocity = 0;
+		    break;
+      case RenderTable::FLAT:
+		  default:
+			  _mouseVelocity = 0;
+		    break;
+    }
+	} 
+	else
 		_mouseVelocity = 0;
-	}
-
-	if (!cursorWasChanged) {
+	if (!cursorWasChanged)
 		_cursorManager->changeCursor(CursorIndex_Idle);
-	}
 }
 
 uint8 ZVision::getZvisionKey(Common::KeyCode scummKeyCode) {
diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index 635889a1c19..28e3bbedefc 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -178,7 +178,7 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 	  }
   }
   mutationTime = _system->getMillis() - mutationTime;
-  debug(1,"\tPanorama mutation time %dms, %s quality", mutationTime, _engine->getScriptManager()->getStateValue(StateKey_HighQuality) ? "high" : "low");
+  debug(5,"\tPanorama mutation time %dms, %s quality", mutationTime, _highQuality? "high" : "low");
 }
 
 void RenderTable::generateRenderTable() {
@@ -280,7 +280,7 @@ void RenderTable::generateLookupTable(bool tilt) {
   }
   generationTime = _system->getMillis() - generationTime;		  
 	debug(1,"Render table generated, %s quality", _highQuality ? "high" : "low");
-  debug(1,"\tRender table generation time %dms, %s quality", generationTime, _engine->getScriptManager()->getStateValue(StateKey_HighQuality) ? "high" : "low");
+  debug(1,"\tRender table generation time %dms", generationTime);
 }
 
 void RenderTable::setPanoramaFoV(float fov) {


Commit: 85140f399476bf0db10a5c05db723809b1c762a8
    https://github.com/scummvm/scummvm/commit/85140f399476bf0db10a5c05db723809b1c762a8
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:57+02:00

Commit Message:
GRAPHICS: Improve precision of FrameLimiter when operating in non-Vsync mode.
Add usage & functionality explanation comments.
Add late frame detection & other functions to return timing data.
Make some variable names more intuitive for clarity of function.

Changed paths:
    graphics/framelimiter.cpp
    graphics/framelimiter.h


diff --git a/graphics/framelimiter.cpp b/graphics/framelimiter.cpp
index 58267996471..716c0c4aac4 100644
--- a/graphics/framelimiter.cpp
+++ b/graphics/framelimiter.cpp
@@ -20,52 +20,56 @@
  */
 
 #include "graphics/framelimiter.h"
-
 #include "common/util.h"
 
 namespace Graphics {
 
-FrameLimiter::FrameLimiter(OSystem *system, const uint framerate, const bool vsync) :
+FrameLimiter::FrameLimiter(OSystem *system, const uint framerate, const bool deferToVsync) :
 		_system(system),
-		_speedLimitMs(0),
-		_startFrameTime(0),
-		_lastFrameDurationMs(_speedLimitMs) {
-	// The frame limiter is disabled when vsync is enabled.
-	_enabled = !(vsync && _system->getFeatureState(OSystem::kFeatureVSync)) && (framerate != 0);
-
-	if (_enabled) {
-		_speedLimitMs = 1000 / CLIP<uint>(framerate, 0, 100);
-	}
+		_deferToVsync(deferToVsync),
+		frameStart(0),
+		frameLimit(0),
+		frameDuration(0),
+		drawStart(0),
+		drawDuration(0),
+		loopDuration(0),
+		delay(0) {
+  initialize(framerate);
 }
 
-void FrameLimiter::startFrame() {
-	uint currentTime = _system->getMillis();
-
-	if (_startFrameTime != 0) {
-		_lastFrameDurationMs = currentTime - _startFrameTime;
-	}
+void FrameLimiter::initialize(const uint framerate) {
+	_enabled =  (framerate != 0) && !(_deferToVsync && _system->getFeatureState(OSystem::kFeatureVSync));
+	if (_enabled)
+		frameLimit = 1000.0f / CLIP<uint>(framerate, 1, 100);
+	frameDuration = frameLimit;
+};
 
-	_startFrameTime = currentTime;
+uint FrameLimiter::startFrame() {
+	now = _system->getMillis();
+	if (frameStart != 0) {
+	  frameDuration = now - frameStart;
+    drawDuration = now - drawStart;
+  }
+	frameStart = now;
+	return frameDuration;
 }
 
-void FrameLimiter::delayBeforeSwap() {
-	uint endFrameTime = _system->getMillis();
-	uint frameDuration = endFrameTime - _startFrameTime;
-
-	if (_enabled && frameDuration < _speedLimitMs) {
-		_system->delayMillis(_speedLimitMs - frameDuration);
+bool FrameLimiter::delayBeforeSwap() {
+  now = _system->getMillis();
+  loopDuration = now - frameStart;
+	if(_enabled) {
+	  //delay = frameLimit - loopDuration;  //Original functionality, will tend to undershoot target framerate slightly due to finite screen.update() time.
+  	delay = frameLimit - (now - drawStart); //Ensure EXACTLY the specified frame duration has elapsed since last screen.update() was called.
+    if(delay > 0)
+  	  _system->delayMillis(delay);
 	}
+	drawStart = _system->getMillis();
+	return (delay < 0); //Check if frame is late
 }
 
 void FrameLimiter::pause(bool pause) {
-	if (!pause) {
-		// Make sure the frame duration value is consistent when resuming
-		_startFrameTime = 0;
-	}
-}
-
-uint FrameLimiter::getLastFrameDuration() const {
-	return _lastFrameDurationMs;
+	if (!pause)
+		frameStart = 0; // Ensure the frame duration value is consistent when resuming
 }
 
 } // End of namespace Graphics
diff --git a/graphics/framelimiter.h b/graphics/framelimiter.h
index 69995e4c411..58f3c5fd0c5 100644
--- a/graphics/framelimiter.h
+++ b/graphics/framelimiter.h
@@ -33,24 +33,67 @@ namespace Graphics {
  * by delaying until all of the timeslot allocated to the frame
  * is consumed.
  * Allows to curb CPU usage and have a stable framerate.
+ * If deferToVsync is set true (default), framerate will only be limited to the set value when hardware vsync is inactive, otherwise it will track Vsync directly.
+ * If deferToVsync is set false, framerate will always be limited to the set value, whether or not hardware vsync is active.
+ * In order for hardware vsync status detection to work correctly, initialize() must be called AFTER initGraphics; see below.
  */
 class FrameLimiter {
 public:
-	FrameLimiter(OSystem *system, const uint framerate, const bool vsync = true);
-
-	void startFrame();
-	void delayBeforeSwap();
+	FrameLimiter(OSystem *system, const uint framerate, const bool deferToVsync = true);
+/**
+ * Always call this after instantiating Screen & calling initGraphics(), to ensure Vsync status is detected correctly!
+ */
+	void initialize(const uint framerate);
 
+/**
+ * Call immediately before starting game logic cycle, and immediately after previous screen->update(), if any.
+ * Returns last frame duration.
+ */
+	uint startFrame();
+	
+/**
+ * Call immediately after game logic cycle is completed, and immediately before screen->update().
+ * If Vsync is inactive, will wait and return at the appropriate moment to call screen->update() in order to maintain the specified FPS.
+ * If Vsync is active, will return immediately as screen->update() should automatically wait for the right moment.
+ * Returns true if next frame is expected to be late.
+ */
+	bool delayBeforeSwap();
 	void pause(bool pause);
-
-	uint getLastFrameDuration() const;
+/**
+ * Return duration of last whole frame, including game logic, frame limiter or Vsync delay (if any), and screen redraw time.
+ * Specifically, this is the time between the last two successive startFrame() calls.
+ */
+	uint getLastFrameDuration() const {return frameDuration;};
+/**
+ * Return duration of last screen update
+ * If Vsync is inactive, this value will just be the duration of the redraw process itself;
+ * If Vsync is active, this value will encompass both the redraw time AND the delay between presenting the frame to redraw and the screen redraw actually starting.
+ */
+ 	uint getLastDrawDuration() const {return drawDuration;}; 
+/**
+ * Return duration of last game logic loop
+ * Specifically, this is the time from when startFrame() was last called to when delayBeforeSwap() was last called
+ */
+	uint getLastLoopDuration() const {return loopDuration;};
+/**
+ * If true, framelimiter is active and applying _system->delayMillis(delay) to maintain the specified FPS, if valid.
+ * If false, framelimiter is inactive, either because supplied FPS was invalid or because Vsync is active.
+ * delayBeforeSwap() should still be called even if inactive, in order to ensure timers are updated correctly.
+ */
+	bool isEnabled() const {return _enabled;};
+	
 private:
 	OSystem *_system;
-
 	bool _enabled;
-	uint _speedLimitMs;
-	uint _startFrameTime;
-	uint _lastFrameDurationMs;
+	bool _deferToVsync;
+	uint frameStart;  //Time at which screen update completed and startFrame() was called; start of next cycle of game logic
+  uint frameLimit;  //Target frame duration to achieve specified FPS
+  uint frameDuration; //Duration of previous frame between successive startFrame() calls; total game logic, delay (if any) and screen update time
+  uint drawStart;  //Time at which delayBeforeSwap() returns
+  uint drawDuration;  //Measured screen update time
+  uint loopDuration;  //Duration of last game logic cycle, from when startFrame() was called to when delayBeforeSwap() was called
+  int delay; //Time to delay before returning from delayBeforeSwap()
+  uint now; //Current time
 };
 
 } // End of namespace Graphics


Commit: b32eba27af16fa7ec1e6908555ff72fb90fb4113
    https://github.com/scummvm/scummvm/commit/b32eba27af16fa7ec1e6908555ff72fb90fb4113
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:57+02:00

Commit Message:
ZVISION: Fix bug in script parser.
"Dissolve" effect in Nemesis scripts specified without parentheses;
parser was failing to correctly detect these actions.
Interim screen-blank dissolve effect tested; jarring & unpleasant, so left disabled.
Did not solve bug I originally hoped it would;
transitions to new locations immediately after playing video still shows frame of previous scene.

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/scr_file_handling.cpp
    engines/zvision/scripting/script_manager.cpp


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index ebfc251a1bc..d46d5fb237b 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -983,12 +983,12 @@ void RenderManager::markDirty() {
 	_backgroundDirtyRect = Common::Rect(_backgroundWidth, _backgroundHeight);
 }
 
-#if 0
+//*
 void RenderManager::bkgFill(uint8 r, uint8 g, uint8 b) {
 	_currentBackgroundImage.fillRect(Common::Rect(_currentBackgroundImage.w, _currentBackgroundImage.h), _currentBackgroundImage.format.RGBToColor(r, g, b));
 	markDirty();
 }
-#endif
+//*/
 
 void RenderManager::updateRotation() {
 	int16 _velocity = _engine->getMouseVelocity() + _engine->getKeyboardVelocity();
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index 749679fb233..8b7e17d0145 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -348,10 +348,10 @@ public:
 	// Mark whole background surface as dirty
 	void markDirty();
 
-#if 0
+//*/
 	// Fill background surface by color
 	void bkgFill(uint8 r, uint8 g, uint8 b);
-#endif
+//*/
 	
 	void checkBorders();
 	void rotateTo(int16 to, int16 time);
diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index ffb124b565f..a2e4d47f124 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -110,13 +110,13 @@ ActionAttenuate::ActionAttenuate(ZVision *engine, int32 slotKey, const Common::S
 	_attenuation = 0;
 
 	sscanf(line.c_str(), "%u, %d", &_key, &_attenuation);
-  debug(2,"Created Action: Attenuate, slotKey %d", _slotKey);
+  debug(1,"Created Action: Attenuate, slotKey %d", _slotKey);
   debug(2,"Attenuate script: %s", line.c_str());
   debug(2,"Attenuate parameters: key1 %d, attenuation %d", _key, _attenuation);
 }
 
 bool ActionAttenuate::execute() {
-  debug(2,"Executing Action: Attenuate");
+  debug(1,"Executing Action: Attenuate, slotkey %d", _slotKey);
 	ScriptingEffect *fx = _scriptManager->getSideFX(_key);
 	if (fx && fx->getType() == ScriptingEffect::SCRIPTING_EFFECT_AUDIO) {
 		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
@@ -284,11 +284,14 @@ bool ActionDisplayMessage::execute() {
 
 ActionDissolve::ActionDissolve(ZVision *engine) :
 	ResultAction(engine, 0) {
+  debug(1,"Created action: Dissolve");
 }
 
 bool ActionDissolve::execute() {
+  debug(1,"Executing action: Dissolve");
 	// Cause black screen flick
-	// _engine->getRenderManager()->bkgFill(0, 0, 0); //TODO - reimplement this?  Find out where it is used first.
+	// Not ideal.  Original engine used a softer dissolve effect; simply turning the screen black is jarring, so disabled for now.
+	//_engine->getRenderManager()->bkgFill(0, 0, 0); //TODO - reimplement this?  
 	return true;
 }
 
diff --git a/engines/zvision/scripting/scr_file_handling.cpp b/engines/zvision/scripting/scr_file_handling.cpp
index 82857ae6d8c..62e41ea3ad1 100644
--- a/engines/zvision/scripting/scr_file_handling.cpp
+++ b/engines/zvision/scripting/scr_file_handling.cpp
@@ -274,32 +274,52 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 	line.toLowercase();
 
 	// TODO: Re-order the if-then statements in order of highest occurrence
+	//While within results block
 	while (!stream.eos() && !line.contains('}')) {
+	  //Skip empty lines
 		if (line.empty()) {
 			line = stream.readLine();
 			trimCommentsAndWhiteSpace(&line);
 			line.toLowercase();
 			continue;
 		}
+    debug(4,"Result line: %s", line.c_str());	
 		const char *chrs = line.c_str();
 		uint pos;
-		for (pos = 0; pos < line.size(); pos++)
+/*/
+		//Iterate along line until colon encountered
+		for (pos = 0; pos < line.size(); pos++) {
 			if (chrs[pos] == ':')
 				break;
-		if (pos < line.size()) {
-			uint startpos = pos + 1;
+		}
+/*/
+	  if(line.matchString("action:*", true))
+      pos = 6;
+	  else if(line.matchString("event:*", true))
+	    pos = 5;
+	  else if(line.matchString("background:*", true))
+	    pos = 10;
+	  else
+	    continue;
+//*/
+		if (pos < line.size()) {  //Stuff left
+			uint startpos = pos + 1;  //first character after colon
+			//Scan for next colon or opening bracket
 			for (pos = startpos; pos < line.size(); pos++)
 				if (chrs[pos] == ':' || chrs[pos] == '(')
 					break;
+			debug(4,"startpos %d, pos %d, line.size %d", startpos, pos, line.size());
+			int32 slot = 11;  //Non-setting default slot
+			Common::String args = "";
+			Common::String act(chrs + startpos, chrs + pos);
+			//Extract arguments, if any
 			if (pos < line.size()) {
-				int32 slot = 11;
-				Common::String args = "";
-				Common::String act(chrs + startpos, chrs + pos);
 				startpos = pos + 1;
 				if (chrs[pos] == ':') {
 					for (pos = startpos; pos < line.size(); pos++)
 						if (chrs[pos] == '(')
 							break;
+					//Extract slotkey, if specified
 					Common::String strSlot(chrs + startpos, chrs + pos);
 					slot = atoi(strSlot.c_str());
 					startpos = pos + 1;
@@ -310,6 +330,8 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 							break;
 					args = Common::String(chrs + startpos, chrs + pos);
 				}
+			}
+				debug(4,"Action string: '%s', slot %d, arguments string '%s'", act.c_str(), slot, args.c_str());
 
 				// Parse for the action type
 				if (act.matchString("add", true)) {
@@ -406,7 +428,6 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 				} else {
 					warning("Unhandled result action type: %s", line.c_str());
 				}
-			}
 		}
 		line = stream.readLine();
 		trimCommentsAndWhiteSpace(&line);
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index 12cc672b5fd..660469248aa 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -472,6 +472,7 @@ void ScriptManager::onKeyUp(Common::KeyState keyState) {
 }
 
 void ScriptManager::changeLocation(const Location &_newLocation) {
+  
 	changeLocation(_newLocation.world, _newLocation.room, _newLocation.node, _newLocation.view, _newLocation.offset);
 }
 


Commit: b4363314b33981d374ba937ff3c889b456964749
    https://github.com/scummvm/scummvm/commit/b4363314b33981d374ba937ff3c889b456964749
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:57+02:00

Commit Message:
ZVISION: Fixed bug that briefly showed previous scene after a streaming video right before a location change.

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/scripting/script_manager.h
    engines/zvision/zvision.cpp


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index d46d5fb237b..ed7b28841fb 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -257,7 +257,7 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
     return true;
   }
   else {
-    debug(4,"Skipping screen update; engine forbids rendering at this time.");
+    debug(2,"Skipping screen update; engine forbids rendering at this time.");
     return false;
   };
 }
diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index a2e4d47f124..41e9b44b50b 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -237,6 +237,7 @@ ActionDelayRender::ActionDelayRender(ZVision *engine, int32 slotKey, const Commo
 }
 
 bool ActionDelayRender::execute() {
+  debug(2,"Executing Action: DelayRender");
 	_engine->setRenderDelay(_framesToDelay);
 	return true;
 }
@@ -991,7 +992,8 @@ bool ActionStreamVideo::execute() {
 	if (_scriptManager->getStateValue(StateKey_MPEGMovies) == 1 &&_engine->getSearchManager()->hasFile(hiresPath)) {
 		_fileName = hiresPath;
 		switchToHires = true;
-	} else if (!_engine->getSearchManager()->hasFile(_fileName))
+	} 
+	else if (!_engine->getSearchManager()->hasFile(_fileName))
 		return true;
 #else
 	if (!_engine->getSearchManager()->hasFile(_fileName))
@@ -1000,9 +1002,7 @@ bool ActionStreamVideo::execute() {
 
 	decoder = _engine->loadAnimation(_fileName);
 	uint16 sub = (subtitleExists) ? _engine->getSubtitleManager()->create(subpath, switchToHires) : 0;
-	
 	_engine->getCursorManager()->showMouse(false);
-
 	if (switchToHires) {
 		_engine->getRenderManager()->initialize(true);
     srcRect = Common::Rect(Common::Point(0,69),720, 344);
@@ -1031,6 +1031,7 @@ bool ActionStreamVideo::execute() {
 		_engine->getRenderManager()->initialize(false);
 	_engine->getCursorManager()->showMouse(true);
   _engine->getSubtitleManager()->destroy(sub);
+  _scriptManager->justStreamedVideo();
   debug(2,"Completed executing video stream");
 	return true;
 }
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index 660469248aa..dc287c5b2a1 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -93,6 +93,7 @@ void ScriptManager::update(uint deltaTimeMillis) {
 	if (!execScope(universe))
 		return;
 	updateControls(deltaTimeMillis);
+	_justStreamedVideo=false;
 }
 
 bool ScriptManager::execScope(ScriptScope &scope) {
@@ -477,6 +478,13 @@ void ScriptManager::changeLocation(const Location &_newLocation) {
 }
 
 void ScriptManager::changeLocation(char _world, char _room, char _node, char _view, uint32 offset) {
+  if(_justStreamedVideo) {
+    debug(1,"Initiating location change after video stream");
+  	_engine->setRenderDelay(2); //Prevents previous scene from being rerendered for a moment after scene transition movie plays (e.g. opening temple door)
+  	_justStreamedVideo = false;
+	}
+	else
+    debug(1,"Initiating normal location change");
 	_changeLocationDelayCycles = 1;
 	_nextLocation.world = _world;
 	_nextLocation.room = _room;
@@ -531,7 +539,7 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 			}
 		}
 	}
-	_engine->setRenderDelay(2);
+	//_engine->setRenderDelay(2); //Uncertain if this is necessary; doesn't seem to cause any problems when disabled, but keep an eye on it.
 	if (!leavingMenu) {
 		if (!isLoading && !enteringMenu) {
 			setStateValue(StateKey_LastWorld, getStateValue(StateKey_World));
diff --git a/engines/zvision/scripting/script_manager.h b/engines/zvision/scripting/script_manager.h
index 5311a746bff..317293f80b7 100644
--- a/engines/zvision/scripting/script_manager.h
+++ b/engines/zvision/scripting/script_manager.h
@@ -195,11 +195,15 @@ private:
 	int _changeLocationDelayCycles;
 
 	uint32 _currentlyFocusedControl;
+	
+	bool _justStreamedVideo;
 
 public:
 	void initialize();
 	void update(uint deltaTimeMillis);
 	void queuePuzzles(uint32 key);
+	
+	void justStreamedVideo() {_justStreamedVideo=true;};
 
 	int getStateValue(uint32 key);
 	void setStateValue(uint32 key, int value);
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index 4bbdc96e222..9b41fccc7e1 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -351,7 +351,7 @@ Common::Error ZVision::run() {
     debug(5,"Rotation");
 		_renderManager->updateRotation();	
     debug(5,"Scripts");
-		_scriptManager->update(deltaTime);		
+		_scriptManager->update(deltaTime);
     debug(5,"Menu");
 		_menu->process(deltaTime);
     debug(5,"Subtitles");


Commit: dded57736b48ad43c5d2546faf35c41f052f8002
    https://github.com/scummvm/scummvm/commit/dded57736b48ad43c5d2546faf35c41f052f8002
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:57+02:00

Commit Message:
ZVISION: Fix bug in PanTrackNode.
Caused DBZ error if node is created in static screen then persists onto panorama.
Auxiliary scripts must now explicitly specify if PanTrackNode is being used on a static screen.

Changed paths:
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/actions.h
    engines/zvision/scripting/control.cpp
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/effects/music_effect.h


diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index 41e9b44b50b..90c7272d4a6 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -552,13 +552,16 @@ ActionPanTrack::ActionPanTrack(ZVision *engine, int32 slotKey, const Common::Str
 	_mag(255),
 	_resetMusicNode(true),
 	_resetMixerOnDelete(false),
+	_staticScreen(false),
 	_musicSlot(0) {
 	uint mag = 255;  //Original game scripts do not specify this, but require it to be 255 to work correctly.
 	uint resetMusicNode = 1;  //Original game scripts do not specify this, but require it to be true to work correctly.
 	uint resetMixerOnDelete = 0;  //Original game scripts do not specify this, but require it to be false to work correctly.
-	sscanf(line.c_str(), "%u %d %u %u %u", &_musicSlot, &_pos, &mag, &resetMusicNode, &resetMixerOnDelete);
+	uint staticScreen = 0;  //Original game scripts do not specify this, but require it to be false to work correctly.
+	sscanf(line.c_str(), "%u %d %u %u %u %u", &_musicSlot, &_pos, &mag, &resetMusicNode, &resetMixerOnDelete, &staticScreen);
 	_resetMusicNode = resetMusicNode > 0;
   _resetMixerOnDelete = resetMixerOnDelete > 0;
+  _staticScreen = staticScreen > 0;
 	_mag = mag;
 	if(_resetMusicNode) {
 	  if(_scriptManager->getStateValue(_musicSlot) != 2) {
@@ -582,7 +585,7 @@ bool ActionPanTrack::execute() {
   debug(2,"Executing Action: PanTrack, slotkey %d, musicSlot %u, pos %d, mag %d", _slotKey, _musicSlot, _pos, _mag);
 	if (_scriptManager->getSideFX(_slotKey))
 		return true;
-	_scriptManager->addSideFX(new PanTrackNode(_engine, _slotKey, _musicSlot, _pos, _mag, _resetMixerOnDelete));
+	_scriptManager->addSideFX(new PanTrackNode(_engine, _slotKey, _musicSlot, _pos, _mag, _resetMixerOnDelete, _staticScreen));
 	return true;
 }
 
diff --git a/engines/zvision/scripting/actions.h b/engines/zvision/scripting/actions.h
index 3ec117ea1c2..5b3fc77fec3 100644
--- a/engines/zvision/scripting/actions.h
+++ b/engines/zvision/scripting/actions.h
@@ -248,6 +248,7 @@ private:
 	* Since there is literally nothing in the game scripts that sets some of these values to 2, and certain pan_tracks require it to be 2 for the puzzle that creates them to trigger,
 	* the original game engine code must have set these values to 2 manually somehow upon conditions being met to allow a pan_track to be created?
 	*/
+	bool _staticScreen; //Used by auxiliary scripts to apply directionality to audio in static screens; not used in original game scripts.
 	bool _resetMixerOnDelete; //Unnecessary and should be set false for original scripts; useful in some cases in extra scripts to avoid brief volume spikes on location changes
 	uint32 _musicSlot;
 };
diff --git a/engines/zvision/scripting/control.cpp b/engines/zvision/scripting/control.cpp
index 6db933df450..0e96dcce780 100644
--- a/engines/zvision/scripting/control.cpp
+++ b/engines/zvision/scripting/control.cpp
@@ -28,14 +28,17 @@
 #include "zvision/graphics/render_manager.h"
 
 #include "common/stream.h"
+#include "common/debug.h"
 
 namespace ZVision {
 
 void Control::parseFlatControl(ZVision *engine) {
+  debug(1,"Setting render state to FLAT");
 	engine->getRenderManager()->getRenderTable()->setRenderState(RenderTable::FLAT);
 }
 
 void Control::parsePanoramaControl(ZVision *engine, Common::SeekableReadStream &stream) {
+  debug(1,"Setting render state to PANORAMA");
 	RenderTable *renderTable = engine->getRenderManager()->getRenderTable();
 	renderTable->setRenderState(RenderTable::PANORAMA);
 
@@ -71,6 +74,7 @@ void Control::parsePanoramaControl(ZVision *engine, Common::SeekableReadStream &
 
 // Only used in Zork Nemesis, handles tilt controls (ZGI doesn't have a tilt view)
 void Control::parseTiltControl(ZVision *engine, Common::SeekableReadStream &stream) {
+  debug(1,"Setting render state to TILT");
 	RenderTable *renderTable = engine->getRenderManager()->getRenderTable();
 	renderTable->setRenderState(RenderTable::TILT);
 
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index c177702e1b6..b3b4b8a2472 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -174,25 +174,16 @@ void MusicNode::setVolume(uint8 newVolume) {
 }
 
 
-PanTrackNode::PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos, uint8 mag, bool resetMixerOnDelete)
+PanTrackNode::PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos, uint8 mag, bool resetMixerOnDelete, bool staticScreen)
 	: ScriptingEffect(engine, key, SCRIPTING_EFFECT_PANTRACK),
 	_slot(slot),
 	sourcePos(0),
 	viewPos(0),
 	_mag(mag),
 	_width(0),
+	_pos(pos),
+	_staticScreen(staticScreen),
 	_resetMixerOnDelete(resetMixerOnDelete) {
-	switch(_engine->getRenderManager()->getRenderTable()->getRenderState()) {
-	  case RenderTable::PANORAMA :
-	    _width = _engine->getRenderManager()->getBkgSize().x;
-	    sourcePos.setDegrees(360*pos/_width);
-	    break;	
-	  case RenderTable::FLAT :
-	  case RenderTable::TILT :
-	  default :
-	    sourcePos.setDegrees(pos);
-	    break;
-	}
   debug(3,"Created PanTrackNode, key %d, slot %d", _key, _slot);
 	process(0); 	// Try to set pan value for music node immediately
 }
@@ -216,16 +207,35 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 	ScriptingEffect *fx = scriptManager->getSideFX(_slot);
 	if (fx && fx->getType() == SCRIPTING_EFFECT_AUDIO) {
 		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
-	  switch(_engine->getRenderManager()->getRenderTable()->getRenderState()) {
-	    case RenderTable::PANORAMA :
-	      viewPos.setDegrees(360*scriptManager->getStateValue(StateKey_ViewPos)/_width);
-	      break;	
-	    case RenderTable::FLAT :
-	    case RenderTable::TILT :
-	    default :
-	      viewPos.setDegrees(0);
-	      break;
-	  }
+		if(!_staticScreen)
+		  //Original game scripted behaviour
+	    switch(_engine->getRenderManager()->getRenderTable()->getRenderState()) {
+	      case RenderTable::PANORAMA :
+	        debug(3,"PanTrackNode in panorama mode");
+	          _width = _engine->getRenderManager()->getBkgSize().x;
+	          if(_width) {
+	            sourcePos.setDegrees(360*_pos/_width);
+      	      viewPos.setDegrees(360*scriptManager->getStateValue(StateKey_ViewPos)/_width);
+    	      }
+    	      else {
+    	        warning("Encountered zero background width whilst processing PanTrackNode in panoramic mode!");
+	            //sourcePos.setDegrees(0);
+	            //viewPos.setDegrees(0);
+	          }
+	        break;	
+	      case RenderTable::FLAT :
+	      case RenderTable::TILT :
+	      default :
+	        debug(3,"PanTrackNode in FLAT/TILT mode");
+	        sourcePos.setDegrees(0);
+	        viewPos.setDegrees(0);
+	        break;
+      }
+    else {
+      //Used for auxiliary scripts only
+      sourcePos.setDegrees(_pos);
+      viewPos.setDegrees(0);
+    }
 		Math::Angle azimuth;
 		azimuth = sourcePos - viewPos;
 		debug(3,"soundPos: %f, viewPos: %f, azimuth: %f, width %d", sourcePos.getDegrees(), viewPos.getDegrees(), azimuth.getDegrees(), _width);
diff --git a/engines/zvision/scripting/effects/music_effect.h b/engines/zvision/scripting/effects/music_effect.h
index 0ff730843fa..78110b5c2c0 100644
--- a/engines/zvision/scripting/effects/music_effect.h
+++ b/engines/zvision/scripting/effects/music_effect.h
@@ -121,17 +121,17 @@ private:
 
 class PanTrackNode : public ScriptingEffect {
 public:
-	PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos, uint8 mag=255, bool resetMixerOnDelete=false);
+	PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos, uint8 mag=255, bool resetMixerOnDelete=false, bool staticScreen=false);
 	~PanTrackNode() override;
 	bool process(uint32 deltaTimeInMillis) override;
 
 private:
 	uint32 _slot;
-	int16 _width;
+	int16 _width, _pos;
   Math::Angle sourcePos, viewPos;
 	uint8 _mag;
 	bool _resetMixerOnDelete;
-	bool staticScreen;
+	bool _staticScreen;
 };
 
 } // End of namespace ZVision


Commit: 52f5defa1b1fb39399ad4cd3993a999f10fa7e4f
    https://github.com/scummvm/scummvm/commit/52f5defa1b1fb39399ad4cd3993a999f10fa7e4f
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:57+02:00

Commit Message:
ZVISION: Amended previous bug fix that prevented scene redraw before changing location after video;
did not prevent erroneous redraws between sequential videos, e.g. totemization.
Now seems to work in all cases.

Changed paths:
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/scripting/script_manager.h


diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index 90c7272d4a6..ebf79948686 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -1034,7 +1034,7 @@ bool ActionStreamVideo::execute() {
 		_engine->getRenderManager()->initialize(false);
 	_engine->getCursorManager()->showMouse(true);
   _engine->getSubtitleManager()->destroy(sub);
-  _scriptManager->justStreamedVideo();
+  _engine->setRenderDelay(2); //Necessary for avoiding redraw of previous scene between sequential videos (eg totemization sequence in ZGI) & when changing location right after a video (e.g. opening temple door in Nemesis)
   debug(2,"Completed executing video stream");
 	return true;
 }
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index dc287c5b2a1..bf54e4564fb 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -93,7 +93,6 @@ void ScriptManager::update(uint deltaTimeMillis) {
 	if (!execScope(universe))
 		return;
 	updateControls(deltaTimeMillis);
-	_justStreamedVideo=false;
 }
 
 bool ScriptManager::execScope(ScriptScope &scope) {
@@ -478,13 +477,6 @@ void ScriptManager::changeLocation(const Location &_newLocation) {
 }
 
 void ScriptManager::changeLocation(char _world, char _room, char _node, char _view, uint32 offset) {
-  if(_justStreamedVideo) {
-    debug(1,"Initiating location change after video stream");
-  	_engine->setRenderDelay(2); //Prevents previous scene from being rerendered for a moment after scene transition movie plays (e.g. opening temple door)
-  	_justStreamedVideo = false;
-	}
-	else
-    debug(1,"Initiating normal location change");
 	_changeLocationDelayCycles = 1;
 	_nextLocation.world = _world;
 	_nextLocation.room = _room;
diff --git a/engines/zvision/scripting/script_manager.h b/engines/zvision/scripting/script_manager.h
index 317293f80b7..5311a746bff 100644
--- a/engines/zvision/scripting/script_manager.h
+++ b/engines/zvision/scripting/script_manager.h
@@ -195,15 +195,11 @@ private:
 	int _changeLocationDelayCycles;
 
 	uint32 _currentlyFocusedControl;
-	
-	bool _justStreamedVideo;
 
 public:
 	void initialize();
 	void update(uint deltaTimeMillis);
 	void queuePuzzles(uint32 key);
-	
-	void justStreamedVideo() {_justStreamedVideo=true;};
 
 	int getStateValue(uint32 key);
 	void setStateValue(uint32 key, int value);


Commit: e068e51d227d318ef1bb3ee43441f234d9556413
    https://github.com/scummvm/scummvm/commit/e068e51d227d318ef1bb3ee43441f234d9556413
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:58+02:00

Commit Message:
ZVISION: Created AutomaticSubtitle class.
Enables scripted subtitles to self-clear when their sound file ends if they are still on-screen when a streaming video starts.
Remaining bug: Subtitles still leave artefacts on-screen when Sarcophagus videos play in Nemesis.
Need mechanism to update screen if streaming a video that doesn't fill the entire background.

Changed paths:
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/effects/syncsound_effect.cpp
    engines/zvision/text/subtitle_manager.cpp
    engines/zvision/text/subtitle_manager.h
    engines/zvision/zvision.cpp


diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index b3b4b8a2472..504f8159147 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -109,7 +109,7 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 
 		Common::Path subpath(filename.getParent().appendComponent(subname));
 		if (_engine->getSearchManager()->hasFile(subpath))
-		  _sub = _engine->getSubtitleManager()->create(subpath);
+		  _sub = _engine->getSubtitleManager()->create(subpath, _handle); //NB automatic subtitle!
 		_loaded = true;
 		updateMixer();
 	}
@@ -160,8 +160,10 @@ bool MusicNode::process(uint32 deltaTimeInMillis) {
 		  if (_volume != _newvol)
 			  setVolume(_newvol);
 		}
+	  /*  //Redundant with switch to automatic subtitles
 		if (_sub && _engine->getScriptManager()->getStateValue(StateKey_Subtitles) == 1)
 			_engine->getSubtitleManager()->update(_engine->_mixer->getSoundElapsedTime(_handle) / 100, _sub);
+		//*/
 	}
 	return false;
 }
diff --git a/engines/zvision/scripting/effects/syncsound_effect.cpp b/engines/zvision/scripting/effects/syncsound_effect.cpp
index fade0238be2..4bbd00fed4d 100644
--- a/engines/zvision/scripting/effects/syncsound_effect.cpp
+++ b/engines/zvision/scripting/effects/syncsound_effect.cpp
@@ -59,7 +59,7 @@ SyncSoundNode::SyncSoundNode(ZVision *engine, uint32 key, Common::Path &filename
 
 	Common::Path subpath(filename.getParent().appendComponent(subname));
 	if (_engine->getSearchManager()->hasFile(subpath))
-		_sub = _engine->getSubtitleManager()->create(subpath);
+		_sub = _engine->getSubtitleManager()->create(subpath, _handle); //NB automatic subtitle!
 }
 
 SyncSoundNode::~SyncSoundNode() {
@@ -74,8 +74,10 @@ bool SyncSoundNode::process(uint32 deltaTimeInMillis) {
 	else {
 		if (_engine->getScriptManager()->getSideFX(_syncto) == NULL)
 			return stop();
+  /*  //Redundant with switch to automatic subtitles
 		if (_sub && _engine->getScriptManager()->getStateValue(StateKey_Subtitles) == 1)
 			_engine->getSubtitleManager()->update(_engine->_mixer->getSoundElapsedTime(_handle) / 100, _sub);
+	//*/
 	}
 	return false;
 }
diff --git a/engines/zvision/text/subtitle_manager.cpp b/engines/zvision/text/subtitle_manager.cpp
index 829e56b1ca7..25fe86344f0 100644
--- a/engines/zvision/text/subtitle_manager.cpp
+++ b/engines/zvision/text/subtitle_manager.cpp
@@ -24,6 +24,7 @@
 #include "zvision/file/search_manager.h"
 #include "zvision/text/text.h"
 #include "common/system.h"
+#include "zvision/scripting/script_manager.h"
 
 namespace ZVision {
 
@@ -50,8 +51,11 @@ SubtitleManager::~SubtitleManager() {
 }
 
 void SubtitleManager::process(int32 deltatime) {
-	//Update all subtitles' respective deletion timers
   for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
+    //Update all automatic subtitles
+    if (it->_value->selfUpdate())
+      redraw = true;
+  	//Update all subtitles' respective deletion timers
 		if (it->_value->process(deltatime)) {
       debug(4,"Deleting subtitle, subId=%d", it->_key);
 			_subsFocus.remove(it->_key);			
@@ -89,7 +93,6 @@ void SubtitleManager::process(int32 deltatime) {
 	}
 }
 
-
 void SubtitleManager::update(int32 count, uint16 subid) {
 	if (_subsList.contains(subid))
     if( _subsList[subid]->update(count) ) {
@@ -106,6 +109,14 @@ uint16 SubtitleManager::create(const Common::Path &subname, bool vob) {
   return _subId;
 }
 
+uint16 SubtitleManager::create(const Common::Path &subname, Audio::SoundHandle handle) {
+  _subId++;
+  debug(2,"Creating scripted subtitle, subId=%d", _subId);
+  _subsList[_subId] = new AutomaticSubtitle(_engine, subname, handle);
+  _subsFocus.set(_subId);
+  return _subId;
+}
+
 uint16 SubtitleManager::create(const Common::String &str) {
   _subId++;
   debug(2,"Creating simple subtitle, subId=%d, message %s", _subId, str.c_str());
@@ -358,4 +369,25 @@ bool Subtitle::update(int32 count) {
   return redraw;
 }
 
+AutomaticSubtitle::AutomaticSubtitle(ZVision *engine, const Common::Path &subname, Audio::SoundHandle handle) :
+  Subtitle(engine, subname, false),
+  _handle(handle) {
+}
+
+bool AutomaticSubtitle::selfUpdate() {
+	if (_engine->_mixer->isSoundHandleActive(_handle) && _engine->getScriptManager()->getStateValue(StateKey_Subtitles) == 1)
+    return update(_engine->_mixer->getSoundElapsedTime(_handle) / 100);
+  else {
+    todelete = true;
+    return false;
+  }
+}
+
+bool AutomaticSubtitle::process(int32 deltatime) {
+  Subtitle::process(deltatime);
+	if(!_engine->_mixer->isSoundHandleActive(_handle))
+	  todelete = true;
+	return todelete;
+}
+
 } // End of namespace ZVision
diff --git a/engines/zvision/text/subtitle_manager.h b/engines/zvision/text/subtitle_manager.h
index cda96e4e872..274119c5d6d 100644
--- a/engines/zvision/text/subtitle_manager.h
+++ b/engines/zvision/text/subtitle_manager.h
@@ -24,6 +24,7 @@
 
 #include "zvision/zvision.h"
 #include "zvision/common/focus_list.h"
+#include "audio/mixer.h"
 
 namespace ZVision {
 
@@ -34,12 +35,12 @@ friend class SubtitleManager;
 public:
   Subtitle(ZVision *engine, const Common::Path &subname, bool vob=false);  //For scripted subtitles
   Subtitle(ZVision *engine, const Common::String &str, const Common::Rect &textArea);  //For other text messages
-  ~Subtitle();
-  
+  virtual ~Subtitle();
   bool update(int32 count); //Return true if necessary to redraw
+  virtual bool selfUpdate() {return false;};
 
-private:
-  bool process(int32 deltatime);  //Return true if to be deleted
+protected:
+  virtual bool process(int32 deltatime);  //Return true if to be deleted
 	ZVision *_engine;
 	Common::Rect r;
 	Common::String txt;
@@ -62,6 +63,17 @@ private:
 	Common::Array<line> _lines;
 };
 
+class AutomaticSubtitle : public Subtitle {
+public:
+  AutomaticSubtitle(ZVision *engine, const Common::Path &subname, Audio::SoundHandle handle);  //For scripted audio subtitles
+  ~AutomaticSubtitle() {};
+  
+private:
+  bool process(int32 deltatime);  //Return true if to be deleted
+  bool selfUpdate(); //Return true if necessary to redraw
+  Audio::SoundHandle _handle;
+};
+
 class SubtitleManager {
 public:
   SubtitleManager(ZVision *engine, const ScreenLayout layout, const Graphics::PixelFormat pixelFormat, bool doubleFPS);
@@ -86,15 +98,18 @@ private:
   FocusList<uint16> _subsFocus;
   
 public:
+  //Update all subtitle objects' deletion timers, delete expired subtitles, & redraw most recent.  Does NOT update any subtitle's count value or displayed string!
   void process(int32 deltatime);  //deltatime is always milliseconds
+  //Update counter value of referenced subtitle id & set current line to display, if any.
 	void update(int32 count, uint16 subid);  //Count is milliseconds for sound & music; frames for video playback.
 	
   Common::Point getTextOffset() {return _textOffset;}
 	
 	// Create subtitle object and return ID
 	uint16 create(const Common::Path &subname, bool vob = false);
+	uint16 create(const Common::Path &subname, Audio::SoundHandle handle);	//NB this creates an automatic subtitle
 	uint16 create(const Common::String &str);
-
+	
 	// Delete subtitle object by ID
 	void destroy(uint16 id);
 	void destroy(uint16 id, int16 delay);
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index 9b41fccc7e1..2ecb6293d38 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -355,7 +355,7 @@ Common::Error ZVision::run() {
     debug(5,"Menu");
 		_menu->process(deltaTime);
     debug(5,"Subtitles");
-		_subtitleManager->process(deltaTime);		
+		_subtitleManager->process(deltaTime);
 	  debug(5,"Render");
 		// Render the backBuffer to the screen
   	_renderManager->prepareBackground();


Commit: e826d7571bcd048647f7e5ea07b2deeecfccdd61
    https://github.com/scummvm/scummvm/commit/e826d7571bcd048647f7e5ea07b2deeecfccdd61
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:58+02:00

Commit Message:
ZVISION: Fix bug that caused graphical corruption of streaming video subtitles.
Bug occurred in special cases where the streaming video does not overlap the subtitles, e.g Nemesis sarcophagi.

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/video/video.cpp


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index ed7b28841fb..64c58674d3c 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -146,9 +146,6 @@ void RenderManager::initialize(bool hiRes) {
     _menuLetterbox = Common::Rect(_menuArea.left, _menuArea.top, _menuArea.right, _workingArea.top);
   else
     _menuLetterbox = _menuArea;
-  //Convert to menuArea coordinates
-  _menuLetterbox.translate(-_menuArea.left, -_menuArea.top);
-  _menuOverlay.translate(-_menuArea.left, -_menuArea.top);
     
   //TODO - add upscaling for HD mode!
   _textOverlay = _textArea.findIntersectingRect(_workingArea);
@@ -156,9 +153,9 @@ void RenderManager::initialize(bool hiRes) {
     _textLetterbox = Common::Rect(_textArea.left, _workingArea.bottom, _textArea.right, _textArea.bottom);
   else
     _textLetterbox = _textArea;
-  //Convert to textArea coordinates
-  _textOverlay.translate(-_textArea.left, -_textArea.top);
-  _textLetterbox.translate(-_textArea.left, -_textArea.top);
+  
+  debug(2,"text overlay area: %d,%d,%d,%d", _textOverlay.left, _textOverlay.top, _textOverlay.bottom, _textOverlay.right);
+  debug(2,"menu overlay area: %d,%d,%d,%d", _menuOverlay.left, _menuOverlay.top, _menuOverlay.bottom, _menuOverlay.right);
 	
   debug(2,"Clearing backbuffers");
 	//Clear backbuffer surfaces
@@ -172,16 +169,15 @@ void RenderManager::initialize(bool hiRes) {
 	debug(1,"Render manager initialized");
 }
 
-bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
-  debug(5,"\nrenderSceneToScreen");
+bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool preStream) {
+  debug(5,"\nrenderSceneToScreen%s%s%s", immediate ? ", immediate" : "", overlayOnly ? ", overlay only" : "", preStream ? ", pre-stream" : "");
   uint32 startTime = _system->getMillis();
   if(!overlayOnly) {
-	  Graphics::Surface *out = &_warpedSceneSurface;
-	  Graphics::Surface *in = &_backgroundSurface;
+	  Graphics::Surface *inputSurface = &_backgroundSurface;
 	  Common::Rect outWndDirtyRect;
 	  //Apply graphical effects to temporary effects buffer and/or directly to current background image, as appropriate
 	  if (!_effects.empty()) {
-	    debug(5,"Rendering effects");
+	    debug(6,"Rendering effects");
 		  bool copied = false;
 		  const Common::Rect windowRect(_workingArea.width(), _workingArea.height());
 		  for (EffectsList::iterator it = _effects.begin(); it != _effects.end(); it++) {
@@ -193,7 +189,7 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
 				  if (!copied) {
 					  copied = true;
 					  _effectSurface.copyFrom(_backgroundSurface);
-					  in = &_effectSurface;
+					  inputSurface = &_effectSurface;
 				  }
 				  const Graphics::Surface *post;
 				  if ((*it)->isPort())
@@ -218,53 +214,60 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly) {
 	    case RenderTable::TILT:
 	      debug(5,"Rendering panorama");
 		    if (!_backgroundSurfaceDirtyRect.isEmpty()) {
-			    _renderTable.mutateImage(&_warpedSceneSurface, in, _engine->getScriptManager()->getStateValue(StateKey_HighQuality));
-			    out = &_warpedSceneSurface;
+			    _renderTable.mutateImage(&_warpedSceneSurface, inputSurface, _engine->getScriptManager()->getStateValue(StateKey_HighQuality));
+			    outputSurface = &_warpedSceneSurface;
 			    outWndDirtyRect = Common::Rect(_workingArea.width(), _workingArea.height());
 		    }
 	      break;
 	    default:
-		    out = in;
+		    outputSurface = inputSurface;
 		    outWndDirtyRect = _backgroundSurfaceDirtyRect;
 		    break;
       debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
     }
     debug(5,"Rendering working area");
-	  _workingManagedSurface.simpleBlitFrom(*out); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
+	  _workingManagedSurface.simpleBlitFrom(*outputSurface); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
     debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
 	}
-  debug(5,"Rendering menu");
-	_menuManagedSurface.transBlitFrom(_menuSurface, -1);
-  debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
-  debug(5,"Rendering text");
-  _textManagedSurface.transBlitFrom(_textSurface, -1);
-  debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
-  if(immediate) {
-    frameLimiter.startFrame();
-    debug(5,"Updating screen");
-    _screen.update();
-    debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
-    debug(10,"~renderSceneToScreen, immediate");
-    return true;
-  }
-  else if (_engine->canRender()) {
-    frameLimiter.delayBeforeSwap();
-    frameLimiter.startFrame();
-    debug(5,"Updating screen");
-    _screen.update();
-    debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
-    debug(10,"~renderSceneToScreen, frame limited");
-    return true;
+  if(preStream) {
+    debug(5,"Pre-rendering text area for video stream");    
+	  _workingManagedSurface.simpleBlitFrom(*outputSurface, _textOverlay, _textOverlay.origin()); //Prevents subtitle visual corruption when streaming videos that don't fully overlap them, e.g. Nemesis sarcophagi
+    return false;
   }
   else {
-    debug(2,"Skipping screen update; engine forbids rendering at this time.");
-    return false;
+    debug(5,"Rendering menu");
+	  _menuManagedSurface.transBlitFrom(_menuSurface, -1);
+    debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
+    debug(5,"Rendering text");
+    _textManagedSurface.transBlitFrom(_textSurface, -1);
+    debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
+    if(immediate) {
+      frameLimiter.startFrame();
+      debug(5,"Updating screen");
+      _screen.update();
+      debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
+      debug(10,"~renderSceneToScreen, immediate");
+      return true;
+    }
+    else if (_engine->canRender()) {
+      frameLimiter.delayBeforeSwap();
+      frameLimiter.startFrame();
+      debug(5,"Updating screen");
+      _screen.update();
+      debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
+      debug(10,"~renderSceneToScreen, frame limited");
+      return true;
+    }
+    else {
+      debug(2,"Skipping screen update; engine forbids rendering at this time.");
+      return false;
+    };
   };
 }
 
 Graphics::ManagedSurface &RenderManager::getVidSurface(Common::Rect &dstRect) {
   Common::Rect _dstRect = dstRect;
-  _dstRect.translate(_workingArea.left, _workingArea.top);  //Convert to working area coordinates
+  _dstRect.translate(_workingArea.left, _workingArea.top);  //Convert to screen coordinates
 	_vidManagedSurface.create(_screen, _dstRect);
 	debug(1,"Obtaining managed video surface at %d,%d,%d,%d", _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
 	return _vidManagedSurface;
@@ -667,10 +670,15 @@ void RenderManager::clearMenuSurface(bool force, int32 colorkey) {
   if(force)
     _menuSurfaceDirtyRect = Common::Rect(_menuArea.width(), _menuArea.height());
   if(!_menuSurfaceDirtyRect.isEmpty()) {
-	  Common::Rect _menuLetterboxDirty = _menuSurfaceDirtyRect.findIntersectingRect(_menuLetterbox);
+    //Convert to local menuArea coordinates
+    Common::Rect letterbox = _menuLetterbox;
+    Common::Rect overlay =_menuOverlay;
+    letterbox.translate(-_menuArea.left, -_menuArea.top);
+    overlay.translate(-_menuArea.left, -_menuArea.top);
+	  Common::Rect _menuLetterboxDirty = _menuSurfaceDirtyRect.findIntersectingRect(letterbox);
     if(!_menuLetterboxDirty.isEmpty())
       _menuSurface.fillRect(_menuLetterboxDirty, 0);
-	  Common::Rect _menuOverlayDirty = _menuSurfaceDirtyRect.findIntersectingRect(_menuOverlay);
+	  Common::Rect _menuOverlayDirty = _menuSurfaceDirtyRect.findIntersectingRect(overlay);
     if(!_menuOverlayDirty.isEmpty()) {
 	    _menuSurface.fillRect(_menuOverlayDirty, colorkey);
       //TODO - mark working window dirty here so that it will redraw & blank overlaid residue on next frame
@@ -694,10 +702,15 @@ void RenderManager::clearTextSurface(bool force, int32 colorkey) {
   if(force)
     _textSurfaceDirtyRect = Common::Rect(_textArea.width(),_textArea.height());
   if(!_textSurfaceDirtyRect.isEmpty()) {
-	  Common::Rect _textLetterboxDirty = _textSurfaceDirtyRect.findIntersectingRect(_textLetterbox);
+    //Convert to local textArea coordinates
+    Common::Rect letterbox = _textLetterbox;
+    Common::Rect overlay =_textOverlay;
+    letterbox.translate(-_textArea.left, -_textArea.top);
+    overlay.translate(-_textArea.left, -_textArea.top);
+	  Common::Rect _textLetterboxDirty = _textSurfaceDirtyRect.findIntersectingRect(letterbox);
     if(!_textLetterboxDirty.isEmpty())
       _textSurface.fillRect(_textLetterboxDirty, 0);
-	  Common::Rect _textOverlayDirty = _textSurfaceDirtyRect.findIntersectingRect(_textOverlay);
+	  Common::Rect _textOverlayDirty = _textSurfaceDirtyRect.findIntersectingRect(overlay);
     if(!_textOverlayDirty.isEmpty()) {
 	    _textSurface.fillRect(_textOverlayDirty, colorkey);
       //TODO - mark working window dirty here so that it will redraw & blank overlaid residue on next frame
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index 8b7e17d0145..98c88f4eef3 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -118,8 +118,8 @@ private:
 //*/
 
 	// Rectangle for subtitles & other messages
-	Common::Rect _textArea;
-	Common::Rect _textLetterbox;  //Section of text area to be filled with black when blanked
+	Common::Rect _textArea; //NB Screen coordinates
+	Common::Rect _textLetterbox;  //Section of text area outside working window, to be filled with black when blanked
 	Common::Rect _textOverlay;	//Section of text area to be filled with colorkey when blanked (may potentially intersect text letterbox area if screen/window is wider than working area!)
 
 	// Buffer for drawing menu
@@ -128,12 +128,19 @@ private:
 	Common::Rect _menuSurfaceDirtyRect;  //subrectangle of menu area outside working area
 
 	// Rectangle for menu area
-	Common::Rect _menuArea;
+	Common::Rect _menuArea; //Screen coordinates
 	Common::Rect _menuLetterbox; //Section of menu area to be filled with black when blanked
 	Common::Rect _menuOverlay;	//Section of menu area to be filled with colorkey when blanked (may potentially intersect menu letterbox area if screen/window is wider than working area!)
 
-	//Buffer for video playback (render directly for speed; no backbuffer)
+	//Buffer for streamed video playback
+//*
 	Graphics::ManagedSurface _vidManagedSurface;
+/*/
+  Graphics::Surface _vidSurface;
+//*/
+  
+  //Area of streamed video playback
+  Common::Rect _vidArea;
 
 	// A buffer used for apply graphics effects
 	Graphics::Surface _effectSurface;
@@ -146,6 +153,9 @@ private:
 
 	// Visual effects list
 	EffectsList _effects;
+	
+	//Pointer to currently active backbuffer output surface 
+  Graphics::Surface *outputSurface;
 
 	bool _doubleFPS;
 	bool _widescreen;
@@ -155,11 +165,12 @@ public:
 
 	/**
 	 * Renders the scene to the screen
-	 . Returns true if screen was updated
+	 * Returns true if screen was updated
+	 * If streamMode is set true, all background processing is skipped and the previous framebuffer is used
 	 */
-	bool renderSceneToScreen(bool immediate = false, bool overlayOnly = false);
+	bool renderSceneToScreen(bool immediate = false, bool overlayOnly = false, bool preStream = false);
 	
-	Graphics::ManagedSurface &getVidSurface(Common::Rect &dstRect);  //dstRect is defined relative to working window origin
+	Graphics::ManagedSurface &getVidSurface(Common::Rect &dstRect);  //dstRect is defined relative to working area origin
 	
 	Common::Rect getMenuArea() {
 	  return _menuArea;
diff --git a/engines/zvision/video/video.cpp b/engines/zvision/video/video.cpp
index 7f214e5ab88..2e1ba691aef 100644
--- a/engines/zvision/video/video.cpp
+++ b/engines/zvision/video/video.cpp
@@ -149,6 +149,7 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 			if (showSubs && sub > 0)
 				_subtitleManager->update(vid.getCurFrame(), sub);
 			if (frame) {
+		    _renderManager->renderSceneToScreen(true,true,true);  //Redraw text area to clean background of subtitles for videos that don't fill entire working area, e.g, Nemesis sarcophagi
 				if (scaled) {
 				  debug(8,"Scaled blit from area %d x %d to video output surface at output surface position %d, %d", _srcRect.width(), _srcRect.height(), _dstRect.left, _dstRect.top);
 					outSurface.blitFrom(*frame, _srcRect, _dstRect);
@@ -161,7 +162,7 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 			}
 		}
 		// Always update the screen so the mouse continues to render & video does not skip
-		_renderManager->renderSceneToScreen(true,true);
+		_renderManager->renderSceneToScreen(true,true,false);
 		_system->delayMillis(vid.getTimeToNextFrame() / 2); //Exponentially decaying delay
 	}
 	_cutscenesKeymap->setEnabled(false);


Commit: 32cc542bb07cb3523cc8b13a1ce183a7b99fe9f8
    https://github.com/scummvm/scummvm/commit/32cc542bb07cb3523cc8b13a1ce183a7b99fe9f8
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:58+02:00

Commit Message:
ZVISION: Clearer debug message for ActionMusic().

Changed paths:
    engines/zvision/scripting/actions.cpp


diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index ebf79948686..76afc47d093 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -493,6 +493,7 @@ ActionMusic::ActionMusic(ZVision *engine, int32 slotKey, const Common::String &l
 		  sscanf(line.c_str(), "%u %d %d %14s", &type, &prog, &note, volumeBuffer);
 		  _note = note;
 		  _prog = prog;
+		  _loop = false;
 		  break;
 	  default:
 		  _midi = false;
@@ -515,7 +516,7 @@ ActionMusic::ActionMusic(ZVision *engine, int32 slotKey, const Common::String &l
 	if (engine->getGameId() == GID_NEMESIS && _slotKey == 14822 && _scriptManager->getStateValue(_slotKey) == 2)
 		_scriptManager->setStateValue(_slotKey, 0);
 
-  debug(3,"Created Action: Music, slotKey %d, type %u, file %24s, note %u, volume %d", _slotKey, type, fileNameBuffer, _note, _volume->getValue());
+  debug(2,"Created Action: Music, slotKey %d, type %u, file %24s, note %u, volume %d, %s", _slotKey, type, fileNameBuffer, _note, _volume->getValue(), _loop ? "looping" : "");
   debug(4,"Music script: %s", line.c_str());
 }
 
@@ -526,7 +527,7 @@ ActionMusic::~ActionMusic() {
 }
 
 bool ActionMusic::execute() {
-  debug(3,"Executing Action: Music, slotKey %d, volume %d", _slotKey, _volume->getValue());
+  debug(2,"Executing Action: Music, slotKey %d, volume %d", _slotKey, _volume->getValue());
 	if (_scriptManager->getSideFX(_slotKey)) {
 		_scriptManager->killSideFx(_slotKey);
 		_scriptManager->setStateValue(_slotKey, 2);


Commit: 7d46f3f29e4385a8b2f9b17bd6b706e13c376b2b
    https://github.com/scummvm/scummvm/commit/7d46f3f29e4385a8b2f9b17bd6b706e13c376b2b
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:58+02:00

Commit Message:
ZVISION: Fix stuttering audio bug in ZGI room tp1e (invisible bridge guy)

Changed paths:
    engines/zvision/scripting/scr_file_handling.cpp
    engines/zvision/scripting/script_manager.h


diff --git a/engines/zvision/scripting/scr_file_handling.cpp b/engines/zvision/scripting/scr_file_handling.cpp
index 62e41ea3ad1..6dd85c573c6 100644
--- a/engines/zvision/scripting/scr_file_handling.cpp
+++ b/engines/zvision/scripting/scr_file_handling.cpp
@@ -103,7 +103,7 @@ void ScriptManager::parsePuzzle(Puzzle *puzzle, Common::SeekableReadStream &stre
 		if (line.matchString("criteria {", true))
 			parseCriteria(stream, puzzle->criteriaList, puzzle->key);
 		else if (line.matchString("results {", true)) {
-			parseResults(stream, puzzle->resultActions);
+			parseResults(stream, puzzle->resultActions, puzzle->key);
 
 			// WORKAROUND for a script bug in Zork Nemesis, room ve5e (tuning
 			// fork box closeup). If the player leaves the screen while the
@@ -130,6 +130,7 @@ void ScriptManager::parsePuzzle(Puzzle *puzzle, Common::SeekableReadStream &stre
 			// version doesn't have a separate room for the cutscene.
 			else if (_engine->getGameId() == GID_GRANDINQUISITOR && (_engine->getFeatures() & ADGF_DVD) && puzzle->key == 10836)
 				puzzle->resultActions.push_front(new ActionAssign(_engine, 11, "10803, 0"));
+
 		} 
 		else if (line.matchString("flags {", true))
 			setStateFlag(puzzle->key, parseFlags(stream));
@@ -267,7 +268,7 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 	return true;
 }
 
-void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::List<ResultAction *> &actionList) const {
+void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::List<ResultAction *> &actionList, uint32 key) const {
 	// Loop until we find the closing brace
 	Common::String line = stream.readLine();
 	trimCommentsAndWhiteSpace(&line);
@@ -346,7 +347,14 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 				} else if (act.matchString("attenuate", true)) {
 					actionList.push_back(new ActionAttenuate(_engine, slot, args));
 				} else if (act.matchString("assign", true)) {
-					actionList.push_back(new ActionAssign(_engine, slot, args));
+	        if (_engine->getGameId() == GID_GRANDINQUISITOR && key == 17761) {
+	          // WORKAROUND for a script bug in Zork: Grand Inquisitor, room tp1e.
+            // Background looping sound effect continuously restarts on every game cycle.
+            // This is caused by resetting itself to zero as a result of itself.
+            // Simple fix is to simply not generate this result assignment action at all.
+	        }
+	        else 
+  					actionList.push_back(new ActionAssign(_engine, slot, args));
 				} else if (act.matchString("change_location", true)) {
 					actionList.push_back(new ActionChangeLocation(_engine, slot, args));
 				} else if (act.matchString("crossfade", true)) {
diff --git a/engines/zvision/scripting/script_manager.h b/engines/zvision/scripting/script_manager.h
index 5311a746bff..4efd0c93f19 100644
--- a/engines/zvision/scripting/script_manager.h
+++ b/engines/zvision/scripting/script_manager.h
@@ -344,9 +344,10 @@ private:
 	 *
 	 * @param stream        Scr file stream
 	 * @param actionList    The list where the results will be added
+	 * @param key           Puzzle key (for workarounds)
 	 * @return              Created Results object
 	 */
-	void parseResults(Common::SeekableReadStream &stream, Common::List<ResultAction *> &actionList) const;
+	void parseResults(Common::SeekableReadStream &stream, Common::List<ResultAction *> &actionList, uint32 key) const;
 
 	/**
 	 * Helper method for parsePuzzle. Parses the stream into a bitwise or of the StateFlags enum


Commit: e444f4b415f6eaf5f5dce9c54bbb850483a859c3
    https://github.com/scummvm/scummvm/commit/e444f4b415f6eaf5f5dce9c54bbb850483a859c3
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:58+02:00

Commit Message:
ZVISION: Workaround added for ZGI script bug.
Castle heartbeat never terminated upon leaving location.
Cleaned up workaround code.

Changed paths:
    engines/zvision/scripting/scr_file_handling.cpp


diff --git a/engines/zvision/scripting/scr_file_handling.cpp b/engines/zvision/scripting/scr_file_handling.cpp
index 6dd85c573c6..f42ec387f72 100644
--- a/engines/zvision/scripting/scr_file_handling.cpp
+++ b/engines/zvision/scripting/scr_file_handling.cpp
@@ -104,33 +104,54 @@ void ScriptManager::parsePuzzle(Puzzle *puzzle, Common::SeekableReadStream &stre
 			parseCriteria(stream, puzzle->criteriaList, puzzle->key);
 		else if (line.matchString("results {", true)) {
 			parseResults(stream, puzzle->resultActions, puzzle->key);
-
-			// WORKAROUND for a script bug in Zork Nemesis, room ve5e (tuning
-			// fork box closeup). If the player leaves the screen while the
-			// box is open, puzzle 19398 shows the animation where the box
-			// closes, but the box state (state variable 19397) is not updated.
-			// We insert the missing assignment for the box state here.
-			// Fixes bug #6803.
-			if (_engine->getGameId() == GID_NEMESIS && puzzle->key == 19398)
-				puzzle->resultActions.push_back(new ActionAssign(_engine, 11, "19397, 0"));
-
-			// WORKAROUND for bug #10604. If the player is looking at the
-			// cigar box when Antharia Jack returns to examine the lamp,
-			// pp1f_video_flag remains 1. Later, when the player returns
-			// to pick up the lantern, the game will try to play the
-			// cutscene again, but since that script has already been
-			// run the player gets stuck in a dark room instead. We have
-			// to add the assignment action to the front, or it won't be
-			// reached because changing the location terminates the script.
-			//
-			// Fixing it this way only keeps the bug from happening. It
-			// will not repair old savegames.
-			//
-			// Note that the bug only affects the DVD version. The CD
-			// version doesn't have a separate room for the cutscene.
-			else if (_engine->getGameId() == GID_GRANDINQUISITOR && (_engine->getFeatures() & ADGF_DVD) && puzzle->key == 10836)
-				puzzle->resultActions.push_front(new ActionAssign(_engine, 11, "10803, 0"));
-
+      //WORKAROUNDS:
+      switch(_engine->getGameId()) {
+        case GID_NEMESIS: {
+			      // WORKAROUND for a script bug in Zork Nemesis, room ve5e (tuning
+			      // fork box closeup). If the player leaves the screen while the
+			      // box is open, puzzle 19398 shows the animation where the box
+			      // closes, but the box state (state variable 19397) is not updated.
+			      // We insert the missing assignment for the box state here.
+			      // Fixes bug #6803.
+			      if (puzzle->key == 19398)
+				      puzzle->resultActions.push_back(new ActionAssign(_engine, 11, "19397, 0"));
+			    }
+          break;
+        case GID_GRANDINQUISITOR: {
+			      switch(puzzle->key) {
+			        case 10836:
+			          // WORKAROUND for bug #10604. If the player is looking at the
+			          // cigar box when Antharia Jack returns to examine the lamp,
+			          // pp1f_video_flag remains 1. Later, when the player returns
+			          // to pick up the lantern, the game will try to play the
+			          // cutscene again, but since that script has already been
+			          // run the player gets stuck in a dark room instead. We have
+			          // to add the assignment action to the front, or it won't be
+			          // reached because changing the location terminates the script.
+			          //
+			          // Fixing it this way only keeps the bug from happening. It
+			          // will not repair old savegames.
+			          //
+			          // Note that the bug only affects the DVD version. The CD
+			          // version doesn't have a separate room for the cutscene.
+			          if (_engine->getFeatures() & ADGF_DVD)
+				          puzzle->resultActions.push_front(new ActionAssign(_engine, 11, "10803, 0"));
+			          break;
+              // WORKAROUND for a script bug in Zork: Grand Inquisitor, room dc10.
+              // Background heartbeat sound effect never terminates upon location change.
+			        case 2341:
+			        case 2344:
+			        case 17545:
+      					puzzle->resultActions.push_front(new ActionKill(_engine, 11, "02310"));
+      					break;
+      				default:
+      				  break;
+			      }
+		      }
+          break;
+        default:
+          break;
+      }
 		} 
 		else if (line.matchString("flags {", true))
 			setStateFlag(puzzle->key, parseFlags(stream));
@@ -157,6 +178,7 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 	// Create a new List to hold the CriteriaEntries
 	criteriaList.push_back(Common::List<Puzzle::CriteriaEntry>());
 	
+	//WORKAROUNDS
   switch(_engine->getGameId()) {
     case GID_NEMESIS:
 	    // WORKAROUND for a script bug in Zork: Nemesis, room td9e (fist puzzle)
@@ -430,7 +452,14 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 				} else if (act.matchString("ttytext", true)) {
 					actionList.push_back(new ActionTtyText(_engine, slot, args));
 				} else if (act.matchString("universe_music", true)) {
-					actionList.push_back(new ActionMusic(_engine, slot, args, true));
+          if (_engine->getGameId() == GID_GRANDINQUISITOR && slot == 2310 && false) { //DISABLED - not effective, sound stops on all zoom-ins for some reason?
+          // WORKAROUND for a script bug in Zork: Grand Inquisitor, room dc10.
+          // Background looping sound effect never terminates upon location change.
+          // Seems that it should have been "music" instead of "universe_music."
+			      actionList.push_back(new ActionMusic(_engine, slot, args, false));
+          }
+          else 
+				    actionList.push_back(new ActionMusic(_engine, slot, args, true));
 				} else if (act.matchString("copy_file", true)) {
 					// Not used. Purposely left empty
 				} else {


Commit: 8daa9f639d0c700a2bdb84ca2d343cb0c340f649
    https://github.com/scummvm/scummvm/commit/8daa9f639d0c700a2bdb84ca2d343cb0c340f649
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:58+02:00

Commit Message:
ZVISION: Fix bug that caused some sounds not to play upon restoring a game in certain locations.

Changed paths:
    engines/zvision/scripting/actions.cpp


diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index 76afc47d093..63d28c23338 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -94,6 +94,7 @@ ActionAssign::~ActionAssign() {
 }
 
 bool ActionAssign::execute() {
+  debug(2,"[%d] = %d", _key, _value->getValue());
 	_scriptManager->setStateValue(_key, _value->getValue());
 	return true;
 }
@@ -110,13 +111,13 @@ ActionAttenuate::ActionAttenuate(ZVision *engine, int32 slotKey, const Common::S
 	_attenuation = 0;
 
 	sscanf(line.c_str(), "%u, %d", &_key, &_attenuation);
-  debug(1,"Created Action: Attenuate, slotKey %d", _slotKey);
-  debug(2,"Attenuate script: %s", line.c_str());
-  debug(2,"Attenuate parameters: key1 %d, attenuation %d", _key, _attenuation);
+  debug(3,"Created Action: Attenuate, slotKey %d", _slotKey);
+  debug(3,"Attenuate script: %s", line.c_str());
+  debug(3,"Attenuate parameters: key1 %d, attenuation %d", _key, _attenuation);
 }
 
 bool ActionAttenuate::execute() {
-  debug(1,"Executing Action: Attenuate, slotkey %d", _slotKey);
+  debug(3,"Executing Action: Attenuate, slotkey %d", _slotKey);
 	ScriptingEffect *fx = _scriptManager->getSideFX(_key);
 	if (fx && fx->getType() == ScriptingEffect::SCRIPTING_EFFECT_AUDIO) {
 		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
@@ -163,13 +164,13 @@ ActionCrossfade::ActionCrossfade(ZVision *engine, int32 slotKey, const Common::S
 	sscanf(line.c_str(),
 	       "%u %u %d %d %d %d %d",
 	       &_keyOne, &_keyTwo, &_oneStartVolume, &_twoStartVolume, &_oneEndVolume, &_twoEndVolume, &_timeInMillis);
-  debug(2,"Created Action: CrossFade, slotKey %d", _slotKey);
-  debug(2,"Crossfade script: %s", line.c_str());
-  debug(2,"Crossfade parameters: key1 %u, key2 %u, startVol1 %d, startVol2 %d, endVol1 %d, endVol2 %d, time %dms", _keyOne, _keyTwo, _oneStartVolume, _twoStartVolume, _oneEndVolume, _twoEndVolume, _timeInMillis);
+  debug(3,"Created Action: CrossFade, slotKey %d", _slotKey);
+  debug(3,"Crossfade script: %s", line.c_str());
+  debug(3,"Crossfade parameters: key1 %u, key2 %u, startVol1 %d, startVol2 %d, endVol1 %d, endVol2 %d, time %dms", _keyOne, _keyTwo, _oneStartVolume, _twoStartVolume, _oneEndVolume, _twoEndVolume, _timeInMillis);
 }
 
 bool ActionCrossfade::execute() {
-  debug(2,"Executing Action: CrossFade, slotkey %d", _slotKey);
+  debug(3,"Executing Action: CrossFade, slotkey %d", _slotKey);
 	if (_keyOne) {
 		ScriptingEffect *fx = _scriptManager->getSideFX(_keyOne);
 		if (fx && fx->getType() == ScriptingEffect::SCRIPTING_EFFECT_AUDIO) {
@@ -237,7 +238,7 @@ ActionDelayRender::ActionDelayRender(ZVision *engine, int32 slotKey, const Commo
 }
 
 bool ActionDelayRender::execute() {
-  debug(2,"Executing Action: DelayRender");
+  debug(3,"Executing Action: DelayRender");
 	_engine->setRenderDelay(_framesToDelay);
 	return true;
 }
@@ -285,11 +286,11 @@ bool ActionDisplayMessage::execute() {
 
 ActionDissolve::ActionDissolve(ZVision *engine) :
 	ResultAction(engine, 0) {
-  debug(1,"Created action: Dissolve");
+  debug(3,"Created action: Dissolve");
 }
 
 bool ActionDissolve::execute() {
-  debug(1,"Executing action: Dissolve");
+  debug(3,"Executing action: Dissolve");
 	// Cause black screen flick
 	// Not ideal.  Original engine used a softer dissolve effect; simply turning the screen black is jarring, so disabled for now.
 	//_engine->getRenderManager()->bkgFill(0, 0, 0); //TODO - reimplement this?  
@@ -317,7 +318,7 @@ ActionDistort::~ActionDistort() {
 }
 
 bool ActionDistort::execute() {
-  debug(2,"Executing Action: Distort");
+  debug(3,"Executing Action: Distort");
 	if (_scriptManager->getSideFX(_distSlot))
 		return true;
 
@@ -437,13 +438,16 @@ ActionKill::ActionKill(ZVision *engine, int32 slotKey, const Common::String &lin
 			_type = ScriptingEffect::SCRIPTING_EFFECT_ALL;
 	} else
 		_key = atoi(keytype);
+  debug(3,"Created Action: Kill, slotKey %d, type %s, target slotKey %d", _slotKey, keytype, _key);
 }
 
 bool ActionKill::execute() {
 	if (_type)
 		_scriptManager->killSideFxType((ScriptingEffect::ScriptingEffectType)_type);
-	else
+	else {
+    debug(2,"Executing Action: Kill, slotKey %d, target slotKey %d", _slotKey, _key);
 		_scriptManager->killSideFx(_key);
+	}
 	return true;
 }
 
@@ -515,7 +519,15 @@ ActionMusic::ActionMusic(ZVision *engine, int32 slotKey, const Common::String &l
 	// sound effect finishes. Fixes script bug #6794.
 	if (engine->getGameId() == GID_NEMESIS && _slotKey == 14822 && _scriptManager->getStateValue(_slotKey) == 2)
 		_scriptManager->setStateValue(_slotKey, 0);
-
+		
+	//Ensure MusicNodes that were active when game was saved are recreated when it is loaded.
+	//Certain game scripts can become locked-up if this is not the case.
+  if(_engine->getScriptManager()->getStateValue(_slotKey) == 1)
+    if(!_scriptManager->getSideFX(_slotKey)) {
+    debug(1, "Recreating missing musicnode, slotkey %d", _slotKey);
+    execute();
+  }
+      
   debug(2,"Created Action: Music, slotKey %d, type %u, file %24s, note %u, volume %d, %s", _slotKey, type, fileNameBuffer, _note, _volume->getValue(), _loop ? "looping" : "");
   debug(4,"Music script: %s", line.c_str());
 }
@@ -524,6 +536,7 @@ ActionMusic::~ActionMusic() {
 	if (!_universe)
 		_scriptManager->killSideFx(_slotKey);
 	delete _volume;
+  debug(2,"Destroyed Action: %sMusic, slotkey %d", _universe ? "Universe_" : "", _slotKey);
 }
 
 bool ActionMusic::execute() {
@@ -566,24 +579,24 @@ ActionPanTrack::ActionPanTrack(ZVision *engine, int32 slotKey, const Common::Str
 	_mag = mag;
 	if(_resetMusicNode) {
 	  if(_scriptManager->getStateValue(_musicSlot) != 2) {
-	    debug(2,"Forcing musicSlot %d to 2", _musicSlot);
+	    debug(3,"Forcing musicSlot %d to 2", _musicSlot);
       _scriptManager->setStateValue(_musicSlot, 2); //Not all original game pan_track scripts trigger correctly unless this is set!
     }
     else
-      debug(2,"musicSlot %d already set to 2", _musicSlot);
+      debug(3,"musicSlot %d already set to 2", _musicSlot);
   }
   else
-    debug(2,"NOT forcing musicSlot %d to 2", _musicSlot);
-  debug(2,"Created Action: PanTrack, slotkey %d, musicSlot %u, pos %d, mag %d", _slotKey, _musicSlot, _pos, _mag);
+    debug(3,"NOT forcing musicSlot %d to 2", _musicSlot);
+  debug(3,"Created Action: PanTrack, slotkey %d, musicSlot %u, pos %d, mag %d", _slotKey, _musicSlot, _pos, _mag);
 }
 
 ActionPanTrack::~ActionPanTrack() {
 	_scriptManager->killSideFx(_slotKey);
-  debug(2,"Destroyed Action: PanTrack, slotkey %d", _slotKey);
+  debug(3,"Destroyed Action: PanTrack, slotkey %d", _slotKey);
 }
 
 bool ActionPanTrack::execute() {
-  debug(2,"Executing Action: PanTrack, slotkey %d, musicSlot %u, pos %d, mag %d", _slotKey, _musicSlot, _pos, _mag);
+  debug(3,"Executing Action: PanTrack, slotkey %d, musicSlot %u, pos %d, mag %d", _slotKey, _musicSlot, _pos, _mag);
 	if (_scriptManager->getSideFX(_slotKey))
 		return true;
 	_scriptManager->addSideFX(new PanTrackNode(_engine, _slotKey, _musicSlot, _pos, _mag, _resetMixerOnDelete, _staticScreen));
@@ -945,7 +958,7 @@ ActionStop::ActionStop(ZVision *engine, int32 slotKey, const Common::String &lin
 }
 
 bool ActionStop::execute() {
-  debug(2,"Executing Action: Stop");
+  debug(2,"Executing Action: Stop, key %d", _key);
 	_scriptManager->stopSideFx(_key);
 	return true;
 }
@@ -969,11 +982,11 @@ ActionStreamVideo::ActionStreamVideo(ZVision *engine, int32 slotKey, const Commo
 }
 
 bool ActionStreamVideo::execute() {
-  debug(2,"Executing video stream");
+  debug(3,"Executing video stream");
 	Video::VideoDecoder *decoder;
 	Common::Rect destRect = Common::Rect(_x1, _y1, _x2 + 1, _y2 + 1);
 	Common::Rect srcRect = Common::Rect(0,0);
-  debug(2,"Streaming video original scripted destination left=%d, top=%d, right=%d, bottom=%d", destRect.left, destRect.top, destRect.right, destRect.bottom);
+  debug(3,"Streaming video original scripted destination left=%d, top=%d, right=%d, bottom=%d", destRect.left, destRect.top, destRect.right, destRect.bottom);
 	Common::String subname = _fileName.baseName();
 	subname.setChar('s', subname.size() - 3);
 	subname.setChar('u', subname.size() - 2);
@@ -1036,7 +1049,7 @@ bool ActionStreamVideo::execute() {
 	_engine->getCursorManager()->showMouse(true);
   _engine->getSubtitleManager()->destroy(sub);
   _engine->setRenderDelay(2); //Necessary for avoiding redraw of previous scene between sequential videos (eg totemization sequence in ZGI) & when changing location right after a video (e.g. opening temple door in Nemesis)
-  debug(2,"Completed executing video stream");
+  debug(3,"Completed executing video stream");
 	return true;
 }
 
@@ -1054,7 +1067,7 @@ ActionSyncSound::ActionSyncSound(ZVision *engine, int32 slotKey, const Common::S
 }
 
 bool ActionSyncSound::execute() {
-  debug(2,"Executing Action: SyncSound");
+  debug(3,"Executing Action: SyncSound");
 	ScriptingEffect *fx = _scriptManager->getSideFX(_syncto);
 	if (!fx)
 		return true;


Commit: 35002be5ab852af07026081b13cde242547a2de9
    https://github.com/scummvm/scummvm/commit/35002be5ab852af07026081b13cde242547a2de9
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:58+02:00

Commit Message:
ZVISION: Amend 3D sound option behaviour.
Now disables directional audio but still applies nonlinear volume profile.

Changed paths:
    engines/zvision/scripting/effects/music_effect.cpp


diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 504f8159147..7c42e6e3517 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -46,6 +46,8 @@ void MusicNodeBASE::setDirection(Math::Angle azimuth, uint8 magnitude) {
     _directionality = magnitude;
     _balance = ((int)(127*_azimuth.getSine())*_directionality)/255;
   }
+  else
+    setBalance(0);
 	updateMixer();
 }
 
@@ -58,9 +60,10 @@ void MusicNodeBASE::setBalance(int8 balance) {
 
 void MusicNodeBASE::updateMixer() {
   if(_engine->getScriptManager()->getStateValue(StateKey_Qsound) >= 1)
-    volumeOut = _engine->getVolumeManager()->convert(_volume, _azimuth, _directionality);  //Apply volume profile and then attenuate according to azimuth
+    volumeOut = _engine->getVolumeManager()->convert(_volume, _azimuth, _directionality);  //Apply game-specific volume profile and then attenuate according to azimuth
   else
-    volumeOut = _engine->getVolumeManager()->convert(_volume, kVolumeLinear);  //Apply linear volume profile and ignore azimuth
+//    volumeOut = _engine->getVolumeManager()->convert(_volume, kVolumeLinear);  //Apply linear volume profile and ignore azimuth
+    volumeOut = _engine->getVolumeManager()->convert(_volume);  //Apply game-specific volume profile and ignore azimuth
   outputMixer();
 }
 


Commit: f9565f0b00fb94943c15dc42f3f33bcd4524c7c6
    https://github.com/scummvm/scummvm/commit/f9565f0b00fb94943c15dc42f3f33bcd4524c7c6
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:58+02:00

Commit Message:
ZVISION: Lowered ZGI inventory & spell scrollbar periods.

Changed paths:
    engines/zvision/scripting/menu.cpp
    engines/zvision/scripting/menu.h


diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index 29d6027db85..6e897eff06f 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -212,8 +212,8 @@ void MenuManager::setFocus(int8 currentFocus) {
 
 MenuZGI::MenuZGI(ZVision *engine, const Common::Rect menuArea) :
 	MenuManager(engine, menuArea, zgiParams),
-	itemsScroller(Common::Point(0,0), Common::Point(wSideMenuTab-wSideMenu,0), 1000),
-	magicScroller(Common::Point(-wSideMenu,0), Common::Point(-wSideMenuTab,0), 1000),
+	itemsScroller(Common::Point(0,0), Common::Point(wSideMenuTab-wSideMenu,0), sideMenuPeriod),
+	magicScroller(Common::Point(-wSideMenu,0), Common::Point(-wSideMenuTab,0), sideMenuPeriod),
 	itemsOrigin(menuArea.left, menuArea.top),
 	magicOrigin(menuArea.right, menuArea.top) {
 
diff --git a/engines/zvision/scripting/menu.h b/engines/zvision/scripting/menu.h
index 6e4c96bbb41..23ca91d8cad 100644
--- a/engines/zvision/scripting/menu.h
+++ b/engines/zvision/scripting/menu.h
@@ -164,6 +164,8 @@ private:
 	static const uint16 wSideMenuTab = 20;
   static const int16 magicWidth = 47;
 
+  const int16 sideMenuPeriod = 300;
+
   Scroller itemsScroller, magicScroller;
 
   const Common::Point magicOrigin;


Commit: 6a135edfef37d2b374ac92f797ea547fcc9d2ca3
    https://github.com/scummvm/scummvm/commit/6a135edfef37d2b374ac92f797ea547fcc9d2ca3
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:58+02:00

Commit Message:
GRAPHICS: Improve FrameLimiter initialization code.
Now possible to initialize without re-specifying FPS.
More resistant to DBZ errors.

Changed paths:
    graphics/framelimiter.cpp
    graphics/framelimiter.h


diff --git a/graphics/framelimiter.cpp b/graphics/framelimiter.cpp
index 716c0c4aac4..6d215b306d9 100644
--- a/graphics/framelimiter.cpp
+++ b/graphics/framelimiter.cpp
@@ -37,13 +37,16 @@ FrameLimiter::FrameLimiter(OSystem *system, const uint framerate, const bool def
   initialize(framerate);
 }
 
-void FrameLimiter::initialize(const uint framerate) {
-	_enabled =  (framerate != 0) && !(_deferToVsync && _system->getFeatureState(OSystem::kFeatureVSync));
-	if (_enabled)
-		frameLimit = 1000.0f / CLIP<uint>(framerate, 1, 100);
+void FrameLimiter::initialize() {
+	_enabled =  (frameLimit != 0) && !(_deferToVsync && _system->getFeatureState(OSystem::kFeatureVSync));
 	frameDuration = frameLimit;
 };
 
+void FrameLimiter::initialize(const uint framerate) {
+	frameLimit = (framerate > 0) ? 1000.0f / CLIP<uint>(framerate, 1, 100) : 0;
+  initialize();
+};
+
 uint FrameLimiter::startFrame() {
 	now = _system->getMillis();
 	if (frameStart != 0) {
diff --git a/graphics/framelimiter.h b/graphics/framelimiter.h
index 58f3c5fd0c5..c4eec34e778 100644
--- a/graphics/framelimiter.h
+++ b/graphics/framelimiter.h
@@ -43,6 +43,7 @@ public:
 /**
  * Always call this after instantiating Screen & calling initGraphics(), to ensure Vsync status is detected correctly!
  */
+  void initialize();
 	void initialize(const uint framerate);
 
 /**


Commit: 3e392fd0d16e63cb91d988248bbd5a25294df29e
    https://github.com/scummvm/scummvm/commit/3e392fd0d16e63cb91d988248bbd5a25294df29e
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:58+02:00

Commit Message:
ZVISION: Fix framerate limiter functionality in non-Vsync mode.
Ensure pan speed is unaffected by status of Vsync and doubleFPS options.

Changed paths:
    engines/zvision/graphics/render_manager.cpp


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 64c58674d3c..2eaae5307eb 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -166,6 +166,7 @@ void RenderManager::initialize(bool hiRes) {
   //Set hardware/window resolution
   debug(1,"_screen.w = %d, _screen.h = %d", _screen.w, _screen.h);
   initGraphics(_screen.w, _screen.h, &_engine->_screenPixelFormat);
+  frameLimiter.initialize();
 	debug(1,"Render manager initialized");
 }
 
@@ -243,7 +244,7 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
     debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
     if(immediate) {
       frameLimiter.startFrame();
-      debug(5,"Updating screen");
+      debug(5,"Updating screen, immediate");
       _screen.update();
       debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
       debug(10,"~renderSceneToScreen, immediate");
@@ -252,7 +253,7 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
     else if (_engine->canRender()) {
       frameLimiter.delayBeforeSwap();
       frameLimiter.startFrame();
-      debug(5,"Updating screen");
+      debug(5,"Updating screen, frame limited");
       _screen.update();
       debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
       debug(10,"~renderSceneToScreen, frame limited");
@@ -1006,7 +1007,7 @@ void RenderManager::bkgFill(uint8 r, uint8 g, uint8 b) {
 void RenderManager::updateRotation() {
 	int16 _velocity = _engine->getMouseVelocity() + _engine->getKeyboardVelocity();
 	ScriptManager *scriptManager = _engine->getScriptManager();
-	if (_doubleFPS)
+	if (_doubleFPS | !frameLimiter.isEnabled()) //Assuming 60fps when in Vsync mode.
 		_velocity /= 2;
 	if (_velocity) {
 		switch(_renderTable.getRenderState()) {


Commit: f7f45f55e9e1275a62ef0a46acf3ff5e9574318e
    https://github.com/scummvm/scummvm/commit/f7f45f55e9e1275a62ef0a46acf3ff5e9574318e
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:58+02:00

Commit Message:
ZVISION: Disabled vestigial development testing code in RenderTable.

Changed paths:
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h


diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index 28e3bbedefc..8cbb3745adc 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -200,8 +200,8 @@ void RenderTable::generateRenderTable() {
 
 void RenderTable::generateLookupTable(bool tilt) {
   debug(1,"Generating %s lookup table.", tilt ? "tilt" : "panorama");
-	debug(1,"halfWidth %f, halfHeight %f", halfWidth, halfHeight);
-	debug(1,"halfRows %d, halfColumns %d", halfRows, halfColumns);
+	debug(5,"halfWidth %f, halfHeight %f", halfWidth, halfHeight);
+	debug(5,"halfRows %d, halfColumns %d", halfRows, halfColumns);
   uint32 generationTime = _system->getMillis();
 	float alpha, cosAlpha, polarCoordInCylinderCoords, linearCoordInCylinderCoords, cylinderRadius, xOffset, yOffset;
 	uint32 indexTL, indexBL, indexTR, indexBR;
@@ -223,13 +223,16 @@ void RenderTable::generateLookupTable(bool tilt) {
 		linearCoordInCylinderCoords = halfLinearSize + ((float)linearCoord - halfLinearSize) * cosAlpha;
 		linearOffset = linearCoordInCylinderCoords - linearCoord;
     polarOffset = polarCoordInCylinderCoords - polarCoord;
+/*
     bool _printDebug = (Common::Point(x,y)==testPixel);
     if(_printDebug) {
-      debug(2,"\tGenerating test pixel %d, %d", x, y);
-      debug(2,"\tOffsets %f,%f", xOffset, yOffset);
-    } 
+      debug(5,"\tGenerating test pixel %d, %d", x, y);
+      debug(5,"\tOffsets %f,%f", xOffset, yOffset);
+    }
+*/ 
 		// Only store the (x,y) offsets instead of the absolute positions
-		_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality, _printDebug);
+//		_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality, _printDebug);
+		_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality);
     //Transformation is both horizontally and vertically symmetrical about the camera axis,
     //We can thus save on trigonometric calculations by computing one quarter of the transformation matrix and then mirroring it in both X & Y:
 		_internalBuffer[indexBL] = _internalBuffer[indexTL];
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index 079791bda8d..ccb24aea097 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -38,17 +38,20 @@ public:
   
   float fX, fY, fTL, fTR, fBL, fBR;
   
-  bool _printDebug = false;
+//  bool _printDebug = false;
   
   FilterPixel() {};
-  FilterPixel(float x, float y, bool highQuality=false, bool printDebug=false) {
+//  FilterPixel(float x, float y, bool highQuality=false, bool printDebug=false) {
+  FilterPixel(float x, float y, bool highQuality=false) {
     Src.left = int16(floor(x));
     Src.right = int16(ceil(x));
 	  Src.top = int16(floor(y));
 	  Src.bottom = int16(ceil(y));
+/*
 	  _printDebug = printDebug;
     if(_printDebug)
-      debug(1,"\tTarget pixel offset: %f, %f", x, y);
+      debug(5,"\tTarget pixel offset: %f, %f", x, y);
+*/
     if(highQuality) {
       fX = x-(float)Src.left;
       fY = y-(float)Src.top;
@@ -56,15 +59,19 @@ public:
       fTR = fX*(1-fY);
       fBL = (1-fX)*fY;
       fBR = fX*fY;
+/*
       if(_printDebug)
-        debug(1,"fX: %f, fY: %f, fTL:%f, fTR:%f, fBL:%f, fBR:%f", fX, fY, fTL, fTR, fBL, fBR);
+        debug(5,"fX: %f, fY: %f, fTL:%f, fTR:%f, fBL:%f, fBR:%f", fX, fY, fTL, fTR, fBL, fBR);
+*/
     }
 	  else {
       //Nearest neighbour
 		  xDir = (x-Src.left) > 0.5f;
 		  yDir = (y-Src.top) > 0.5f;
+/*
       if(_printDebug)
-        debug(1,"\tNearest neighbour, xDir: 0x%X, yDir: 0x%X", xDir, yDir);
+        debug(5,"\tNearest neighbour, xDir: 0x%X, yDir: 0x%X", xDir, yDir);
+*/
 	  }
   };
   ~FilterPixel() {};
@@ -83,7 +90,7 @@ public:
 	RenderTable(ZVision *engine, uint numRows, uint numColumns, const Graphics::PixelFormat pixelFormat);
 	~RenderTable();
 	
-	Common::Point testPixel = Common::Point(255,0);
+//	Common::Point testPixel = Common::Point(255,0);
 
 public:
 	enum RenderState {


Commit: 7d875213684c5e06df252a09a87f76c924a23666
    https://github.com/scummvm/scummvm/commit/7d875213684c5e06df252a09a87f76c924a23666
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:58+02:00

Commit Message:
ZVISION: Restore functionality of "Main Menu" button in ZGI death screen.

Changed paths:
    engines/zvision/file/save_manager.cpp
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/scripting/script_manager.h


diff --git a/engines/zvision/file/save_manager.cpp b/engines/zvision/file/save_manager.cpp
index 972e16c3e48..257940f0154 100644
--- a/engines/zvision/file/save_manager.cpp
+++ b/engines/zvision/file/save_manager.cpp
@@ -113,9 +113,9 @@ void SaveManager::writeSaveGameHeader(Common::OutSaveFile *file, const Common::S
 
 Common::Error SaveManager::loadGame(int slot) {
 	Common::SeekableReadStream *saveFile = NULL;
-	if (slot >= 0)
-		saveFile = getSlotFile(slot);
-	else {
+	if (slot < 0) {
+  //Restart game, used by ZGI death screen only
+/*
 		saveFile = _engine->getSearchManager()->openFile("r.svr");
 		if (!saveFile) {
 			Common::File *restoreFile = new Common::File();
@@ -125,45 +125,52 @@ Common::Error SaveManager::loadGame(int slot) {
 			}
 			saveFile = restoreFile;
 		}
-	}
-	if (!saveFile)
-		return Common::kPathDoesNotExist;
-	// Read the header
-	SaveGameHeader header;
-	if (!readSaveGameHeader(saveFile, header))
-		return Common::kUnknownError;
-	ScriptManager *scriptManager = _engine->getScriptManager();
-	// Update the state table values
-	scriptManager->deserialize(saveFile);
-	delete saveFile;
-	if (_engine->getGameId() == GID_NEMESIS)  {
-    //Zork Nemesis has no in-game option to select panorama quality or animation options
-    //We set them here to ensure loaded games don't override current game configuration
-    scriptManager->setStateValue(StateKey_HighQuality, ConfMan.getBool("highquality"));
-    scriptManager->setStateValue(StateKey_NoTurnAnim, ConfMan.getBool("noanimwhileturning"));
-	  if(scriptManager->getCurrentLocation() == "tv2f") {
-		  // WORKAROUND for script bug #6793: location tv2f (stairs) has two states:
-		  // one at the top of the stairs, and one at the bottom. When the player
-		  // goes to the bottom of the stairs, the screen changes, and hotspot
-		  // 4652 (exit opposite the stairs) is enabled. However, the variable that
-		  // controls the state (2408) is reset when the player goes down the stairs.
-		  // Furthermore, the room's initialization script disables the stair exit
-		  // control (4652). This leads to an impossible situation, where all the
-		  // exit controls are disabled, and the player can't more anywhere. Thus,
-		  // when loading a game in that room, we check for that impossible
-		  // situation, which only occurs after the player has moved down the stairs,
-		  // and fix it here by setting the correct background, and enabling the
-		  // stair exit hotspot.
-		  if ((scriptManager->getStateFlag(2411) & Puzzle::DISABLED) &&
-			  (scriptManager->getStateFlag(2408) & Puzzle::DISABLED) &&
-			  (scriptManager->getStateFlag(4652) & Puzzle::DISABLED)) {
-			  _engine->getRenderManager()->setBackgroundImage("tv2fb21c.tga");
-			  scriptManager->unsetStateFlag(4652, Puzzle::DISABLED);
-		  }
+/*/
+    _engine->getScriptManager()->initialize(true);
+//*/
+	  return Common::kNoError;
+  }
+	else {
+	  saveFile = getSlotFile(slot);
+	  if (!saveFile)
+		  return Common::kPathDoesNotExist;
+	  // Read the header
+	  SaveGameHeader header;
+	  if (!readSaveGameHeader(saveFile, header))
+		  return Common::kUnknownError;
+	  ScriptManager *scriptManager = _engine->getScriptManager();
+	  // Update the state table values
+	  scriptManager->deserialize(saveFile);
+	  delete saveFile;
+	  if (_engine->getGameId() == GID_NEMESIS)  {
+      //Zork Nemesis has no in-game option to select panorama quality or animation options
+      //We set them here to ensure loaded games don't override current game configuration
+      scriptManager->setStateValue(StateKey_HighQuality, ConfMan.getBool("highquality"));
+      scriptManager->setStateValue(StateKey_NoTurnAnim, ConfMan.getBool("noanimwhileturning"));
+	    if(scriptManager->getCurrentLocation() == "tv2f") {
+		    // WORKAROUND for script bug #6793: location tv2f (stairs) has two states:
+		    // one at the top of the stairs, and one at the bottom. When the player
+		    // goes to the bottom of the stairs, the screen changes, and hotspot
+		    // 4652 (exit opposite the stairs) is enabled. However, the variable that
+		    // controls the state (2408) is reset when the player goes down the stairs.
+		    // Furthermore, the room's initialization script disables the stair exit
+		    // control (4652). This leads to an impossible situation, where all the
+		    // exit controls are disabled, and the player can't more anywhere. Thus,
+		    // when loading a game in that room, we check for that impossible
+		    // situation, which only occurs after the player has moved down the stairs,
+		    // and fix it here by setting the correct background, and enabling the
+		    // stair exit hotspot.
+		    if ((scriptManager->getStateFlag(2411) & Puzzle::DISABLED) &&
+			    (scriptManager->getStateFlag(2408) & Puzzle::DISABLED) &&
+			    (scriptManager->getStateFlag(4652) & Puzzle::DISABLED)) {
+			    _engine->getRenderManager()->setBackgroundImage("tv2fb21c.tga");
+			    scriptManager->unsetStateFlag(4652, Puzzle::DISABLED);
+		    }
+	    }
 	  }
-	}
-	g_engine->setTotalPlayTime(header.playTime * 1000);
-	return Common::kNoError;
+	  g_engine->setTotalPlayTime(header.playTime * 1000);
+	  return Common::kNoError;
+  }
 }
 
 bool SaveManager::readSaveGameHeader(Common::InSaveFile *in, SaveGameHeader &header, bool skipThumbnail) {
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index bf54e4564fb..7e702a11130 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -53,7 +53,11 @@ ScriptManager::~ScriptManager() {
 	_controlEvents.clear();
 }
 
-void ScriptManager::initialize() {
+void ScriptManager::initialize(bool restarted) {
+  if(restarted) {
+	  _globalState.clear();
+	  _globalStateFlags.clear();
+	}
 	cleanScriptScope(universe);
 	cleanScriptScope(world);
 	cleanScriptScope(room);
@@ -63,9 +67,31 @@ void ScriptManager::initialize() {
 	_currentLocation.room = 0;
 	_currentLocation.view = 0;
 	_changeLocationDelayCycles = 0;
+  if(restarted) {
+	  for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); iter++)
+		  delete(*iter);
+	  _activeSideFx.clear();
+	  _referenceTable.clear();
+	  switch(_engine->getGameId()) {
+      case GID_GRANDINQUISITOR:
+        //Bypass logo video
+        setStateValue(16966, 1);  
+        //Ensure post-logo screen redraw is not inhibited in CD version
+        setStateValue(5813, 1);
+        //Bypass additional logo videos in DVD version
+        setStateValue(19810, 1);
+        setStateValue(19848, 1);
+        break;
+      case GID_NEMESIS:
+      default:
+        break;
+    }
+	}
 	parseScrFile("universe.scr", universe);
 	changeLocation('g', 'a', 'r', 'y', 0);
 	_controlEvents.clear();
+	if(restarted)
+	  _engine->loadSettings();
 }
 
 void ScriptManager::update(uint deltaTimeMillis) {
diff --git a/engines/zvision/scripting/script_manager.h b/engines/zvision/scripting/script_manager.h
index 4efd0c93f19..67927b02fbc 100644
--- a/engines/zvision/scripting/script_manager.h
+++ b/engines/zvision/scripting/script_manager.h
@@ -197,7 +197,7 @@ private:
 	uint32 _currentlyFocusedControl;
 
 public:
-	void initialize();
+	void initialize(bool restarted = false);
 	void update(uint deltaTimeMillis);
 	void queuePuzzles(uint32 key);
 


Commit: 2afa00137ebba7f59a897e762a1e4515c8f29dfa
    https://github.com/scummvm/scummvm/commit/2afa00137ebba7f59a897e762a1e4515c8f29dfa
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:58+02:00

Commit Message:
ZVISION: Code cleanup to meet github workflow requirements.

Changed paths:
    engines/zvision/scripting/menu.cpp


diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index 6e897eff06f..82e2b81c78c 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -183,11 +183,11 @@ void MenuManager::process(uint32 deltatime) {
   	redrawAll();
   	redraw = false;
   }
-};
+}
 
 void MenuNemesis::redrawAll() {
   redrawMain();
-};
+}
 
 void MenuManager::redrawMain() {
   //Draw menu background
@@ -410,7 +410,7 @@ int MenuZGI::mouseOverItem(const Common::Point &Pos, int itemCount) {
 	  itemHotspot.translate(itemWidth,0);
   }
   return -1;
-};
+}
 
 int MenuZGI::mouseOverMagic(const Common::Point &Pos) {
   Common::Rect magicHotspot(28,hSideMenu);
@@ -422,7 +422,7 @@ int MenuZGI::mouseOverMagic(const Common::Point &Pos) {
   magicHotspot.translate(magicWidth,0);
   }
   return -1;
-};
+}
 
 void MenuZGI::process(uint32 deltatime) {
 	if(itemsScroller.update(deltatime)) {
@@ -456,7 +456,7 @@ void MenuZGI::redrawAll() {
         default:
 	        break;
       }
-};
+}
 
 void MenuZGI::redrawMagic() {
   const int16 yOrigin = _menuArea.width();


Commit: b582171e051b28f432b5ef246491bd3416fe5da8
    https://github.com/scummvm/scummvm/commit/b582171e051b28f432b5ef246491bd3416fe5da8
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:59+02:00

Commit Message:
GRAPHICS: Make FrameLimiter member variable names compliant with coding convention.

Changed paths:
    graphics/framelimiter.cpp
    graphics/framelimiter.h


diff --git a/graphics/framelimiter.cpp b/graphics/framelimiter.cpp
index 6d215b306d9..cc1df8e603d 100644
--- a/graphics/framelimiter.cpp
+++ b/graphics/framelimiter.cpp
@@ -27,52 +27,52 @@ namespace Graphics {
 FrameLimiter::FrameLimiter(OSystem *system, const uint framerate, const bool deferToVsync) :
 		_system(system),
 		_deferToVsync(deferToVsync),
-		frameStart(0),
-		frameLimit(0),
-		frameDuration(0),
-		drawStart(0),
-		drawDuration(0),
-		loopDuration(0),
-		delay(0) {
+		_frameStart(0),
+		_frameLimit(0),
+		_frameDuration(0),
+		_drawStart(0),
+		_drawDuration(0),
+		_loopDuration(0),
+		_delay(0) {
   initialize(framerate);
 }
 
 void FrameLimiter::initialize() {
-	_enabled =  (frameLimit != 0) && !(_deferToVsync && _system->getFeatureState(OSystem::kFeatureVSync));
-	frameDuration = frameLimit;
+	_enabled =  (_frameLimit != 0) && !(_deferToVsync && _system->getFeatureState(OSystem::kFeatureVSync));
+	_frameDuration = _frameLimit;
 };
 
 void FrameLimiter::initialize(const uint framerate) {
-	frameLimit = (framerate > 0) ? 1000.0f / CLIP<uint>(framerate, 1, 100) : 0;
+	_frameLimit = (framerate > 0) ? 1000.0f / CLIP<uint>(framerate, 1, 100) : 0;
   initialize();
 };
 
 uint FrameLimiter::startFrame() {
-	now = _system->getMillis();
-	if (frameStart != 0) {
-	  frameDuration = now - frameStart;
-    drawDuration = now - drawStart;
+	_now = _system->getMillis();
+	if (_frameStart != 0) {
+	  _frameDuration = _now - _frameStart;
+    _drawDuration = _now - _drawStart;
   }
-	frameStart = now;
-	return frameDuration;
+	_frameStart = _now;
+	return _frameDuration;
 }
 
 bool FrameLimiter::delayBeforeSwap() {
-  now = _system->getMillis();
-  loopDuration = now - frameStart;
+  _now = _system->getMillis();
+  _loopDuration = _now - _frameStart;
 	if(_enabled) {
 	  //delay = frameLimit - loopDuration;  //Original functionality, will tend to undershoot target framerate slightly due to finite screen.update() time.
-  	delay = frameLimit - (now - drawStart); //Ensure EXACTLY the specified frame duration has elapsed since last screen.update() was called.
-    if(delay > 0)
-  	  _system->delayMillis(delay);
+  	_delay = _frameLimit - (_now - _drawStart); //Ensure EXACTLY the specified frame duration has elapsed since last screen.update() was called.
+    if(_delay > 0)
+  	  _system->delayMillis(_delay);
 	}
-	drawStart = _system->getMillis();
-	return (delay < 0); //Check if frame is late
+	_drawStart = _system->getMillis();
+	return (_delay < 0); //Check if frame is late
 }
 
 void FrameLimiter::pause(bool pause) {
 	if (!pause)
-		frameStart = 0; // Ensure the frame duration value is consistent when resuming
+		_frameStart = 0; // Ensure the frame duration value is consistent when resuming
 }
 
 } // End of namespace Graphics
diff --git a/graphics/framelimiter.h b/graphics/framelimiter.h
index c4eec34e778..fa7fb595570 100644
--- a/graphics/framelimiter.h
+++ b/graphics/framelimiter.h
@@ -64,18 +64,18 @@ public:
  * Return duration of last whole frame, including game logic, frame limiter or Vsync delay (if any), and screen redraw time.
  * Specifically, this is the time between the last two successive startFrame() calls.
  */
-	uint getLastFrameDuration() const {return frameDuration;};
+	uint getLastFrameDuration() const {return _frameDuration;};
 /**
  * Return duration of last screen update
  * If Vsync is inactive, this value will just be the duration of the redraw process itself;
  * If Vsync is active, this value will encompass both the redraw time AND the delay between presenting the frame to redraw and the screen redraw actually starting.
  */
- 	uint getLastDrawDuration() const {return drawDuration;}; 
+ 	uint getLastDrawDuration() const {return _drawDuration;}; 
 /**
  * Return duration of last game logic loop
  * Specifically, this is the time from when startFrame() was last called to when delayBeforeSwap() was last called
  */
-	uint getLastLoopDuration() const {return loopDuration;};
+	uint getLastLoopDuration() const {return _loopDuration;};
 /**
  * If true, framelimiter is active and applying _system->delayMillis(delay) to maintain the specified FPS, if valid.
  * If false, framelimiter is inactive, either because supplied FPS was invalid or because Vsync is active.
@@ -87,14 +87,14 @@ private:
 	OSystem *_system;
 	bool _enabled;
 	bool _deferToVsync;
-	uint frameStart;  //Time at which screen update completed and startFrame() was called; start of next cycle of game logic
-  uint frameLimit;  //Target frame duration to achieve specified FPS
-  uint frameDuration; //Duration of previous frame between successive startFrame() calls; total game logic, delay (if any) and screen update time
-  uint drawStart;  //Time at which delayBeforeSwap() returns
-  uint drawDuration;  //Measured screen update time
-  uint loopDuration;  //Duration of last game logic cycle, from when startFrame() was called to when delayBeforeSwap() was called
-  int delay; //Time to delay before returning from delayBeforeSwap()
-  uint now; //Current time
+	uint _frameStart;  //Time at which screen update completed and startFrame() was called; start of next cycle of game logic
+  uint _frameLimit;  //Target frame duration to achieve specified FPS
+  uint _frameDuration; //Duration of previous frame between successive startFrame() calls; total game logic, delay (if any) and screen update time
+  uint _drawStart;  //Time at which delayBeforeSwap() returns
+  uint _drawDuration;  //Measured screen update time
+  uint _loopDuration;  //Duration of last game logic cycle, from when startFrame() was called to when delayBeforeSwap() was called
+  int _delay; //Time to delay before returning from delayBeforeSwap()
+  uint _now; //Current time
 };
 
 } // End of namespace Graphics


Commit: 45c0e3ffe68eef069155a88028dcb3380ddd00f3
    https://github.com/scummvm/scummvm/commit/45c0e3ffe68eef069155a88028dcb3380ddd00f3
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:59+02:00

Commit Message:
ZVISION: Code formatting & convention compliance.
Add "fall through" comments to switch statements.
Apply astyle with standard ScummVM parameters to all cpp & h files.
Manually readjust alignment of volume lookup arrays in volume_manager.cpp for readability.

Changed paths:
    engines/zvision/common/focus_list.h
    engines/zvision/common/scroller.cpp
    engines/zvision/common/scroller.h
    engines/zvision/core/console.cpp
    engines/zvision/core/events.cpp
    engines/zvision/detection_tables.h
    engines/zvision/file/save_manager.cpp
    engines/zvision/graphics/cursors/cursor.cpp
    engines/zvision/graphics/cursors/cursor_manager.cpp
    engines/zvision/graphics/effects/fog.cpp
    engines/zvision/graphics/graphics_effect.h
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h
    engines/zvision/metaengine.cpp
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/actions.h
    engines/zvision/scripting/control.cpp
    engines/zvision/scripting/controls/fist_control.h
    engines/zvision/scripting/controls/hotmov_control.h
    engines/zvision/scripting/controls/input_control.h
    engines/zvision/scripting/controls/lever_control.h
    engines/zvision/scripting/controls/safe_control.h
    engines/zvision/scripting/effects/animation_effect.cpp
    engines/zvision/scripting/effects/animation_effect.h
    engines/zvision/scripting/effects/distort_effect.cpp
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/effects/music_effect.h
    engines/zvision/scripting/effects/syncsound_effect.cpp
    engines/zvision/scripting/menu.cpp
    engines/zvision/scripting/menu.h
    engines/zvision/scripting/scr_file_handling.cpp
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/scripting/script_manager.h
    engines/zvision/sound/midi.cpp
    engines/zvision/sound/midi.h
    engines/zvision/sound/volume_manager.cpp
    engines/zvision/sound/volume_manager.h
    engines/zvision/sound/zork_raw.cpp
    engines/zvision/sound/zork_raw.h
    engines/zvision/text/subtitle_manager.cpp
    engines/zvision/text/subtitle_manager.h
    engines/zvision/text/text.cpp
    engines/zvision/text/truetype_font.cpp
    engines/zvision/video/rlf_decoder.cpp
    engines/zvision/video/rlf_decoder.h
    engines/zvision/video/video.cpp
    engines/zvision/video/zork_avi_decoder.cpp
    engines/zvision/zvision.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/common/focus_list.h b/engines/zvision/common/focus_list.h
index 795cf1fa773..99ff4961891 100644
--- a/engines/zvision/common/focus_list.h
+++ b/engines/zvision/common/focus_list.h
@@ -27,65 +27,65 @@
 template<typename T>
 class FocusList {
 private:
-  Common::Array<T> focus;
-  typedef uint _size_type;  //TODO - find a way to make this typedef inherit from the definition in Common::Array
+	Common::Array<T> focus;
+	typedef uint _size_type;  //TODO - find a way to make this typedef inherit from the definition in Common::Array
 public:
-  void set(T currentFocus) {
-    if(!focus.size())
-      focus.push_back(currentFocus);     
-    else {
-      if(focus.front() != currentFocus) {
-        Common::Array<T> buffer;
-        while(focus.size() > 0) {
-          if(focus.back() != currentFocus)
-            buffer.push_back(focus.back());
-          focus.pop_back();
-        }
-        focus.push_back(currentFocus);
-        while(buffer.size() > 0) {
-          focus.push_back(buffer.back());
-          buffer.pop_back();
-        }
-      }
-    }
-  }
+	void set(T currentFocus) {
+		if (!focus.size())
+			focus.push_back(currentFocus);
+		else {
+			if (focus.front() != currentFocus) {
+				Common::Array<T> buffer;
+				while (focus.size() > 0) {
+					if (focus.back() != currentFocus)
+						buffer.push_back(focus.back());
+					focus.pop_back();
+				}
+				focus.push_back(currentFocus);
+				while (buffer.size() > 0) {
+					focus.push_back(buffer.back());
+					buffer.pop_back();
+				}
+			}
+		}
+	}
+
+	T get(_size_type idx = 0) {
+		return focus[idx];
+	}
 
-  T get(_size_type idx=0) {
-    return focus[idx];
-  }
+	T front() {
+		return focus.front();
+	}
 
-  T front() {
-    return focus.front();
-  }
-  
 	T &operator[](_size_type idx) {
 		assert(idx < focus.size());
 		return focus[idx];
 	}
 
-  _size_type size() {
-    return focus.size();
-  }
-  
-  void clear() {
-    focus.clear();
-  }
-  
-  void remove(T value) {
-    if(focus.size()) {
-      Common::Array<T> buffer;
-      while(focus.size() > 0) {
-        if(focus.back() != value)
-          buffer.push_back(focus.back());
-        focus.pop_back();
-      }
-      while(buffer.size() > 0) {
-        focus.push_back(buffer.back());
-        buffer.pop_back();
-      }
-    }
-  }
-  
+	_size_type size() {
+		return focus.size();
+	}
+
+	void clear() {
+		focus.clear();
+	}
+
+	void remove(T value) {
+		if (focus.size()) {
+			Common::Array<T> buffer;
+			while (focus.size() > 0) {
+				if (focus.back() != value)
+					buffer.push_back(focus.back());
+				focus.pop_back();
+			}
+			while (buffer.size() > 0) {
+				focus.push_back(buffer.back());
+				buffer.pop_back();
+			}
+		}
+	}
+
 };
 
 #endif
diff --git a/engines/zvision/common/scroller.cpp b/engines/zvision/common/scroller.cpp
index d1b6eeec0a1..bfd1c6491fd 100644
--- a/engines/zvision/common/scroller.cpp
+++ b/engines/zvision/common/scroller.cpp
@@ -24,100 +24,98 @@
 namespace ZVision {
 
 LinearScroller::LinearScroller(const int16 activePos, const int16 idlePos, const int16 period) :
-  Pos(idlePos),
-  prevPos(idlePos),
-  _activePos(activePos),
-  _idlePos(idlePos),
-  deltaPos((int16)(activePos-idlePos)),
-  _period(period) {
+	Pos(idlePos),
+	prevPos(idlePos),
+	_activePos(activePos),
+	_idlePos(idlePos),
+	deltaPos((int16)(activePos - idlePos)),
+	_period(period) {
 }
 
 LinearScroller::~LinearScroller() {
 }
 
 bool LinearScroller::update(uint32 deltatime) {
-  prevPos = Pos;
-  if(_period != 0)
-    {
-    int16 targetPos;
-	  float dPos=0;
-	  if (_active)
-	    targetPos = _activePos;
-    else
-    	targetPos = _idlePos;
-    if (Pos != targetPos) {
-      dPos = (float)((int32)deltatime * (int32)deltaPos) / _period;
-      if((int16)dPos == 0) {
-        if(deltaPos > 0)
-          dPos = 1;
-        else
-          dPos = -1;
-      }
-    }   
-    if(!_active)
-      dPos = -dPos;
-    Pos += (int16)dPos;
-    if( (dPos == 0) || ( (dPos > 0) && (Pos > targetPos) ) || ( (dPos < 0) && (Pos < targetPos) ) )
-      Pos = targetPos;
-    moving = (Pos != targetPos);
-  }
-  else {
-    if(_active)
-      Pos = _activePos;
-    else
-      Pos = _idlePos;
-    moving = false;
-  } 
+	prevPos = Pos;
+	if (_period != 0) {
+		int16 targetPos;
+		float dPos = 0;
+		if (_active)
+			targetPos = _activePos;
+		else
+			targetPos = _idlePos;
+		if (Pos != targetPos) {
+			dPos = (float)((int32)deltatime * (int32)deltaPos) / _period;
+			if ((int16)dPos == 0) {
+				if (deltaPos > 0)
+					dPos = 1;
+				else
+					dPos = -1;
+			}
+		}
+		if (!_active)
+			dPos = -dPos;
+		Pos += (int16)dPos;
+		if ((dPos == 0) || ((dPos > 0) && (Pos > targetPos)) || ((dPos < 0) && (Pos < targetPos)))
+			Pos = targetPos;
+		moving = (Pos != targetPos);
+	} else {
+		if (_active)
+			Pos = _activePos;
+		else
+			Pos = _idlePos;
+		moving = false;
+	}
 	return (Pos != prevPos);  //True if redraw necessary
 }
 
 void LinearScroller::reset() {
-  setActive(false);
-  Pos = _idlePos;
+	setActive(false);
+	Pos = _idlePos;
 }
 
 void LinearScroller::setActive(bool active) {
-  _active = active;
+	_active = active;
 }
 
 bool LinearScroller::isMoving() {
-  return moving;
+	return moving;
 }
 
 
 Scroller::Scroller(const Common::Point &activePos, const Common::Point &idlePos, int16 period) :
-  Xscroller(activePos.x,idlePos.x,period), 
-  Yscroller(activePos.y,idlePos.y,period) {
-  Pos.x = Xscroller.Pos;
-  Pos.y = Yscroller.Pos;
+	Xscroller(activePos.x, idlePos.x, period),
+	Yscroller(activePos.y, idlePos.y, period) {
+	Pos.x = Xscroller.Pos;
+	Pos.y = Yscroller.Pos;
 }
 
 Scroller::~Scroller() {
 }
 
 void Scroller::reset() {
-  Xscroller.reset();
-  Yscroller.reset();
+	Xscroller.reset();
+	Yscroller.reset();
 };
 
 
 void Scroller::setActive(bool active) {
-  Xscroller.setActive(active);
-  Yscroller.setActive(active);
+	Xscroller.setActive(active);
+	Yscroller.setActive(active);
 }
 
 bool Scroller::isMoving() {
-  return Xscroller.isMoving() | Yscroller.isMoving();
+	return Xscroller.isMoving() | Yscroller.isMoving();
 }
 
 bool Scroller::update(uint32 deltatime) {
-  bool redraw = false;
-  if(Xscroller.update(deltatime))
-    redraw = true; 
-  if(Yscroller.update(deltatime))
-    redraw = true;
-  Pos.x = Xscroller.Pos;
-  Pos.y = Yscroller.Pos;
+	bool redraw = false;
+	if (Xscroller.update(deltatime))
+		redraw = true;
+	if (Yscroller.update(deltatime))
+		redraw = true;
+	Pos.x = Xscroller.Pos;
+	Pos.y = Yscroller.Pos;
 	return (redraw);
 }
 
diff --git a/engines/zvision/common/scroller.h b/engines/zvision/common/scroller.h
index d1ba89bab00..c2883056d1a 100644
--- a/engines/zvision/common/scroller.h
+++ b/engines/zvision/common/scroller.h
@@ -29,38 +29,38 @@ namespace ZVision {
 
 class LinearScroller {
 public:
-  LinearScroller(const int16 activePos, const int16 idlePos, const int16 period = 500);
-  ~LinearScroller();
-  void reset();
-  bool update(uint32 deltatime);  //Calculate updated position of scrolled graphics; return true if redraw is necessary.
-  void setActive(bool active);
-  bool isMoving();
-  int16 getPos();
+	LinearScroller(const int16 activePos, const int16 idlePos, const int16 period = 500);
+	~LinearScroller();
+	void reset();
+	bool update(uint32 deltatime);  //Calculate updated position of scrolled graphics; return true if redraw is necessary.
+	void setActive(bool active);
+	bool isMoving();
+	int16 getPos();
 
 	int16 Pos;
 	int16 prevPos;
 
 private:
-  bool _active = false;
-  bool moving = false;
-  const int16 _activePos;
-  const int16 _idlePos;
+	bool _active = false;
+	bool moving = false;
+	const int16 _activePos;
+	const int16 _idlePos;
 	const int16 deltaPos;
-  const int16 _period;
+	const int16 _period;
 };
 
 class Scroller {
 public:
-  Scroller(const Common::Point &activePos, const Common::Point &idlePos, const int16 period = 500);
-  ~Scroller();
-  void reset();
-  bool update(uint32 deltatime);  //Calculate updated position of scrolled graphics; return true if redraw is necessary.
-  void setActive(bool active);
-  bool isMoving();
+	Scroller(const Common::Point &activePos, const Common::Point &idlePos, const int16 period = 500);
+	~Scroller();
+	void reset();
+	bool update(uint32 deltatime);  //Calculate updated position of scrolled graphics; return true if redraw is necessary.
+	void setActive(bool active);
+	bool isMoving();
 	Common::Point Pos;
 
 private:
-  LinearScroller Xscroller, Yscroller;
+	LinearScroller Xscroller, Yscroller;
 };
 
 } // End of namespace ZVision
diff --git a/engines/zvision/core/console.cpp b/engines/zvision/core/console.cpp
index 0d9b78cd226..18c290c718a 100644
--- a/engines/zvision/core/console.cpp
+++ b/engines/zvision/core/console.cpp
@@ -140,10 +140,10 @@ bool Console::cmdRawToWav(int argc, const char **argv) {
 	output.writeUint32LE(file.size() * 2);
 	int16 *buffer = new int16[file.size()];
 	audioStream->readBuffer(buffer, file.size());
-#ifndef SCUMM_LITTLE_ENDIAN
+	#ifndef SCUMM_LITTLE_ENDIAN
 	for (int i = 0; i < file.size(); ++i)
 		buffer[i] = TO_LE_16(buffer[i]);
-#endif
+	#endif
 	output.write(buffer, file.size() * 2);
 
 	delete[] buffer;
@@ -204,7 +204,7 @@ bool Console::cmdLocation(int argc, const char **argv) {
 	Location curLocation = _engine->getScriptManager()->getCurrentLocation();
 	Common::String scrFile = Common::String::format("%c%c%c%c.scr", curLocation.world, curLocation.room, curLocation.node, curLocation.view);
 	debugPrintf("Current location: world '%c', room '%c', node '%c', view '%c', offset %d, script %s\n",
-				curLocation.world, curLocation.room, curLocation.node, curLocation.view, curLocation.offset, scrFile.c_str());
+	            curLocation.world, curLocation.room, curLocation.node, curLocation.view, curLocation.offset, scrFile.c_str());
 
 	if (argc != 6) {
 		debugPrintf("Use %s <char: world> <char: room> <char:node> <char:view> <int: x offset> to change your location\n", argv[0]);
diff --git a/engines/zvision/core/events.cpp b/engines/zvision/core/events.cpp
index 9f0764bbd8a..d1633273a34 100644
--- a/engines/zvision/core/events.cpp
+++ b/engines/zvision/core/events.cpp
@@ -80,10 +80,10 @@ void ZVision::cheatCodes(uint8 key) {
 
 		if (checkCode("3100OPB")) {
 			_subtitleManager->showDebugMsg(Common::String::format("Current location: %c%c%c%c",
-			                                    _scriptManager->getStateValue(StateKey_World),
-			                                    _scriptManager->getStateValue(StateKey_Room),
-			                                    _scriptManager->getStateValue(StateKey_Node),
-			                                    _scriptManager->getStateValue(StateKey_View)));
+			                               _scriptManager->getStateValue(StateKey_World),
+			                               _scriptManager->getStateValue(StateKey_Room),
+			                               _scriptManager->getStateValue(StateKey_Node),
+			                               _scriptManager->getStateValue(StateKey_View)));
 		}
 
 		if (checkCode("KILLMENOW")) {
@@ -107,10 +107,10 @@ void ZVision::cheatCodes(uint8 key) {
 
 		if (checkCode("77MASSAVE")) {
 			_subtitleManager->showDebugMsg(Common::String::format("Current location: %c%c%c%c",
-			                                    _scriptManager->getStateValue(StateKey_World),
-			                                    _scriptManager->getStateValue(StateKey_Room),
-			                                    _scriptManager->getStateValue(StateKey_Node),
-			                                    _scriptManager->getStateValue(StateKey_View)));
+			                               _scriptManager->getStateValue(StateKey_World),
+			                               _scriptManager->getStateValue(StateKey_Room),
+			                               _scriptManager->getStateValue(StateKey_Node),
+			                               _scriptManager->getStateValue(StateKey_View)));
 		}
 
 		if (checkCode("IDKFA")) {
@@ -165,34 +165,34 @@ void ZVision::processEvents() {
 		case Common::EVENT_LBUTTONDOWN:
 			_cursorManager->cursorDown(true);
 			_menu->onMouseDown(_event.mouse);
-			if(!_menu->inMenu() || !_widescreen) {
-			  _scriptManager->setStateValue(StateKey_LMouse, 1);
-			  _scriptManager->addEvent(_event);
-		  }
+			if (!_menu->inMenu() || !_widescreen) {
+				_scriptManager->setStateValue(StateKey_LMouse, 1);
+				_scriptManager->addEvent(_event);
+			}
 			break;
 
 		case Common::EVENT_LBUTTONUP:
 			_cursorManager->cursorDown(false);
 			_menu->onMouseUp(_event.mouse);
-			if(!_menu->inMenu() || !_widescreen) {
-			  _scriptManager->setStateValue(StateKey_LMouse, 0);
-			  _scriptManager->addEvent(_event);
-      }
+			if (!_menu->inMenu() || !_widescreen) {
+				_scriptManager->setStateValue(StateKey_LMouse, 0);
+				_scriptManager->addEvent(_event);
+			}
 			break;
 
 		case Common::EVENT_RBUTTONDOWN:
 			_cursorManager->cursorDown(true);
-			if(!_menu->inMenu() || !_widescreen) {
-			  _scriptManager->setStateValue(StateKey_RMouse, 1);
-			  if (getGameId() == GID_NEMESIS)
-				  _scriptManager->inventoryCycle();
+			if (!_menu->inMenu() || !_widescreen) {
+				_scriptManager->setStateValue(StateKey_RMouse, 1);
+				if (getGameId() == GID_NEMESIS)
+					_scriptManager->inventoryCycle();
 			}
 			break;
 
 		case Common::EVENT_RBUTTONUP:
 			_cursorManager->cursorDown(false);
-			if(!_menu->inMenu() || !_widescreen)
-  			_scriptManager->setStateValue(StateKey_RMouse, 0);
+			if (!_menu->inMenu() || !_widescreen)
+				_scriptManager->setStateValue(StateKey_RMouse, 0);
 			break;
 
 		case Common::EVENT_MOUSEMOVE:
@@ -202,6 +202,7 @@ void ZVision::processEvents() {
 		case Common::EVENT_CUSTOM_ENGINE_ACTION_START:
 			switch ((ZVisionAction)_event.customType) {
 			case kZVisionActionLeft:
+			// fall through
 			case kZVisionActionRight:
 				if (_renderManager->getRenderTable()->getRenderState() == RenderTable::PANORAMA)
 					_keyboardVelocity = (_event.customType == kZVisionActionLeft ?
@@ -210,6 +211,7 @@ void ZVision::processEvents() {
 				break;
 
 			case kZVisionActionUp:
+			// fall through
 			case kZVisionActionDown:
 				if (_renderManager->getRenderTable()->getRenderState() == RenderTable::TILT)
 					_keyboardVelocity = (_event.customType == kZVisionActionUp ?
@@ -219,33 +221,33 @@ void ZVision::processEvents() {
 
 			case kZVisionActionSave:
 				//if (_menu->getEnable() & kMenubarSave)
-				if (_menu->getEnable(kMainMenuSave))		
+				if (_menu->getEnable(kMainMenuSave))
 					_scriptManager->changeLocation('g', 'j', 's', 'e', 0);
 				break;
 
 			case kZVisionActionRestore:
 				//if (_menu->getEnable() & kMenubarRestore)
-				if (_menu->getEnable(kMainMenuLoad))		
+				if (_menu->getEnable(kMainMenuLoad))
 					_scriptManager->changeLocation('g', 'j', 'r', 'e', 0);
 				break;
 
 			case kZVisionActionPreferences:
 				//if (_menu->getEnable() & kMenubarSettings)
-				if (_menu->getEnable(kMainMenuPrefs))		
+				if (_menu->getEnable(kMainMenuPrefs))
 					_scriptManager->changeLocation('g', 'j', 'p', 'e', 0);
 				break;
 
 			case kZVisionActionQuit:
 				//if (_menu->getEnable() & kMenubarExit)
-				if (_menu->getEnable(kMainMenuExit))				
+				if (_menu->getEnable(kMainMenuExit))
 					ifQuit();
 				break;
 
 			case kZVisionActionShowFPS: {
 				Common::String fpsStr = Common::String::format("FPS: %d", getFPS());
 				_subtitleManager->showDebugMsg(fpsStr);
-				}
-				break;
+			}
+			break;
 			default:
 				break;
 			}
@@ -254,11 +256,13 @@ void ZVision::processEvents() {
 		case Common::EVENT_CUSTOM_ENGINE_ACTION_END:
 			switch ((ZVisionAction)_event.customType) {
 			case kZVisionActionLeft:
+			// fall through
 			case kZVisionActionRight:
 				if (_renderManager->getRenderTable()->getRenderState() == RenderTable::PANORAMA)
 					_keyboardVelocity = 0;
 				break;
 			case kZVisionActionUp:
+			// fall through
 			case kZVisionActionDown:
 				if (_renderManager->getRenderTable()->getRenderState() == RenderTable::TILT)
 					_keyboardVelocity = 0;
@@ -285,7 +289,7 @@ void ZVision::processEvents() {
 }
 
 void ZVision::onMouseMove(const Common::Point &pos) {
-  debug(6,"ZVision::onMouseMove()");
+	debug(6, "ZVision::onMouseMove()");
 	_menu->onMouseMove(pos);
 	Common::Point imageCoord(_renderManager->screenSpaceToImageSpace(pos));
 	Common::Rect _workingArea = _renderManager->getWorkingArea();
@@ -322,60 +326,56 @@ void ZVision::onMouseMove(const Common::Point &pos) {
 	//               ^
 
 	// Clip the horizontal mouse position to the working window
-	debug(6,"Mouse pos.x, %d, clipping with %d+1, %d+1", pos.x, _workingArea.left, _workingArea.right);
+	debug(6, "Mouse pos.x, %d, clipping with %d+1, %d+1", pos.x, _workingArea.left, _workingArea.right);
 	Common::Point clippedPos = pos;
 	clippedPos.x = CLIP<int16>(pos.x, _workingArea.left + 1, _workingArea.right - 1);
 	if (_workingArea.contains(clippedPos) && !_menu->inMenu()) {
 		cursorWasChanged = _scriptManager->onMouseMove(clippedPos, imageCoord);
 		RenderTable::RenderState renderState = _renderManager->getRenderTable()->getRenderState();
-		switch(renderState) {
-		  case RenderTable::PANORAMA:
-			  if (clippedPos.x >= _workingArea.left && clippedPos.x < _workingArea.left + ROTATION_SCREEN_EDGE_OFFSET) {
-				  int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
-				  if (mspeed <= 0)
-					  mspeed = 25;
-				  _mouseVelocity  = MIN(((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (clippedPos.x - _workingArea.left)) - mspeed).toInt(), -1);
-				  _cursorManager->changeCursor(CursorIndex_Left);
-				  cursorWasChanged = true;
-			  } 
-			  else if (clippedPos.x <= _workingArea.right && clippedPos.x > _workingArea.right - ROTATION_SCREEN_EDGE_OFFSET) {
-				  int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
-				  if (mspeed <= 0)
-					  mspeed = 25;
-				  _mouseVelocity  = MAX((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (clippedPos.x - _workingArea.right + ROTATION_SCREEN_EDGE_OFFSET)).toInt(), 1);
-				  _cursorManager->changeCursor(CursorIndex_Right);
-				  cursorWasChanged = true;
-			  } 
-			  else
-				  _mouseVelocity = 0;
-	      break;
-      case RenderTable::TILT:
-		    if (clippedPos.y >= _workingArea.top && clippedPos.y < _workingArea.top + ROTATION_SCREEN_EDGE_OFFSET) {
-			    int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
-			    if (mspeed <= 0)
-				    mspeed = 25;
-			    _mouseVelocity  = MIN(((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (pos.y - _workingArea.top)) - mspeed).toInt(), -1);
-			    _cursorManager->changeCursor(CursorIndex_UpArr);
-			    cursorWasChanged = true;
-		    } 
-		    else if (clippedPos.y <= _workingArea.bottom && clippedPos.y > _workingArea.bottom - ROTATION_SCREEN_EDGE_OFFSET) {
-			    int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
-			    if (mspeed <= 0)
-				    mspeed = 25;
-			    _mouseVelocity = MAX((Common::Rational(MAX_ROTATION_SPEED, ROTATION_SCREEN_EDGE_OFFSET) * (pos.y - _workingArea.bottom + ROTATION_SCREEN_EDGE_OFFSET)).toInt(), 1);
-			    _cursorManager->changeCursor(CursorIndex_DownArr);
-			    cursorWasChanged = true;
-		    } 
-		    else
-			    _mouseVelocity = 0;
-		    break;
-      case RenderTable::FLAT:
-		  default:
-			  _mouseVelocity = 0;
-		    break;
-    }
-	} 
-	else
+		switch (renderState) {
+		case RenderTable::PANORAMA:
+			if (clippedPos.x >= _workingArea.left && clippedPos.x < _workingArea.left + ROTATION_SCREEN_EDGE_OFFSET) {
+				int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
+				if (mspeed <= 0)
+					mspeed = 25;
+				_mouseVelocity  = MIN(((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (clippedPos.x - _workingArea.left)) - mspeed).toInt(), -1);
+				_cursorManager->changeCursor(CursorIndex_Left);
+				cursorWasChanged = true;
+			} else if (clippedPos.x <= _workingArea.right && clippedPos.x > _workingArea.right - ROTATION_SCREEN_EDGE_OFFSET) {
+				int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
+				if (mspeed <= 0)
+					mspeed = 25;
+				_mouseVelocity  = MAX((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (clippedPos.x - _workingArea.right + ROTATION_SCREEN_EDGE_OFFSET)).toInt(), 1);
+				_cursorManager->changeCursor(CursorIndex_Right);
+				cursorWasChanged = true;
+			} else
+				_mouseVelocity = 0;
+			break;
+		case RenderTable::TILT:
+			if (clippedPos.y >= _workingArea.top && clippedPos.y < _workingArea.top + ROTATION_SCREEN_EDGE_OFFSET) {
+				int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
+				if (mspeed <= 0)
+					mspeed = 25;
+				_mouseVelocity  = MIN(((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (pos.y - _workingArea.top)) - mspeed).toInt(), -1);
+				_cursorManager->changeCursor(CursorIndex_UpArr);
+				cursorWasChanged = true;
+			} else if (clippedPos.y <= _workingArea.bottom && clippedPos.y > _workingArea.bottom - ROTATION_SCREEN_EDGE_OFFSET) {
+				int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
+				if (mspeed <= 0)
+					mspeed = 25;
+				_mouseVelocity = MAX((Common::Rational(MAX_ROTATION_SPEED, ROTATION_SCREEN_EDGE_OFFSET) * (pos.y - _workingArea.bottom + ROTATION_SCREEN_EDGE_OFFSET)).toInt(), 1);
+				_cursorManager->changeCursor(CursorIndex_DownArr);
+				cursorWasChanged = true;
+			} else
+				_mouseVelocity = 0;
+			break;
+		case RenderTable::FLAT:
+		// fall through
+		default:
+			_mouseVelocity = 0;
+			break;
+		}
+	} else
 		_mouseVelocity = 0;
 	if (!cursorWasChanged)
 		_cursorManager->changeCursor(CursorIndex_Idle);
diff --git a/engines/zvision/detection_tables.h b/engines/zvision/detection_tables.h
index bb56fe3dff0..612f66a7154 100644
--- a/engines/zvision/detection_tables.h
+++ b/engines/zvision/detection_tables.h
@@ -63,8 +63,8 @@ static const ZVisionGameDescription gameDescriptions[] = {
 		{
 			"znemesis",
 			0,
-			AD_ENTRY2s("CSCR.ZFS",		"f04113357b4748c13efcb58b4629887c", 2577873,
-					   "NEMESIS.STR",	"333bcb17bbb7f57cae742fbbe44f56f3", 9219),
+			AD_ENTRY2s("CSCR.ZFS",      "f04113357b4748c13efcb58b4629887c", 2577873,
+			           "NEMESIS.STR",   "333bcb17bbb7f57cae742fbbe44f56f3", 9219),
 			Common::FR_FRA,
 			Common::kPlatformDOS,
 			ADGF_NO_FLAGS,
@@ -78,8 +78,8 @@ static const ZVisionGameDescription gameDescriptions[] = {
 		{
 			"znemesis",
 			0,
-			AD_ENTRY2s("CSCR.ZFS",		"f04113357b4748c13efcb58b4629887c", 2577873,
-					   "NEMESIS.STR",	"3d1a12b907751653866cffc6d4dfb331", 9505),
+			AD_ENTRY2s("CSCR.ZFS",      "f04113357b4748c13efcb58b4629887c", 2577873,
+			           "NEMESIS.STR",   "3d1a12b907751653866cffc6d4dfb331", 9505),
 			Common::DE_DEU,
 			Common::kPlatformDOS,
 			ADGF_NO_FLAGS,
@@ -93,8 +93,8 @@ static const ZVisionGameDescription gameDescriptions[] = {
 		{
 			"znemesis",
 			0,
-			AD_ENTRY2s("CSCR.ZFS",		"f04113357b4748c13efcb58b4629887c", 2577873,
-					   "NEMESIS.STR",	"7c568feca8d9f9ae855c47183612c305", 9061),
+			AD_ENTRY2s("CSCR.ZFS",      "f04113357b4748c13efcb58b4629887c", 2577873,
+			           "NEMESIS.STR",   "7c568feca8d9f9ae855c47183612c305", 9061),
 			Common::IT_ITA,
 			Common::kPlatformDOS,
 			ADGF_NO_FLAGS,
@@ -216,7 +216,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			"zgi",
 			"CD",
 			AD_ENTRY2s("SCRIPTS.ZFS",  "81efd40ecc3d22531e211368b779f17f", 8336944,
-					   "G0LPH10P.RAW", "c0b1f28b1cd1aaeb83c1a3985401bb14", 24462),
+			           "G0LPH10P.RAW", "c0b1f28b1cd1aaeb83c1a3985401bb14", 24462),
 			Common::EN_ANY,
 			Common::kPlatformMacintosh,
 			ADGF_NO_FLAGS,
@@ -234,11 +234,11 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::EN_ANY,
 			Common::kPlatformWindows,
 			ADGF_DVD,
-#if defined(USE_MPEG2) && defined(USE_A52)
+			#if defined(USE_MPEG2) && defined(USE_A52)
 			GUIO6(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_USE_HIRES_MPEG_MOVIES, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
-#else
+			#else
 			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
-#endif
+			#endif
 		},
 		GID_GRANDINQUISITOR
 	},
diff --git a/engines/zvision/file/save_manager.cpp b/engines/zvision/file/save_manager.cpp
index 257940f0154..10e1087ce86 100644
--- a/engines/zvision/file/save_manager.cpp
+++ b/engines/zvision/file/save_manager.cpp
@@ -114,63 +114,62 @@ void SaveManager::writeSaveGameHeader(Common::OutSaveFile *file, const Common::S
 Common::Error SaveManager::loadGame(int slot) {
 	Common::SeekableReadStream *saveFile = NULL;
 	if (slot < 0) {
-  //Restart game, used by ZGI death screen only
-/*
-		saveFile = _engine->getSearchManager()->openFile("r.svr");
-		if (!saveFile) {
-			Common::File *restoreFile = new Common::File();
-			if (!restoreFile->open("r.svr")) {
-				delete restoreFile;
-				return Common::kPathDoesNotExist;
+		//Restart game, used by ZGI death screen only
+		/*
+		        saveFile = _engine->getSearchManager()->openFile("r.svr");
+		        if (!saveFile) {
+		            Common::File *restoreFile = new Common::File();
+		            if (!restoreFile->open("r.svr")) {
+		                delete restoreFile;
+		                return Common::kPathDoesNotExist;
+		            }
+		            saveFile = restoreFile;
+		        }
+		/*/
+		_engine->getScriptManager()->initialize(true);
+//*/
+		return Common::kNoError;
+	} else {
+		saveFile = getSlotFile(slot);
+		if (!saveFile)
+			return Common::kPathDoesNotExist;
+		// Read the header
+		SaveGameHeader header;
+		if (!readSaveGameHeader(saveFile, header))
+			return Common::kUnknownError;
+		ScriptManager *scriptManager = _engine->getScriptManager();
+		// Update the state table values
+		scriptManager->deserialize(saveFile);
+		delete saveFile;
+		if (_engine->getGameId() == GID_NEMESIS)  {
+			//Zork Nemesis has no in-game option to select panorama quality or animation options
+			//We set them here to ensure loaded games don't override current game configuration
+			scriptManager->setStateValue(StateKey_HighQuality, ConfMan.getBool("highquality"));
+			scriptManager->setStateValue(StateKey_NoTurnAnim, ConfMan.getBool("noanimwhileturning"));
+			if (scriptManager->getCurrentLocation() == "tv2f") {
+				// WORKAROUND for script bug #6793: location tv2f (stairs) has two states:
+				// one at the top of the stairs, and one at the bottom. When the player
+				// goes to the bottom of the stairs, the screen changes, and hotspot
+				// 4652 (exit opposite the stairs) is enabled. However, the variable that
+				// controls the state (2408) is reset when the player goes down the stairs.
+				// Furthermore, the room's initialization script disables the stair exit
+				// control (4652). This leads to an impossible situation, where all the
+				// exit controls are disabled, and the player can't more anywhere. Thus,
+				// when loading a game in that room, we check for that impossible
+				// situation, which only occurs after the player has moved down the stairs,
+				// and fix it here by setting the correct background, and enabling the
+				// stair exit hotspot.
+				if ((scriptManager->getStateFlag(2411) & Puzzle::DISABLED) &&
+				        (scriptManager->getStateFlag(2408) & Puzzle::DISABLED) &&
+				        (scriptManager->getStateFlag(4652) & Puzzle::DISABLED)) {
+					_engine->getRenderManager()->setBackgroundImage("tv2fb21c.tga");
+					scriptManager->unsetStateFlag(4652, Puzzle::DISABLED);
+				}
 			}
-			saveFile = restoreFile;
 		}
-/*/
-    _engine->getScriptManager()->initialize(true);
-//*/
-	  return Common::kNoError;
-  }
-	else {
-	  saveFile = getSlotFile(slot);
-	  if (!saveFile)
-		  return Common::kPathDoesNotExist;
-	  // Read the header
-	  SaveGameHeader header;
-	  if (!readSaveGameHeader(saveFile, header))
-		  return Common::kUnknownError;
-	  ScriptManager *scriptManager = _engine->getScriptManager();
-	  // Update the state table values
-	  scriptManager->deserialize(saveFile);
-	  delete saveFile;
-	  if (_engine->getGameId() == GID_NEMESIS)  {
-      //Zork Nemesis has no in-game option to select panorama quality or animation options
-      //We set them here to ensure loaded games don't override current game configuration
-      scriptManager->setStateValue(StateKey_HighQuality, ConfMan.getBool("highquality"));
-      scriptManager->setStateValue(StateKey_NoTurnAnim, ConfMan.getBool("noanimwhileturning"));
-	    if(scriptManager->getCurrentLocation() == "tv2f") {
-		    // WORKAROUND for script bug #6793: location tv2f (stairs) has two states:
-		    // one at the top of the stairs, and one at the bottom. When the player
-		    // goes to the bottom of the stairs, the screen changes, and hotspot
-		    // 4652 (exit opposite the stairs) is enabled. However, the variable that
-		    // controls the state (2408) is reset when the player goes down the stairs.
-		    // Furthermore, the room's initialization script disables the stair exit
-		    // control (4652). This leads to an impossible situation, where all the
-		    // exit controls are disabled, and the player can't more anywhere. Thus,
-		    // when loading a game in that room, we check for that impossible
-		    // situation, which only occurs after the player has moved down the stairs,
-		    // and fix it here by setting the correct background, and enabling the
-		    // stair exit hotspot.
-		    if ((scriptManager->getStateFlag(2411) & Puzzle::DISABLED) &&
-			    (scriptManager->getStateFlag(2408) & Puzzle::DISABLED) &&
-			    (scriptManager->getStateFlag(4652) & Puzzle::DISABLED)) {
-			    _engine->getRenderManager()->setBackgroundImage("tv2fb21c.tga");
-			    scriptManager->unsetStateFlag(4652, Puzzle::DISABLED);
-		    }
-	    }
-	  }
-	  g_engine->setTotalPlayTime(header.playTime * 1000);
-	  return Common::kNoError;
-  }
+		g_engine->setTotalPlayTime(header.playTime * 1000);
+		return Common::kNoError;
+	}
 }
 
 bool SaveManager::readSaveGameHeader(Common::InSaveFile *in, SaveGameHeader &header, bool skipThumbnail) {
@@ -204,12 +203,12 @@ bool SaveManager::readSaveGameHeader(Common::InSaveFile *in, SaveGameHeader &hea
 	if (header.version > SAVE_VERSION) {
 		uint tempVersion = header.version;
 		GUI::MessageDialog dialog(
-			Common::U32String::format(
-				_("This saved game uses version %u, but this engine only "
-				  "supports up to version %d. You will need an updated version "
-				  "of the engine to use this saved game."), tempVersion, SAVE_VERSION
-			),
-		_("OK"));
+		    Common::U32String::format(
+		        _("This saved game uses version %u, but this engine only "
+		          "supports up to version %d. You will need an updated version "
+		          "of the engine to use this saved game."), tempVersion, SAVE_VERSION
+		    ),
+		    _("OK"));
 		dialog.runModal();
 	}
 
diff --git a/engines/zvision/graphics/cursors/cursor.cpp b/engines/zvision/graphics/cursors/cursor.cpp
index 49f83ae2700..da9c2902e71 100644
--- a/engines/zvision/graphics/cursors/cursor.cpp
+++ b/engines/zvision/graphics/cursors/cursor.cpp
@@ -60,11 +60,11 @@ ZorkCursor::ZorkCursor(ZVision *engine, const Common::Path &fileName)
 	uint32 bytesRead = file.read(_surface.getPixels(), dataSize);
 	assert(bytesRead == dataSize);
 
-#ifndef SCUMM_LITTLE_ENDIAN
+	#ifndef SCUMM_LITTLE_ENDIAN
 	int16 *buffer = (int16 *)_surface.getPixels();
 	for (uint32 i = 0; i < dataSize / 2; ++i)
 		buffer[i] = FROM_LE_16(buffer[i]);
-#endif
+	#endif
 }
 
 ZorkCursor::ZorkCursor(const ZorkCursor &other) {
diff --git a/engines/zvision/graphics/cursors/cursor_manager.cpp b/engines/zvision/graphics/cursors/cursor_manager.cpp
index 62a9ec1c781..b697b390951 100644
--- a/engines/zvision/graphics/cursors/cursor_manager.cpp
+++ b/engines/zvision/graphics/cursors/cursor_manager.cpp
@@ -33,16 +33,16 @@
 namespace ZVision {
 
 const char *CursorManager::_cursorNames[NUM_CURSORS] = { "active", "arrow", "backward", "downarrow", "forward", "handpt", "handpu", "hdown", "hleft",
-														 "hright", "hup", "idle", "leftarrow", "rightarrow", "suggest_surround", "suggest_tilt", "turnaround", "zuparrow"
-													   };
+                                                         "hright", "hup", "idle", "leftarrow", "rightarrow", "suggest_surround", "suggest_tilt", "turnaround", "zuparrow"
+                                                       };
 
 const char *CursorManager::_zgiCursorFileNames[NUM_CURSORS] = { "g0gbc011.zcr", "g0gac011.zcr", "g0gac021.zcr", "g0gac031.zcr", "g0gac041.zcr", "g0gac051.zcr", "g0gac061.zcr", "g0gac071.zcr", "g0gac081.zcr",
-																"g0gac091.zcr", "g0gac101.zcr", "g0gac011.zcr", "g0gac111.zcr", "g0gac121.zcr", "g0gac131.zcr", "g0gac141.zcr", "g0gac151.zcr", "g0gac161.zcr"
-															  };
+                                                                "g0gac091.zcr", "g0gac101.zcr", "g0gac011.zcr", "g0gac111.zcr", "g0gac121.zcr", "g0gac131.zcr", "g0gac141.zcr", "g0gac151.zcr", "g0gac161.zcr"
+                                                              };
 
 const char *CursorManager::_zNemCursorFileNames[NUM_CURSORS] = { "00act", "arrow", "back", "down", "forw", "handpt", "handpu", "hdown", "hleft",
-																 "hright", "hup", "00idle", "left", "right", "ssurr", "stilt", "turn", "up"
-															   };
+                                                                 "hright", "hup", "00idle", "left", "right", "ssurr", "stilt", "turn", "up"
+                                                               };
 
 CursorManager::CursorManager(ZVision *engine, const Graphics::PixelFormat &pixelFormat)
 	: _engine(engine),
@@ -88,13 +88,13 @@ void CursorManager::setItemID(int id) {
 				file = Common::Path(Common::String::format("%2.2d%s%c.zcr", id, "act", 'b'));
 				_cursors[NUM_CURSORS + 1][0] = ZorkCursor(_engine, file);
 			} else if (_engine->getGameId() == GID_GRANDINQUISITOR) {
-				file = Common::Path(Common::String::format("g0b%cc%2.2x1.zcr", 'a' , id));
+				file = Common::Path(Common::String::format("g0b%cc%2.2x1.zcr", 'a', id));
 				_cursors[NUM_CURSORS][0] = ZorkCursor(_engine, file);
-				file = Common::Path(Common::String::format("g0b%cc%2.2x1.zcr", 'c' , id));
+				file = Common::Path(Common::String::format("g0b%cc%2.2x1.zcr", 'c', id));
 				_cursors[NUM_CURSORS][1] = ZorkCursor(_engine, file);
-				file = Common::Path(Common::String::format("g0b%cc%2.2x1.zcr", 'b' , id));
+				file = Common::Path(Common::String::format("g0b%cc%2.2x1.zcr", 'b', id));
 				_cursors[NUM_CURSORS + 1][0] = ZorkCursor(_engine, file);
-				file = Common::Path(Common::String::format("g0b%cc%2.2x1.zcr", 'd' , id));
+				file = Common::Path(Common::String::format("g0b%cc%2.2x1.zcr", 'd', id));
 				_cursors[NUM_CURSORS + 1][1] = ZorkCursor(_engine, file);
 			} else
 				return;
diff --git a/engines/zvision/graphics/effects/fog.cpp b/engines/zvision/graphics/effects/fog.cpp
index 82af1de4ea0..239abbc12f1 100644
--- a/engines/zvision/graphics/effects/fog.cpp
+++ b/engines/zvision/graphics/effects/fog.cpp
@@ -111,7 +111,7 @@ const Graphics::Surface *FogFx::draw(const Graphics::Surface &srcSubRect) {
 void FogFx::update() {
 	_pos += _engine->getScriptManager()->getStateValue(StateKey_EF9_Speed);
 	_pos %= _fog.w;
-  debug(2,"Updating fog effect");
+	debug(2, "Updating fog effect");
 	uint8 dr = _engine->getScriptManager()->getStateValue(StateKey_EF9_R);
 	uint8 dg = _engine->getScriptManager()->getStateValue(StateKey_EF9_G);
 	uint8 db = _engine->getScriptManager()->getStateValue(StateKey_EF9_B);
diff --git a/engines/zvision/graphics/graphics_effect.h b/engines/zvision/graphics/graphics_effect.h
index 3493ed0a24e..e060b9a9028 100644
--- a/engines/zvision/graphics/graphics_effect.h
+++ b/engines/zvision/graphics/graphics_effect.h
@@ -48,13 +48,13 @@ public:
 		return _region;
 	}
 
-  //If true, effect is applied to the current background image prior to panoramic warping
-  //If false, effect is applied to the effects buffer, which corresponds directly to the working window
+	//If true, effect is applied to the current background image prior to panoramic warping
+	//If false, effect is applied to the effects buffer, which corresponds directly to the working window
 	bool isPort() {
 		return _ported;
 	}
 
-  //Make a copy of supplied surface, draw effect on it, then return that altered surface
+	//Make a copy of supplied surface, draw effect on it, then return that altered surface
 	virtual const Graphics::Surface *draw(const Graphics::Surface &srcSubRect) {
 		return &_surface;
 	}
diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 2eaae5307eb..a17607f74eb 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -38,7 +38,6 @@
 
 #include "graphics/blit.h"
 
-//FOR BUG TEST ONLY
 #include "common/debug.h"
 
 namespace ZVision {
@@ -49,7 +48,7 @@ RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const G
 	  _layout(layout),
 	  _screenArea(_layout.screenArea),
 	  _workingArea(_layout.workingArea),
-	  _workingAreaCenter(Common::Point(_workingArea.width()/2, _workingArea.height()/2)),
+	  _workingAreaCenter(Common::Point(_workingArea.width() / 2, _workingArea.height() / 2)),
 	  _textArea(_layout.textArea),
 	  _menuArea(_layout.menuArea),
 	  _pixelFormat(pixelFormat),
@@ -60,28 +59,28 @@ RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const G
 	  _doubleFPS(doubleFPS),
 	  _widescreen(widescreen),
 	  frameLimiter(engine->_system, doubleFPS ? 60 : 30) {
-	debug(1,"creating render manager");
-  //Define graphics modes & screen subarea geometry
+	debug(1, "creating render manager");
+	//Define graphics modes & screen subarea geometry
 	Graphics::ModeList modes;
-  _textOffset = _layout.workingArea.origin() - _layout.textArea.origin();
-  modes.push_back(Graphics::Mode(_screenArea.width(), _screenArea.height()));
-#if defined(USE_MPEG2) && defined(USE_A52)
+	_textOffset = _layout.workingArea.origin() - _layout.textArea.origin();
+	modes.push_back(Graphics::Mode(_screenArea.width(), _screenArea.height()));
+	#if defined(USE_MPEG2) && defined(USE_A52)
 	if (_engine->getGameId() == GID_GRANDINQUISITOR && (_engine->getFeatures() & ADGF_DVD)) {
-	  if(_widescreen)
-  		modes.push_back(Graphics::Mode(_HDscreenAreaWide.width(), _HDscreenAreaWide.height()));
+		if (_widescreen)
+			modes.push_back(Graphics::Mode(_HDscreenAreaWide.width(), _HDscreenAreaWide.height()));
 		else
-  		modes.push_back(Graphics::Mode(_HDscreenArea.width(), _HDscreenArea.height()));
-  }
-#endif
+			modes.push_back(Graphics::Mode(_HDscreenArea.width(), _HDscreenArea.height()));
+	}
+	#endif
 	initGraphicsModes(modes);
-  //Create backbuffers
+	//Create backbuffers
 	_backgroundSurface.create(_workingArea.width(), _workingArea.height(), _pixelFormat);
 	_effectSurface.create(_workingArea.width(), _workingArea.height(), _pixelFormat);
 	_warpedSceneSurface.create(_workingArea.width(), _workingArea.height(), _pixelFormat);
 	_menuSurface.create(_menuArea.width(), _menuArea.height(), _pixelFormat);
 	_textSurface.create(_textArea.width(), _textArea.height(), _pixelFormat);
-	debug(1,"render manager created");
-  initialize(false);
+	debug(1, "render manager created");
+	initialize(false);
 }
 
 RenderManager::~RenderManager() {
@@ -98,179 +97,175 @@ RenderManager::~RenderManager() {
 }
 
 void RenderManager::initialize(bool hiRes) {
-  debug(1,"Initializing render manager");
-  _hiRes = hiRes;
-  
-  _screenArea = _layout.screenArea;
-  _workingArea =_layout.workingArea;
-  _textArea = _layout.textArea;
-  _menuArea = _layout.menuArea;
-  
-  if (_widescreen) {
-    _workingArea.moveTo(0,0);
-    _screenArea = _workingArea;
-    _menuArea.moveTo(_workingArea.origin());
-    _menuLetterbox.moveTo(_menuArea.origin());
-    _textArea.moveTo(_workingArea.left, _workingArea.bottom - _textArea.height());
-    _textLetterbox.moveTo(_textArea.origin());
-  }
-  
-  //Screen
-#if defined(USE_MPEG2) && defined(USE_A52)
-  if(_hiRes) {
-    debug(1,"Switching to high resolution");
-    upscaleRect(_screenArea);
-    upscaleRect(_workingArea);
-    upscaleRect(_textArea);
-  }
-  else
-    debug(1,"Switching to standard resolution");
-#endif
-  _screen.create(_screenArea.width(), _screenArea.height(), _pixelFormat);
+	debug(1, "Initializing render manager");
+	_hiRes = hiRes;
+
+	_screenArea = _layout.screenArea;
+	_workingArea = _layout.workingArea;
+	_textArea = _layout.textArea;
+	_menuArea = _layout.menuArea;
+
+	if (_widescreen) {
+		_workingArea.moveTo(0, 0);
+		_screenArea = _workingArea;
+		_menuArea.moveTo(_workingArea.origin());
+		_menuLetterbox.moveTo(_menuArea.origin());
+		_textArea.moveTo(_workingArea.left, _workingArea.bottom - _textArea.height());
+		_textLetterbox.moveTo(_textArea.origin());
+	}
+
+	//Screen
+	#if defined(USE_MPEG2) && defined(USE_A52)
+	if (_hiRes) {
+		debug(1, "Switching to high resolution");
+		upscaleRect(_screenArea);
+		upscaleRect(_workingArea);
+		upscaleRect(_textArea);
+	} else
+		debug(1, "Switching to standard resolution");
+	#endif
+	_screen.create(_screenArea.width(), _screenArea.height(), _pixelFormat);
 	_screen.setTransparentColor(-1);
 	_screen.clear();
-  
-  debug(1,"_workingAreaCenter = %d,%d", _workingAreaCenter.x, _workingAreaCenter.y);
+
+	debug(1, "_workingAreaCenter = %d,%d", _workingAreaCenter.x, _workingAreaCenter.y);
 
 	//Managed screen subsurfaces
 	_workingManagedSurface.create(_screen, _workingArea);
-  _menuManagedSurface.create(_screen, _menuArea);
+	_menuManagedSurface.create(_screen, _menuArea);
 	_textManagedSurface.create(_screen, _textArea);
-  debug(2,"screen area: %d,%d,%d,%d", _screenArea.left, _screenArea.top, _screenArea.bottom, _screenArea.right);
-  debug(2,"working area: %d,%d,%d,%d", _workingArea.left, _workingArea.top, _workingArea.bottom, _workingArea.right);
-  debug(2,"text area: %d,%d,%d,%d", _textArea.left, _textArea.top, _textArea.bottom, _textArea.right);
-	
-  //Menu & text area dirty rectangles
-  _menuOverlay = _menuArea.findIntersectingRect(_workingArea);
-  if(!_menuOverlay.isEmpty() && _menuArea.left >= _workingArea.left && _menuArea.right <= _workingArea.right)
-    _menuLetterbox = Common::Rect(_menuArea.left, _menuArea.top, _menuArea.right, _workingArea.top);
-  else
-    _menuLetterbox = _menuArea;
-    
-  //TODO - add upscaling for HD mode!
-  _textOverlay = _textArea.findIntersectingRect(_workingArea);
-  if(!_textOverlay.isEmpty() && _textArea.left >= _workingArea.left && _textArea.right <= _workingArea.right)
-    _textLetterbox = Common::Rect(_textArea.left, _workingArea.bottom, _textArea.right, _textArea.bottom);
-  else
-    _textLetterbox = _textArea;
-  
-  debug(2,"text overlay area: %d,%d,%d,%d", _textOverlay.left, _textOverlay.top, _textOverlay.bottom, _textOverlay.right);
-  debug(2,"menu overlay area: %d,%d,%d,%d", _menuOverlay.left, _menuOverlay.top, _menuOverlay.bottom, _menuOverlay.right);
-	
-  debug(2,"Clearing backbuffers");
+	debug(2, "screen area: %d,%d,%d,%d", _screenArea.left, _screenArea.top, _screenArea.bottom, _screenArea.right);
+	debug(2, "working area: %d,%d,%d,%d", _workingArea.left, _workingArea.top, _workingArea.bottom, _workingArea.right);
+	debug(2, "text area: %d,%d,%d,%d", _textArea.left, _textArea.top, _textArea.bottom, _textArea.right);
+
+	//Menu & text area dirty rectangles
+	_menuOverlay = _menuArea.findIntersectingRect(_workingArea);
+	if (!_menuOverlay.isEmpty() && _menuArea.left >= _workingArea.left && _menuArea.right <= _workingArea.right)
+		_menuLetterbox = Common::Rect(_menuArea.left, _menuArea.top, _menuArea.right, _workingArea.top);
+	else
+		_menuLetterbox = _menuArea;
+
+	_textOverlay = _textArea.findIntersectingRect(_workingArea);
+	if (!_textOverlay.isEmpty() && _textArea.left >= _workingArea.left && _textArea.right <= _workingArea.right)
+		_textLetterbox = Common::Rect(_textArea.left, _workingArea.bottom, _textArea.right, _textArea.bottom);
+	else
+		_textLetterbox = _textArea;
+
+	debug(2, "text overlay area: %d,%d,%d,%d", _textOverlay.left, _textOverlay.top, _textOverlay.bottom, _textOverlay.right);
+	debug(2, "menu overlay area: %d,%d,%d,%d", _menuOverlay.left, _menuOverlay.top, _menuOverlay.bottom, _menuOverlay.right);
+
+	debug(2, "Clearing backbuffers");
 	//Clear backbuffer surfaces
 	clearMenuSurface(true);
-  clearTextSurface(true);
-  debug(2,"Backbuffers cleared");
-  
-  //Set hardware/window resolution
-  debug(1,"_screen.w = %d, _screen.h = %d", _screen.w, _screen.h);
-  initGraphics(_screen.w, _screen.h, &_engine->_screenPixelFormat);
-  frameLimiter.initialize();
-	debug(1,"Render manager initialized");
+	clearTextSurface(true);
+	debug(2, "Backbuffers cleared");
+
+	//Set hardware/window resolution
+	debug(1, "_screen.w = %d, _screen.h = %d", _screen.w, _screen.h);
+	initGraphics(_screen.w, _screen.h, &_engine->_screenPixelFormat);
+	frameLimiter.initialize();
+	debug(1, "Render manager initialized");
 }
 
 bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool preStream) {
-  debug(5,"\nrenderSceneToScreen%s%s%s", immediate ? ", immediate" : "", overlayOnly ? ", overlay only" : "", preStream ? ", pre-stream" : "");
-  uint32 startTime = _system->getMillis();
-  if(!overlayOnly) {
-	  Graphics::Surface *inputSurface = &_backgroundSurface;
-	  Common::Rect outWndDirtyRect;
-	  //Apply graphical effects to temporary effects buffer and/or directly to current background image, as appropriate
-	  if (!_effects.empty()) {
-	    debug(6,"Rendering effects");
-		  bool copied = false;
-		  const Common::Rect windowRect(_workingArea.width(), _workingArea.height());
-		  for (EffectsList::iterator it = _effects.begin(); it != _effects.end(); it++) {
-			  Common::Rect rect = (*it)->getRegion();
-			  Common::Rect screenSpaceLocation = rect;
-			  if ((*it)->isPort())
-				  screenSpaceLocation = transformBackgroundSpaceRectToScreenSpace(screenSpaceLocation);
-			  if (windowRect.intersects(screenSpaceLocation)) {
-				  if (!copied) {
-					  copied = true;
-					  _effectSurface.copyFrom(_backgroundSurface);
-					  inputSurface = &_effectSurface;
-				  }
-				  const Graphics::Surface *post;
-				  if ((*it)->isPort())
-					  post = (*it)->draw(_currentBackgroundImage.getSubArea(rect));
-				  else
-					  post = (*it)->draw(_effectSurface.getSubArea(rect));
-				  Common::Rect empty;
-				  blitSurfaceToSurface(*post, empty, _effectSurface, screenSpaceLocation.left, screenSpaceLocation.top);
-				  debug(1,"windowRect %d,%d,%d,%d, screenSpaceLocation %d,%d,%d,%d", windowRect.left, windowRect.top, windowRect.bottom, windowRect.right, screenSpaceLocation.left, screenSpaceLocation.top, screenSpaceLocation.bottom, screenSpaceLocation.right);
-				  screenSpaceLocation.clip(windowRect);
-				  if (_backgroundSurfaceDirtyRect .isEmpty())
-					  _backgroundSurfaceDirtyRect = screenSpaceLocation;
-				  else
-					  _backgroundSurfaceDirtyRect.extend(screenSpaceLocation);
-			  }
-		  }
-	    debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
-	  }
-    //Apply panorama/tilt warp to background image
-	  switch(_renderTable.getRenderState()) {
-	    case RenderTable::PANORAMA:
-	    case RenderTable::TILT:
-	      debug(5,"Rendering panorama");
-		    if (!_backgroundSurfaceDirtyRect.isEmpty()) {
-			    _renderTable.mutateImage(&_warpedSceneSurface, inputSurface, _engine->getScriptManager()->getStateValue(StateKey_HighQuality));
-			    outputSurface = &_warpedSceneSurface;
-			    outWndDirtyRect = Common::Rect(_workingArea.width(), _workingArea.height());
-		    }
-	      break;
-	    default:
-		    outputSurface = inputSurface;
-		    outWndDirtyRect = _backgroundSurfaceDirtyRect;
-		    break;
-      debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
-    }
-    debug(5,"Rendering working area");
-	  _workingManagedSurface.simpleBlitFrom(*outputSurface); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
-    debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
+	debug(5, "\nrenderSceneToScreen%s%s%s", immediate ? ", immediate" : "", overlayOnly ? ", overlay only" : "", preStream ? ", pre-stream" : "");
+	uint32 startTime = _system->getMillis();
+	if (!overlayOnly) {
+		Graphics::Surface *inputSurface = &_backgroundSurface;
+		Common::Rect outWndDirtyRect;
+		//Apply graphical effects to temporary effects buffer and/or directly to current background image, as appropriate
+		if (!_effects.empty()) {
+			debug(6, "Rendering effects");
+			bool copied = false;
+			const Common::Rect windowRect(_workingArea.width(), _workingArea.height());
+			for (EffectsList::iterator it = _effects.begin(); it != _effects.end(); it++) {
+				Common::Rect rect = (*it)->getRegion();
+				Common::Rect screenSpaceLocation = rect;
+				if ((*it)->isPort())
+					screenSpaceLocation = transformBackgroundSpaceRectToScreenSpace(screenSpaceLocation);
+				if (windowRect.intersects(screenSpaceLocation)) {
+					if (!copied) {
+						copied = true;
+						_effectSurface.copyFrom(_backgroundSurface);
+						inputSurface = &_effectSurface;
+					}
+					const Graphics::Surface *post;
+					if ((*it)->isPort())
+						post = (*it)->draw(_currentBackgroundImage.getSubArea(rect));
+					else
+						post = (*it)->draw(_effectSurface.getSubArea(rect));
+					Common::Rect empty;
+					blitSurfaceToSurface(*post, empty, _effectSurface, screenSpaceLocation.left, screenSpaceLocation.top);
+					debug(1, "windowRect %d,%d,%d,%d, screenSpaceLocation %d,%d,%d,%d", windowRect.left, windowRect.top, windowRect.bottom, windowRect.right, screenSpaceLocation.left, screenSpaceLocation.top, screenSpaceLocation.bottom, screenSpaceLocation.right);
+					screenSpaceLocation.clip(windowRect);
+					if (_backgroundSurfaceDirtyRect .isEmpty())
+						_backgroundSurfaceDirtyRect = screenSpaceLocation;
+					else
+						_backgroundSurfaceDirtyRect.extend(screenSpaceLocation);
+				}
+			}
+			debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
+		}
+		//Apply panorama/tilt warp to background image
+		switch (_renderTable.getRenderState()) {
+		case RenderTable::PANORAMA:
+		// fall through
+		case RenderTable::TILT:
+			debug(5, "Rendering panorama");
+			if (!_backgroundSurfaceDirtyRect.isEmpty()) {
+				_renderTable.mutateImage(&_warpedSceneSurface, inputSurface, _engine->getScriptManager()->getStateValue(StateKey_HighQuality));
+				outputSurface = &_warpedSceneSurface;
+				outWndDirtyRect = Common::Rect(_workingArea.width(), _workingArea.height());
+			}
+			break;
+		default:
+			outputSurface = inputSurface;
+			outWndDirtyRect = _backgroundSurfaceDirtyRect;
+			break;
+			debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
+		}
+		debug(5, "Rendering working area");
+		_workingManagedSurface.simpleBlitFrom(*outputSurface); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
+		debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
 	}
-  if(preStream) {
-    debug(5,"Pre-rendering text area for video stream");    
-	  _workingManagedSurface.simpleBlitFrom(*outputSurface, _textOverlay, _textOverlay.origin()); //Prevents subtitle visual corruption when streaming videos that don't fully overlap them, e.g. Nemesis sarcophagi
-    return false;
-  }
-  else {
-    debug(5,"Rendering menu");
-	  _menuManagedSurface.transBlitFrom(_menuSurface, -1);
-    debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
-    debug(5,"Rendering text");
-    _textManagedSurface.transBlitFrom(_textSurface, -1);
-    debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
-    if(immediate) {
-      frameLimiter.startFrame();
-      debug(5,"Updating screen, immediate");
-      _screen.update();
-      debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
-      debug(10,"~renderSceneToScreen, immediate");
-      return true;
-    }
-    else if (_engine->canRender()) {
-      frameLimiter.delayBeforeSwap();
-      frameLimiter.startFrame();
-      debug(5,"Updating screen, frame limited");
-      _screen.update();
-      debug(5,"\tNett render time %d ms", _system->getMillis() - startTime);
-      debug(10,"~renderSceneToScreen, frame limited");
-      return true;
-    }
-    else {
-      debug(2,"Skipping screen update; engine forbids rendering at this time.");
-      return false;
-    };
-  };
+	if (preStream) {
+		debug(5, "Pre-rendering text area for video stream");
+		_workingManagedSurface.simpleBlitFrom(*outputSurface, _textOverlay, _textOverlay.origin()); //Prevents subtitle visual corruption when streaming videos that don't fully overlap them, e.g. Nemesis sarcophagi
+		return false;
+	} else {
+		debug(5, "Rendering menu");
+		_menuManagedSurface.transBlitFrom(_menuSurface, -1);
+		debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
+		debug(5, "Rendering text");
+		_textManagedSurface.transBlitFrom(_textSurface, -1);
+		debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
+		if (immediate) {
+			frameLimiter.startFrame();
+			debug(5, "Updating screen, immediate");
+			_screen.update();
+			debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
+			debug(10, "~renderSceneToScreen, immediate");
+			return true;
+		} else if (_engine->canRender()) {
+			frameLimiter.delayBeforeSwap();
+			frameLimiter.startFrame();
+			debug(5, "Updating screen, frame limited");
+			_screen.update();
+			debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
+			debug(10, "~renderSceneToScreen, frame limited");
+			return true;
+		} else {
+			debug(2, "Skipping screen update; engine forbids rendering at this time.");
+			return false;
+		};
+	};
 }
 
 Graphics::ManagedSurface &RenderManager::getVidSurface(Common::Rect &dstRect) {
-  Common::Rect _dstRect = dstRect;
-  _dstRect.translate(_workingArea.left, _workingArea.top);  //Convert to screen coordinates
+	Common::Rect _dstRect = dstRect;
+	_dstRect.translate(_workingArea.left, _workingArea.top);  //Convert to screen coordinates
 	_vidManagedSurface.create(_screen, _dstRect);
-	debug(1,"Obtaining managed video surface at %d,%d,%d,%d", _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
+	debug(1, "Obtaining managed video surface at %d,%d,%d,%d", _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
 	return _vidManagedSurface;
 }
 
@@ -328,12 +323,11 @@ void RenderManager::readImageToSurface(const Common::Path &fileName, Graphics::S
 		LzssReadStream lzssStream(&file);
 		buffer = (uint16 *)(new uint16[decompressedSize]);
 		lzssStream.read(buffer, 2 * decompressedSize);
-#ifndef SCUMM_LITTLE_ENDIAN
+		#ifndef SCUMM_LITTLE_ENDIAN
 		for (uint32 i = 0; i < decompressedSize; ++i)
 			buffer[i] = FROM_LE_16(buffer[i]);
-#endif
-	} 
-	else {
+		#endif
+	} else {
 		isTGZ = false;
 		// Reset the cursor
 		file.seek(0);
@@ -365,33 +359,32 @@ void RenderManager::readImageToSurface(const Common::Path &fileName, Graphics::S
 				dest[columnIndex + x] = buffer[x * imageHeight + y];
 			}
 		}
-	} 
-	else
+	} else
 		memcpy(destination.getPixels(), buffer, imageWidth * imageHeight * destination.format.bytesPerPixel);
 	// Cleanup
 	if (isTGZ)
 		delete[] buffer;
-  else
+	else
 		tga.destroy();
 }
 
 const Common::Point RenderManager::screenSpaceToImageSpace(const Common::Point &point) {
-  debug(9,"screenSpaceToImageSpace()");
+	debug(9, "screenSpaceToImageSpace()");
 	if (_workingArea.contains(point)) {
 		// Convert from screen space to working image space, i.e. panoramic background image or static image
 		Common::Point newPoint(point - _workingArea.origin());
-		switch(_renderTable.getRenderState()) {
-		  case RenderTable::PANORAMA:
-			  newPoint = _renderTable.convertWarpedCoordToFlatCoord(newPoint);		  
-			  newPoint += (Common::Point(_backgroundOffset - _workingAreaCenter.x, 0));
-			  break;
-		  case RenderTable::TILT:
-			  newPoint = _renderTable.convertWarpedCoordToFlatCoord(newPoint);
-			  newPoint += (Common::Point(0, _backgroundOffset - _workingAreaCenter.y));
-			  break;
-		  default:
-		    break;
-	  }
+		switch (_renderTable.getRenderState()) {
+		case RenderTable::PANORAMA:
+			newPoint = _renderTable.convertWarpedCoordToFlatCoord(newPoint);
+			newPoint += (Common::Point(_backgroundOffset - _workingAreaCenter.x, 0));
+			break;
+		case RenderTable::TILT:
+			newPoint = _renderTable.convertWarpedCoordToFlatCoord(newPoint);
+			newPoint += (Common::Point(0, _backgroundOffset - _workingAreaCenter.y));
+			break;
+		default:
+			break;
+		}
 		if (_backgroundWidth)
 			newPoint.x %= _backgroundWidth;
 		if (_backgroundHeight)
@@ -400,11 +393,10 @@ const Common::Point RenderManager::screenSpaceToImageSpace(const Common::Point &
 			newPoint.x += _backgroundWidth;
 		if (newPoint.y < 0)
 			newPoint.y += _backgroundHeight;
-    debug(9,"~screenSpaceToImageSpace()");
+		debug(9, "~screenSpaceToImageSpace()");
 		return newPoint;
-	} 
-	else {
-    debug(9,"~screenSpaceToImageSpace()");
+	} else {
+		debug(9, "~screenSpaceToImageSpace()");
 		return Common::Point(0, 0);
 	}
 }
@@ -421,26 +413,28 @@ void RenderManager::setBackgroundImage(const Common::Path &fileName) {
 }
 
 void RenderManager::setBackgroundPosition(int offset) {
-	switch(_renderTable.getRenderState()) {
-	  case RenderTable::PANORAMA :	
-	  case RenderTable::TILT :
-		  if (_backgroundOffset != offset)
-			  _backgroundDirtyRect = Common::Rect(_backgroundWidth, _backgroundHeight);
-		  break;
-	  default :
-	    break;
+	switch (_renderTable.getRenderState()) {
+	case RenderTable::PANORAMA :
+	// fall through
+	case RenderTable::TILT :
+		if (_backgroundOffset != offset)
+			_backgroundDirtyRect = Common::Rect(_backgroundWidth, _backgroundHeight);
+		break;
+	default :
+		break;
 	}
- 	_backgroundOffset = offset;
+	_backgroundOffset = offset;
 	_engine->getScriptManager()->setStateValue(StateKey_ViewPos, offset);
 }
 
 uint32 RenderManager::getCurrentBackgroundOffset() {
-	switch(_renderTable.getRenderState()) {
-	  case RenderTable::PANORAMA :
-	  case RenderTable::TILT :
-  		return _backgroundOffset;
-		default :
-		  return 0;
+	switch (_renderTable.getRenderState()) {
+	case RenderTable::PANORAMA :
+	// fall through
+	case RenderTable::TILT :
+		return _backgroundOffset;
+	default :
+		return 0;
 	}
 }
 
@@ -470,8 +464,7 @@ void RenderManager::scaleBuffer(const void *src, void *dst, uint32 srcWidth, uin
 				dstPtr++;
 			}
 		}
-	} 
-	else if (bytesPerPixel == 2) {
+	} else if (bytesPerPixel == 2) {
 		const uint16 *srcPtr = (const uint16 *)src;
 		uint16 *dstPtr = (uint16 *)dst;
 		for (uint32 y = 0; y < dstHeight; ++y) {
@@ -486,73 +479,73 @@ void RenderManager::scaleBuffer(const void *src, void *dst, uint32 srcWidth, uin
 
 //ORIGINAL FUNCTION
 //*
-void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect , Graphics::Surface &dst, int _x, int _y) {
-  debug(9,"blitSurfaceToSurface");
+void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect, Graphics::Surface &dst, int _x, int _y) {
+	debug(9, "blitSurfaceToSurface");
 	Common::Rect srcRect = _srcRect;
-	Common::Point dstPos = Common::Point(_x,_y);
+	Common::Point dstPos = Common::Point(_x, _y);
 	//Default to using whole source surface
 	if (srcRect.isEmpty())
 		srcRect = Common::Rect(src.w, src.h);
-  //Clip source rectangle to within bounds of source buffer
-	srcRect.clip(src.w, src.h); 
-	
+	//Clip source rectangle to within bounds of source buffer
+	srcRect.clip(src.w, src.h);
+
 	//CODE IDENTICAL TO HERE
-	
+
 	//BUG TEST CODE
 	//Common::Point dstPos2 = dstPos;
 	//Common::Rect srcRect2 = srcRect;
 	//Common::Rect::getBlitRect(dstPos2, srcRect2, Common::Rect(dst.w,dst.h));
-	
+
 	//Generate destination rectangle
 	Common::Rect dstRect = Common::Rect(dst.w, dst.h);
 	//Translate destination rectangle to its position relative to source rectangle
-	dstRect.translate(srcRect.left-_x,srcRect.top-_y);
+	dstRect.translate(srcRect.left - _x, srcRect.top - _y);
 	//clip source rectangle to within bounds of offset destination rectangle
 	srcRect.clip(dstRect);
-	
+
 	//BUG TEST
 	/*
 	if(srcRect.left != srcRect2.left) {
-	   debug("srcRect.left = %i, srcRect2.left = %i", srcRect.left, srcRect2.left);	   	   
+	   debug("srcRect.left = %i, srcRect2.left = %i", srcRect.left, srcRect2.left);
 	}
 	if(srcRect.top != srcRect2.top) {
 	   debug("srcRect.top = %i, srcRect2.top = %i", srcRect.top, srcRect2.top);
-  } 
+	}
 	if(srcRect.right != srcRect2.right) {
 	   debug("srcRect.right = %i, srcRect2.right = %i", srcRect.right, srcRect2.right);
-  }
+	}
 	if(srcRect.bottom != srcRect2.bottom) {
-	   debug("srcRect.bottom = %i, srcRect2.bottom = %i", srcRect.bottom, srcRect2.bottom);	   
-  }
-*/
+	   debug("srcRect.bottom = %i, srcRect2.bottom = %i", srcRect.bottom, srcRect2.bottom);
+	}
+	*/
 
-  //CODE IDENTICAL FROM HERE  
+	//CODE IDENTICAL FROM HERE
 
-  //Abort if nothing to blit
+	//Abort if nothing to blit
 	if (!srcRect.isEmpty()) {
-    //Convert pixel format of source to match destination
-	  Graphics::Surface *srcAdapted = src.convertTo(dst.format);
-	  //Get pointer for source buffer blit rectangle origin
-	  const byte *srcBuffer = (const byte *)srcAdapted->getBasePtr(srcRect.left, srcRect.top);
-
-    //Default to blitting into origin of target surface if negative valued
-	  if (dstPos.x < 0)
-		  dstPos.x = 0;
-	  if (dstPos.y < 0)
-		  dstPos.y = 0;
-		  
-	  //BUG TEST
-	  //assert(dstPos == dstPos2);
-    
-    //If _x & _y lie within destination surface
-    if (dstPos.x < dst.w && dstPos.y < dst.h) {
-      //Get pointer for destination buffer blit rectangle origin
-	    byte *dstBuffer = (byte *)dst.getBasePtr(dstPos.x, dstPos.y);
-	    Graphics::copyBlit(dstBuffer,srcBuffer,dst.pitch,srcAdapted->pitch,srcRect.width(),srcRect.height(),srcAdapted->format.bytesPerPixel);
-    }
-    srcAdapted->free();
-    delete srcAdapted;
-  }
+		//Convert pixel format of source to match destination
+		Graphics::Surface *srcAdapted = src.convertTo(dst.format);
+		//Get pointer for source buffer blit rectangle origin
+		const byte *srcBuffer = (const byte *)srcAdapted->getBasePtr(srcRect.left, srcRect.top);
+
+		//Default to blitting into origin of target surface if negative valued
+		if (dstPos.x < 0)
+			dstPos.x = 0;
+		if (dstPos.y < 0)
+			dstPos.y = 0;
+
+		//BUG TEST
+		//assert(dstPos == dstPos2);
+
+		//If _x & _y lie within destination surface
+		if (dstPos.x < dst.w && dstPos.y < dst.h) {
+			//Get pointer for destination buffer blit rectangle origin
+			byte *dstBuffer = (byte *)dst.getBasePtr(dstPos.x, dstPos.y);
+			Graphics::copyBlit(dstBuffer, srcBuffer, dst.pitch, srcAdapted->pitch, srcRect.width(), srcRect.height(), srcAdapted->format.bytesPerPixel);
+		}
+		srcAdapted->free();
+		delete srcAdapted;
+	}
 
 }
 /*/
@@ -560,50 +553,50 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Com
 //SIMPLIFIED FUNCTION
 //TODO - find bug that breaks panorama rotation.  Suspect problem with negative arguments of some sort.
 void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect , Graphics::Surface &dst, int _x, int _y) {
-	Common::Rect srcRect = _srcRect;
-	Common::Point dstPos = Common::Point(_x,_y);
-	//Default to using whole source surface
-	if (srcRect.isEmpty())
-		srcRect = Common::Rect(src.w, src.h);
+    Common::Rect srcRect = _srcRect;
+    Common::Point dstPos = Common::Point(_x,_y);
+    //Default to using whole source surface
+    if (srcRect.isEmpty())
+        srcRect = Common::Rect(src.w, src.h);
   //Ensure source rectangle does not read beyond bounds of source surface
-	srcRect.clip(src.w, src.h);
+    srcRect.clip(src.w, src.h);
 
-	//CODE IDENTICAL TO HERE
-	
-	//Ensure source rectangle does not write beyond bounds of destination surface & is valid
-	  //NB alters dstPos & srcRect!
-	Common::Rect::getBlitRect(dstPos, srcRect, Common::Rect(dst.w,dst.h));
+    //CODE IDENTICAL TO HERE
+
+    //Ensure source rectangle does not write beyond bounds of destination surface & is valid
+      //NB alters dstPos & srcRect!
+    Common::Rect::getBlitRect(dstPos, srcRect, Common::Rect(dst.w,dst.h));
 
   //CODE IDENTICAL FROM HERE
-  
-	//Abort if nothing to blit
-	if(!srcRect.isEmpty()) {
+
+    //Abort if nothing to blit
+    if(!srcRect.isEmpty()) {
     //Convert pixel format of source to match destination
-	  Graphics::Surface *srcAdapted = src.convertTo(dst.format);
-	  //Get pointer for source buffer blit rectangle origin
-	  const byte *srcBuffer = (const byte *)srcAdapted->getBasePtr(srcRect.left, srcRect.top); 
+      Graphics::Surface *srcAdapted = src.convertTo(dst.format);
+      //Get pointer for source buffer blit rectangle origin
+      const byte *srcBuffer = (const byte *)srcAdapted->getBasePtr(srcRect.left, srcRect.top);
     //If _x & _y lie within destination surface
     if (dstPos.x < dst.w && dstPos.y < dst.h) {
       //Get pointer for destination buffer blit rectangle origin
-	    byte *dstBuffer = (byte *)dst.getBasePtr(dstPos.x, dstPos.y);
-	    Graphics::copyBlit(dstBuffer,srcBuffer,dst.pitch,srcAdapted->pitch,srcRect.width(),srcRect.height(),srcAdapted->format.bytesPerPixel);
+        byte *dstBuffer = (byte *)dst.getBasePtr(dstPos.x, dstPos.y);
+        Graphics::copyBlit(dstBuffer,srcBuffer,dst.pitch,srcAdapted->pitch,srcRect.width(),srcRect.height(),srcAdapted->format.bytesPerPixel);
     }
-	  srcAdapted->free();
-	  delete srcAdapted;
+      srcAdapted->free();
+      delete srcAdapted;
   }
 }
 //*/
 
-void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect , Graphics::Surface &dst, int _x, int _y, uint32 colorkey) {
-  debug(9,"blitSurfaceToSurface");
+void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect, Graphics::Surface &dst, int _x, int _y, uint32 colorkey) {
+	debug(9, "blitSurfaceToSurface");
 	Common::Rect srcRect = _srcRect;
 	if (srcRect.isEmpty())
 		srcRect = Common::Rect(src.w, src.h);
 	srcRect.clip(src.w, src.h);
-	Common::Rect dstRect = Common::Rect(-_x + srcRect.left , -_y + srcRect.top, -_x + srcRect.left + dst.w, -_y + srcRect.top + dst.h);
+	Common::Rect dstRect = Common::Rect(-_x + srcRect.left, -_y + srcRect.top, -_x + srcRect.left + dst.w, -_y + srcRect.top + dst.h);
 	srcRect.clip(dstRect);
 
-  //Abort if nothing to blit
+	//Abort if nothing to blit
 	if (srcRect.isEmpty() || !srcRect.isValidRect())
 		return;
 
@@ -622,9 +615,9 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Com
 		yy = 0;
 
 	if (_x < dst.w && _y < dst.h) {
-	  byte *dstBuffer = (byte *)dst.getBasePtr(xx, yy);
-    Graphics::keyBlit(dstBuffer,srcBuffer,dst.pitch,srcAdapted->pitch,srcRect.width(),srcRect.height(),srcAdapted->format.bytesPerPixel,keycolor);
-  }
+		byte *dstBuffer = (byte *)dst.getBasePtr(xx, yy);
+		Graphics::keyBlit(dstBuffer, srcBuffer, dst.pitch, srcAdapted->pitch, srcRect.width(), srcRect.height(), srcAdapted->format.bytesPerPixel, keycolor);
+	}
 	srcAdapted->free();
 	delete srcAdapted;
 }
@@ -668,24 +661,24 @@ void RenderManager::blitSurfaceToMenu(const Graphics::Surface &src, int16 x, int
 }
 
 void RenderManager::clearMenuSurface(bool force, int32 colorkey) {
-  if(force)
-    _menuSurfaceDirtyRect = Common::Rect(_menuArea.width(), _menuArea.height());
-  if(!_menuSurfaceDirtyRect.isEmpty()) {
-    //Convert to local menuArea coordinates
-    Common::Rect letterbox = _menuLetterbox;
-    Common::Rect overlay =_menuOverlay;
-    letterbox.translate(-_menuArea.left, -_menuArea.top);
-    overlay.translate(-_menuArea.left, -_menuArea.top);
-	  Common::Rect _menuLetterboxDirty = _menuSurfaceDirtyRect.findIntersectingRect(letterbox);
-    if(!_menuLetterboxDirty.isEmpty())
-      _menuSurface.fillRect(_menuLetterboxDirty, 0);
-	  Common::Rect _menuOverlayDirty = _menuSurfaceDirtyRect.findIntersectingRect(overlay);
-    if(!_menuOverlayDirty.isEmpty()) {
-	    _menuSurface.fillRect(_menuOverlayDirty, colorkey);
-      //TODO - mark working window dirty here so that it will redraw & blank overlaid residue on next frame
-    }
-    _menuSurfaceDirtyRect = Common::Rect(0,0);
-  }
+	if (force)
+		_menuSurfaceDirtyRect = Common::Rect(_menuArea.width(), _menuArea.height());
+	if (!_menuSurfaceDirtyRect.isEmpty()) {
+		//Convert to local menuArea coordinates
+		Common::Rect letterbox = _menuLetterbox;
+		Common::Rect overlay = _menuOverlay;
+		letterbox.translate(-_menuArea.left, -_menuArea.top);
+		overlay.translate(-_menuArea.left, -_menuArea.top);
+		Common::Rect _menuLetterboxDirty = _menuSurfaceDirtyRect.findIntersectingRect(letterbox);
+		if (!_menuLetterboxDirty.isEmpty())
+			_menuSurface.fillRect(_menuLetterboxDirty, 0);
+		Common::Rect _menuOverlayDirty = _menuSurfaceDirtyRect.findIntersectingRect(overlay);
+		if (!_menuOverlayDirty.isEmpty()) {
+			_menuSurface.fillRect(_menuOverlayDirty, colorkey);
+			//TODO - mark working window dirty here so that it will redraw & blank overlaid residue on next frame
+		}
+		_menuSurfaceDirtyRect = Common::Rect(0, 0);
+	}
 }
 
 void RenderManager::blitSurfaceToText(const Graphics::Surface &src, int16 x, int16 y, int32 colorkey) {
@@ -700,28 +693,28 @@ void RenderManager::blitSurfaceToText(const Graphics::Surface &src, int16 x, int
 }
 
 void RenderManager::clearTextSurface(bool force, int32 colorkey) {
-  if(force)
-    _textSurfaceDirtyRect = Common::Rect(_textArea.width(),_textArea.height());
-  if(!_textSurfaceDirtyRect.isEmpty()) {
-    //Convert to local textArea coordinates
-    Common::Rect letterbox = _textLetterbox;
-    Common::Rect overlay =_textOverlay;
-    letterbox.translate(-_textArea.left, -_textArea.top);
-    overlay.translate(-_textArea.left, -_textArea.top);
-	  Common::Rect _textLetterboxDirty = _textSurfaceDirtyRect.findIntersectingRect(letterbox);
-    if(!_textLetterboxDirty.isEmpty())
-      _textSurface.fillRect(_textLetterboxDirty, 0);
-	  Common::Rect _textOverlayDirty = _textSurfaceDirtyRect.findIntersectingRect(overlay);
-    if(!_textOverlayDirty.isEmpty()) {
-	    _textSurface.fillRect(_textOverlayDirty, colorkey);
-      //TODO - mark working window dirty here so that it will redraw & blank overlaid residue on next frame
-    }
-    _textSurfaceDirtyRect = Common::Rect(0,0);
-  }
+	if (force)
+		_textSurfaceDirtyRect = Common::Rect(_textArea.width(), _textArea.height());
+	if (!_textSurfaceDirtyRect.isEmpty()) {
+		//Convert to local textArea coordinates
+		Common::Rect letterbox = _textLetterbox;
+		Common::Rect overlay = _textOverlay;
+		letterbox.translate(-_textArea.left, -_textArea.top);
+		overlay.translate(-_textArea.left, -_textArea.top);
+		Common::Rect _textLetterboxDirty = _textSurfaceDirtyRect.findIntersectingRect(letterbox);
+		if (!_textLetterboxDirty.isEmpty())
+			_textSurface.fillRect(_textLetterboxDirty, 0);
+		Common::Rect _textOverlayDirty = _textSurfaceDirtyRect.findIntersectingRect(overlay);
+		if (!_textOverlayDirty.isEmpty()) {
+			_textSurface.fillRect(_textOverlayDirty, colorkey);
+			//TODO - mark working window dirty here so that it will redraw & blank overlaid residue on next frame
+		}
+		_textSurfaceDirtyRect = Common::Rect(0, 0);
+	}
 }
 
 Graphics::Surface *RenderManager::getBkgRect(Common::Rect &rect) {
-  debug(11,"getBkgRect()");
+	debug(11, "getBkgRect()");
 	Common::Rect dst = rect;
 	dst.clip(_backgroundWidth, _backgroundHeight);
 	if (dst.isEmpty() || !dst.isValidRect())
@@ -745,79 +738,78 @@ Graphics::Surface *RenderManager::loadImage(const Common::Path &file, bool trans
 }
 
 void RenderManager::prepareBackground() {
-  debug(5,"prepareBackground()");
+	debug(5, "prepareBackground()");
 	_backgroundDirtyRect.clip(_backgroundWidth, _backgroundHeight);
-  switch(_renderTable.getRenderState()) {
-	  case RenderTable::PANORAMA: {
-		  // Calculate the visible portion of the background
-		  Common::Rect viewPort(_workingArea.width(), _workingArea.height());
-		  viewPort.translate(-(_workingAreaCenter.x - _backgroundOffset), 0);
-		  Common::Rect drawRect = _backgroundDirtyRect;
-		  drawRect.clip(viewPort);
-
-		  // Render the visible portion
-		  if (!drawRect.isEmpty())
-			  blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _workingAreaCenter.x - _backgroundOffset + drawRect.left, drawRect.top);
-
-		  // Mark the dirty portion of the surface
-		  _backgroundSurfaceDirtyRect = _backgroundDirtyRect;
-		  _backgroundSurfaceDirtyRect.translate(_workingAreaCenter.x - _backgroundOffset, 0);
-
-		  // Panorama mode allows the user to spin in circles. Therefore, we need to render
-		  // the portion of the image that wrapped to the other side of the screen
-		  if (_backgroundOffset < _workingAreaCenter.x) {
-			  viewPort.moveTo(-(_workingAreaCenter.x - (_backgroundOffset + _backgroundWidth)), 0);
-			  drawRect = _backgroundDirtyRect;
-			  drawRect.clip(viewPort);
-
-			  if (!drawRect.isEmpty())
-				  blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _workingAreaCenter.x - (_backgroundOffset + _backgroundWidth) + drawRect.left, drawRect.top);
-
-			  Common::Rect tmp = _backgroundDirtyRect;
-			  tmp.translate(_workingAreaCenter.x - (_backgroundOffset + _backgroundWidth), 0);
-			  if (!tmp.isEmpty())
-				  _backgroundSurfaceDirtyRect.extend(tmp);
-
-		  } 
-		  else if (_backgroundWidth - _backgroundOffset < _workingAreaCenter.x) {
-			  viewPort.moveTo(-(_workingAreaCenter.x + _backgroundWidth - _backgroundOffset), 0);
-			  drawRect = _backgroundDirtyRect;
-			  drawRect.clip(viewPort);
-
-			  if (!drawRect.isEmpty())
-				  blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _workingAreaCenter.x + _backgroundWidth - _backgroundOffset + drawRect.left, drawRect.top);
-
-			  Common::Rect tmp = _backgroundDirtyRect;
-			  tmp.translate(_workingAreaCenter.x + _backgroundWidth - _backgroundOffset, 0);
-			  if (!tmp.isEmpty())
-				  _backgroundSurfaceDirtyRect.extend(tmp);
-		  }
-	    break;
-	  }
-	  case RenderTable::TILT: {
-		  // Tilt doesn't allow wrapping, so we just do a simple clip
-		  Common::Rect viewPort(_workingArea.width(), _workingArea.height());
-		  viewPort.translate(0, -(_workingAreaCenter.y - _backgroundOffset));
-		  Common::Rect drawRect = _backgroundDirtyRect;
-		  drawRect.clip(viewPort);
-		  if (!drawRect.isEmpty())
-			  blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, drawRect.left, _workingAreaCenter.y - _backgroundOffset + drawRect.top);
-		  // Mark the dirty portion of the surface
-		  _backgroundSurfaceDirtyRect = _backgroundDirtyRect;
-		  _backgroundSurfaceDirtyRect.translate(0, _workingAreaCenter.y - _backgroundOffset);
-		  break;
-	  } 
-	  default: {
-		  if (!_backgroundDirtyRect.isEmpty())
-			  blitSurfaceToSurface(_currentBackgroundImage, _backgroundDirtyRect, _backgroundSurface, _backgroundDirtyRect.left, _backgroundDirtyRect.top);
-		  _backgroundSurfaceDirtyRect = _backgroundDirtyRect;
-		  break;
-	  }
+	switch (_renderTable.getRenderState()) {
+	case RenderTable::PANORAMA: {
+		// Calculate the visible portion of the background
+		Common::Rect viewPort(_workingArea.width(), _workingArea.height());
+		viewPort.translate(-(_workingAreaCenter.x - _backgroundOffset), 0);
+		Common::Rect drawRect = _backgroundDirtyRect;
+		drawRect.clip(viewPort);
+
+		// Render the visible portion
+		if (!drawRect.isEmpty())
+			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _workingAreaCenter.x - _backgroundOffset + drawRect.left, drawRect.top);
+
+		// Mark the dirty portion of the surface
+		_backgroundSurfaceDirtyRect = _backgroundDirtyRect;
+		_backgroundSurfaceDirtyRect.translate(_workingAreaCenter.x - _backgroundOffset, 0);
+
+		// Panorama mode allows the user to spin in circles. Therefore, we need to render
+		// the portion of the image that wrapped to the other side of the screen
+		if (_backgroundOffset < _workingAreaCenter.x) {
+			viewPort.moveTo(-(_workingAreaCenter.x - (_backgroundOffset + _backgroundWidth)), 0);
+			drawRect = _backgroundDirtyRect;
+			drawRect.clip(viewPort);
+
+			if (!drawRect.isEmpty())
+				blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _workingAreaCenter.x - (_backgroundOffset + _backgroundWidth) + drawRect.left, drawRect.top);
+
+			Common::Rect tmp = _backgroundDirtyRect;
+			tmp.translate(_workingAreaCenter.x - (_backgroundOffset + _backgroundWidth), 0);
+			if (!tmp.isEmpty())
+				_backgroundSurfaceDirtyRect.extend(tmp);
+
+		} else if (_backgroundWidth - _backgroundOffset < _workingAreaCenter.x) {
+			viewPort.moveTo(-(_workingAreaCenter.x + _backgroundWidth - _backgroundOffset), 0);
+			drawRect = _backgroundDirtyRect;
+			drawRect.clip(viewPort);
+
+			if (!drawRect.isEmpty())
+				blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _workingAreaCenter.x + _backgroundWidth - _backgroundOffset + drawRect.left, drawRect.top);
+
+			Common::Rect tmp = _backgroundDirtyRect;
+			tmp.translate(_workingAreaCenter.x + _backgroundWidth - _backgroundOffset, 0);
+			if (!tmp.isEmpty())
+				_backgroundSurfaceDirtyRect.extend(tmp);
+		}
+		break;
+	}
+	case RenderTable::TILT: {
+		// Tilt doesn't allow wrapping, so we just do a simple clip
+		Common::Rect viewPort(_workingArea.width(), _workingArea.height());
+		viewPort.translate(0, -(_workingAreaCenter.y - _backgroundOffset));
+		Common::Rect drawRect = _backgroundDirtyRect;
+		drawRect.clip(viewPort);
+		if (!drawRect.isEmpty())
+			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, drawRect.left, _workingAreaCenter.y - _backgroundOffset + drawRect.top);
+		// Mark the dirty portion of the surface
+		_backgroundSurfaceDirtyRect = _backgroundDirtyRect;
+		_backgroundSurfaceDirtyRect.translate(0, _workingAreaCenter.y - _backgroundOffset);
+		break;
+	}
+	default: {
+		if (!_backgroundDirtyRect.isEmpty())
+			blitSurfaceToSurface(_currentBackgroundImage, _backgroundDirtyRect, _backgroundSurface, _backgroundDirtyRect.left, _backgroundDirtyRect.top);
+		_backgroundSurfaceDirtyRect = _backgroundDirtyRect;
+		break;
+	}
 	}
 	// Clear the dirty rect since everything is clean now
 	_backgroundDirtyRect = Common::Rect();
 	_backgroundSurfaceDirtyRect.clip(_workingArea.width(), _workingArea.height());
-  debug(11,"~prepareBackground()");
+	debug(11, "~prepareBackground()");
 }
 
 Common::Point RenderManager::getBkgSize() {
@@ -838,41 +830,39 @@ void RenderManager::deleteEffect(uint32 ID) {
 }
 
 Common::Rect RenderManager::transformBackgroundSpaceRectToScreenSpace(const Common::Rect &src) {
-  debug(10,"transformBackgroundSpaceRectToScreenSpace");
+	debug(10, "transformBackgroundSpaceRectToScreenSpace");
 	Common::Rect tmp = src;
-  switch(_renderTable.getRenderState()) {
-	  case RenderTable::PANORAMA: {
-		  if (_backgroundOffset < _workingAreaCenter.x) {
-			  Common::Rect rScreen(_workingAreaCenter.x + _backgroundOffset, _workingArea.height());
-			  Common::Rect lScreen(_workingArea.width() - rScreen.width(), _workingArea.height());
-			  lScreen.translate(_backgroundWidth - lScreen.width(), 0);
-			  lScreen.clip(src);
-			  rScreen.clip(src);
-			  if (rScreen.width() < lScreen.width())
-				  tmp.translate(_workingAreaCenter.x - _backgroundOffset - _backgroundWidth, 0);
-			  else
-				  tmp.translate(_workingAreaCenter.x - _backgroundOffset, 0);
-		  } 
-		  else if (_backgroundWidth - _backgroundOffset < _workingAreaCenter.x) {
-			  Common::Rect rScreen(_workingAreaCenter.x - (_backgroundWidth - _backgroundOffset), _workingArea.height());
-			  Common::Rect lScreen(_workingArea.width() - rScreen.width(), _workingArea.height());
-			  lScreen.translate(_backgroundWidth - lScreen.width(), 0);
-			  lScreen.clip(src);
-			  rScreen.clip(src);
-			  if (lScreen.width() < rScreen.width())
-				  tmp.translate(_workingAreaCenter.x + (_backgroundWidth - _backgroundOffset), 0);
-			  else
-				  tmp.translate(_workingAreaCenter.x - _backgroundOffset, 0);
-		  } 
-		  else
-			  tmp.translate(_workingAreaCenter.x - _backgroundOffset, 0);
-	    break;
-	  }
-    case RenderTable::TILT:
-		  tmp.translate(0, (_workingAreaCenter.y - _backgroundOffset));
-		  break;
-	  default:
-	    break;
+	switch (_renderTable.getRenderState()) {
+	case RenderTable::PANORAMA: {
+		if (_backgroundOffset < _workingAreaCenter.x) {
+			Common::Rect rScreen(_workingAreaCenter.x + _backgroundOffset, _workingArea.height());
+			Common::Rect lScreen(_workingArea.width() - rScreen.width(), _workingArea.height());
+			lScreen.translate(_backgroundWidth - lScreen.width(), 0);
+			lScreen.clip(src);
+			rScreen.clip(src);
+			if (rScreen.width() < lScreen.width())
+				tmp.translate(_workingAreaCenter.x - _backgroundOffset - _backgroundWidth, 0);
+			else
+				tmp.translate(_workingAreaCenter.x - _backgroundOffset, 0);
+		} else if (_backgroundWidth - _backgroundOffset < _workingAreaCenter.x) {
+			Common::Rect rScreen(_workingAreaCenter.x - (_backgroundWidth - _backgroundOffset), _workingArea.height());
+			Common::Rect lScreen(_workingArea.width() - rScreen.width(), _workingArea.height());
+			lScreen.translate(_backgroundWidth - lScreen.width(), 0);
+			lScreen.clip(src);
+			rScreen.clip(src);
+			if (lScreen.width() < rScreen.width())
+				tmp.translate(_workingAreaCenter.x + (_backgroundWidth - _backgroundOffset), 0);
+			else
+				tmp.translate(_workingAreaCenter.x - _backgroundOffset, 0);
+		} else
+			tmp.translate(_workingAreaCenter.x - _backgroundOffset, 0);
+		break;
+	}
+	case RenderTable::TILT:
+		tmp.translate(0, (_workingAreaCenter.y - _backgroundOffset));
+		break;
+	default:
+		break;
 	}
 	return tmp;
 }
@@ -918,8 +908,7 @@ EffectMap *RenderManager::makeEffectMap(const Common::Point &xy, int16 depth, co
 				        (cC2 - stC2 < depth8) &&
 				        (cC3 - stC3 < depth8))
 					use = true;
-			} 
-			else { /* if (curClr < color) */
+			} else { /* if (curClr < color) */
 				if ((stC1 - cC1 < depth8) &&
 				        (stC2 - cC2 < depth8) &&
 				        (stC3 - cC3 < depth8))
@@ -1010,77 +999,77 @@ void RenderManager::updateRotation() {
 	if (_doubleFPS | !frameLimiter.isEnabled()) //Assuming 60fps when in Vsync mode.
 		_velocity /= 2;
 	if (_velocity) {
-		switch(_renderTable.getRenderState()) {
-		  case RenderTable::PANORAMA : {
-  			int16 startPosition = scriptManager->getStateValue(StateKey_ViewPos);
-		    int16 newPosition = startPosition + (_renderTable.getPanoramaReverse() ? -_velocity : _velocity);
-		    int16 zeroPoint = _renderTable.getPanoramaZeroPoint();
-		    if (startPosition >= zeroPoint && newPosition < zeroPoint)
-			    scriptManager->setStateValue(StateKey_Rounds, scriptManager->getStateValue(StateKey_Rounds) - 1);
-		    if (startPosition <= zeroPoint && newPosition > zeroPoint)
-			    scriptManager->setStateValue(StateKey_Rounds, scriptManager->getStateValue(StateKey_Rounds) + 1);
-		    int16 screenWidth = getBkgSize().x;
-		    if (screenWidth)
-			    newPosition %= screenWidth;
-		    if (newPosition < 0)
-			    newPosition += screenWidth;
-		    setBackgroundPosition(newPosition);
-		    break;
-	    }
-	    case RenderTable::TILT : {
-  			int16 startPosition = scriptManager->getStateValue(StateKey_ViewPos);
-			  int16 newPosition = startPosition + _velocity;
-			  int16 screenHeight = getBkgSize().y;
-			  int16 tiltGap = (int16)_renderTable.getTiltGap();
-			  if (newPosition >= (screenHeight - tiltGap))
-				  newPosition = screenHeight - tiltGap;
-			  if (newPosition <= tiltGap)
-				  newPosition = tiltGap;
-			  setBackgroundPosition(newPosition);
-			  break;
-		  }
-		  default:
-		    break;
+		switch (_renderTable.getRenderState()) {
+		case RenderTable::PANORAMA : {
+			int16 startPosition = scriptManager->getStateValue(StateKey_ViewPos);
+			int16 newPosition = startPosition + (_renderTable.getPanoramaReverse() ? -_velocity : _velocity);
+			int16 zeroPoint = _renderTable.getPanoramaZeroPoint();
+			if (startPosition >= zeroPoint && newPosition < zeroPoint)
+				scriptManager->setStateValue(StateKey_Rounds, scriptManager->getStateValue(StateKey_Rounds) - 1);
+			if (startPosition <= zeroPoint && newPosition > zeroPoint)
+				scriptManager->setStateValue(StateKey_Rounds, scriptManager->getStateValue(StateKey_Rounds) + 1);
+			int16 screenWidth = getBkgSize().x;
+			if (screenWidth)
+				newPosition %= screenWidth;
+			if (newPosition < 0)
+				newPosition += screenWidth;
+			setBackgroundPosition(newPosition);
+			break;
+		}
+		case RenderTable::TILT : {
+			int16 startPosition = scriptManager->getStateValue(StateKey_ViewPos);
+			int16 newPosition = startPosition + _velocity;
+			int16 screenHeight = getBkgSize().y;
+			int16 tiltGap = (int16)_renderTable.getTiltGap();
+			if (newPosition >= (screenHeight - tiltGap))
+				newPosition = screenHeight - tiltGap;
+			if (newPosition <= tiltGap)
+				newPosition = tiltGap;
+			setBackgroundPosition(newPosition);
+			break;
+		}
+		default:
+			break;
 		}
 	}
 }
 
 void RenderManager::checkBorders() {
-	switch(_renderTable.getRenderState()) {
-	  case RenderTable::PANORAMA: {
-		  int16 startPosition = _engine->getScriptManager()->getStateValue(StateKey_ViewPos);
-		  int16 newPosition = startPosition;
-		  int16 screenWidth = getBkgSize().x;
-		  if (screenWidth)
-			  newPosition %= screenWidth;
-		  if (newPosition < 0)
-			  newPosition += screenWidth;
-		  if (startPosition != newPosition)
-			  setBackgroundPosition(newPosition);
-	    break;
-	  } 
-	  case RenderTable::TILT: {
-		  int16 startPosition = _engine->getScriptManager()->getStateValue(StateKey_ViewPos);
-		  int16 newPosition = startPosition;
-		  int16 screenHeight = getBkgSize().y;
-		  int16 tiltGap = (int16)_renderTable.getTiltGap();
-		  if (newPosition >= (screenHeight - tiltGap))
-			  newPosition = screenHeight - tiltGap;
-		  if (newPosition <= tiltGap)
-			  newPosition = tiltGap;
-		  if (startPosition != newPosition)
-			  setBackgroundPosition(newPosition);
-		  break;
-	  }
-	  default: 
-	    break;
+	switch (_renderTable.getRenderState()) {
+	case RenderTable::PANORAMA: {
+		int16 startPosition = _engine->getScriptManager()->getStateValue(StateKey_ViewPos);
+		int16 newPosition = startPosition;
+		int16 screenWidth = getBkgSize().x;
+		if (screenWidth)
+			newPosition %= screenWidth;
+		if (newPosition < 0)
+			newPosition += screenWidth;
+		if (startPosition != newPosition)
+			setBackgroundPosition(newPosition);
+		break;
+	}
+	case RenderTable::TILT: {
+		int16 startPosition = _engine->getScriptManager()->getStateValue(StateKey_ViewPos);
+		int16 newPosition = startPosition;
+		int16 screenHeight = getBkgSize().y;
+		int16 tiltGap = (int16)_renderTable.getTiltGap();
+		if (newPosition >= (screenHeight - tiltGap))
+			newPosition = screenHeight - tiltGap;
+		if (newPosition <= tiltGap)
+			newPosition = tiltGap;
+		if (startPosition != newPosition)
+			setBackgroundPosition(newPosition);
+		break;
+	}
+	default:
+		break;
 	}
 }
 
 void RenderManager::rotateTo(int16 _toPos, int16 _time) {
 	if (_renderTable.getRenderState() != RenderTable::PANORAMA)
 		return;
-  debug(1,"Rotating panorama to %d", _toPos);
+	debug(1, "Rotating panorama to %d", _toPos);
 	if (_time == 0)
 		_time = 1;
 	int32 maxX = getBkgSize().x;
@@ -1093,8 +1082,7 @@ void RenderManager::rotateTo(int16 _toPos, int16 _time) {
 			dx = (_toPos + (maxX - curX)) / _time;
 		else
 			dx = -(curX - _toPos) / _time;
-	} 
-	else {
+	} else {
 		if (_toPos - curX > maxX / 2)
 			dx = -((maxX - _toPos) + curX) / _time;
 		else
@@ -1109,7 +1097,7 @@ void RenderManager::rotateTo(int16 _toPos, int16 _time) {
 		if (curX < 0)
 			curX = maxX - curX;
 		else if (curX >= maxX)
-			curX %= maxX;	
+			curX %= maxX;
 		setBackgroundPosition(curX);
 		prepareBackground();
 		renderSceneToScreen();
@@ -1119,9 +1107,9 @@ void RenderManager::rotateTo(int16 _toPos, int16 _time) {
 }
 
 void RenderManager::upscaleRect(Common::Rect &rect) {
-  Common::Rect _HDscreen = _widescreen ? _HDscreenAreaWide : _HDscreenArea;
-  Common::Rect _SDscreen = _widescreen ? _layout.workingArea : _layout.screenArea;
-  _SDscreen.moveTo(0,0);
+	Common::Rect _HDscreen = _widescreen ? _HDscreenAreaWide : _HDscreenArea;
+	Common::Rect _SDscreen = _widescreen ? _layout.workingArea : _layout.screenArea;
+	_SDscreen.moveTo(0, 0);
 	rect.top = rect.top * _HDscreen.height() / _SDscreen.height();
 	rect.left = rect.left * _HDscreen.width() / _SDscreen.width();
 	rect.bottom = rect.bottom * _HDscreen.height() / _SDscreen.height();
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index 98c88f4eef3..b02a1413ab0 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -66,12 +66,12 @@ private:
 
 	/**
 	 * A Rectangle representing the screen/window resolution.
-	 */	
+	 */
 	Common::Rect _screenArea;
-	
-	Common::Rect _HDscreenArea = Common::Rect(800,600);
-	Common::Rect _HDscreenAreaWide = Common::Rect(720,377);
-	
+
+	Common::Rect _HDscreenArea = Common::Rect(800, 600);
+	Common::Rect _HDscreenAreaWide = Common::Rect(720, 377);
+
 	Common::Point _textOffset;  //Position vector of text area origin relative to working window origin
 
 	/**
@@ -80,12 +80,12 @@ private:
 	 * edges of this Rectangle
 	 */
 	Common::Rect _workingArea;
-	
+
 	Common::Point _workingAreaCenter; //Center of the working area in working area coordinates
-	
+
 	/**
 	Managed surface representing physical screen; dirty rectangles will be handled automatically by this from now on
-    */
+	*/
 	Graphics::Screen _screen;
 
 	/** A buffer for background image that's being used to create the background */
@@ -120,7 +120,7 @@ private:
 	// Rectangle for subtitles & other messages
 	Common::Rect _textArea; //NB Screen coordinates
 	Common::Rect _textLetterbox;  //Section of text area outside working window, to be filled with black when blanked
-	Common::Rect _textOverlay;	//Section of text area to be filled with colorkey when blanked (may potentially intersect text letterbox area if screen/window is wider than working area!)
+	Common::Rect _textOverlay;  //Section of text area to be filled with colorkey when blanked (may potentially intersect text letterbox area if screen/window is wider than working area!)
 
 	// Buffer for drawing menu
 	Graphics::Surface _menuSurface;
@@ -130,17 +130,17 @@ private:
 	// Rectangle for menu area
 	Common::Rect _menuArea; //Screen coordinates
 	Common::Rect _menuLetterbox; //Section of menu area to be filled with black when blanked
-	Common::Rect _menuOverlay;	//Section of menu area to be filled with colorkey when blanked (may potentially intersect menu letterbox area if screen/window is wider than working area!)
+	Common::Rect _menuOverlay;  //Section of menu area to be filled with colorkey when blanked (may potentially intersect menu letterbox area if screen/window is wider than working area!)
 
 	//Buffer for streamed video playback
 //*
 	Graphics::ManagedSurface _vidManagedSurface;
-/*/
-  Graphics::Surface _vidSurface;
-//*/
-  
-  //Area of streamed video playback
-  Common::Rect _vidArea;
+	/*/
+	  Graphics::Surface _vidSurface;
+	//*/
+
+	//Area of streamed video playback
+	Common::Rect _vidArea;
 
 	// A buffer used for apply graphics effects
 	Graphics::Surface _effectSurface;
@@ -153,9 +153,9 @@ private:
 
 	// Visual effects list
 	EffectsList _effects;
-	
-	//Pointer to currently active backbuffer output surface 
-  Graphics::Surface *outputSurface;
+
+	//Pointer to currently active backbuffer output surface
+	Graphics::Surface *outputSurface;
 
 	bool _doubleFPS;
 	bool _widescreen;
@@ -169,15 +169,15 @@ public:
 	 * If streamMode is set true, all background processing is skipped and the previous framebuffer is used
 	 */
 	bool renderSceneToScreen(bool immediate = false, bool overlayOnly = false, bool preStream = false);
-	
+
 	Graphics::ManagedSurface &getVidSurface(Common::Rect &dstRect);  //dstRect is defined relative to working area origin
-	
+
 	Common::Rect getMenuArea() {
-	  return _menuArea;
-  }  
+		return _menuArea;
+	}
 	Common::Rect getWorkingArea() {
-	  return _workingArea;
-  }
+		return _workingArea;
+	}
 
 	/**
 	 * Blits the image or a portion of the image to the background.
@@ -263,12 +263,12 @@ public:
 	 * @param src       Source surface
 	 * @param _srcRect  Rectangle defining area of source surface to blit; if this rectangle is empty, entire source surface is blitted
 	 * @param dst       Destination surface
- 	 * @param x         Destination surface x coordinate
+	 * @param x         Destination surface x coordinate
 	 * @param y         Destination surface y coordinate
-	 */	
+	 */
 
-	void blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect , Graphics::Surface &dst, int _x, int _y);
-	void blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect , Graphics::Surface &dst, int _x, int _y, uint32 colorkey);
+	void blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect, Graphics::Surface &dst, int _x, int _y);
+	void blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect, Graphics::Surface &dst, int _x, int _y, uint32 colorkey);
 
 	// Blitting surface-to-background methods
 	void blitSurfaceToBkg(const Graphics::Surface &src, int x, int y, int32 colorkey = -1);
@@ -280,18 +280,18 @@ public:
 	 * Blit from source surface to menu area
 	 *
 	 * @param src       Source surface
- 	 * @param x         x coordinate relative to menu area origin
+	 * @param x         x coordinate relative to menu area origin
 	 * @param y         y coordinate relative to menu area origin
-	 */	
+	 */
 	void blitSurfaceToMenu(const Graphics::Surface &src, int16 x, int16 y, int32 colorkey = 0);
 
 	/**
 	 * Blit from source surface to text area
 	 *
 	 * @param src       Source surface
- 	 * @param x         x coordinate relative to text area origin
+	 * @param x         x coordinate relative to text area origin
 	 * @param y         y coordinate relative to text area origin
-	 */	
+	 */
 	void blitSurfaceToText(const Graphics::Surface &src, int16 x, int16 y, int32 colorkey = 0);
 
 	// Return background size
@@ -305,10 +305,10 @@ public:
 	Graphics::Surface *loadImage(const Common::Path &file, bool transposed);
 
 	// Clear whole/area of menu backbuffer
-	void clearMenuSurface(bool force=false, int32 colorkey = -1);
-	
+	void clearMenuSurface(bool force = false, int32 colorkey = -1);
+
 	// Clear whole/area of subtitle backbuffer
-	void clearTextSurface(bool force=false, int32 colorkey = -1);
+	void clearTextSurface(bool force = false, int32 colorkey = -1);
 
 	// Copy needed portion of background surface to workingArea surface
 	void prepareBackground();
@@ -363,7 +363,7 @@ public:
 	// Fill background surface by color
 	void bkgFill(uint8 r, uint8 g, uint8 b);
 //*/
-	
+
 	void checkBorders();
 	void rotateTo(int16 to, int16 time);
 	void updateRotation();
diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index 8cbb3745adc..8460a4bc4e8 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -34,15 +34,15 @@ RenderTable::RenderTable(ZVision *engine, uint numColumns, uint numRows, const G
 	: _engine(engine),
 	  _system(engine->_system),
 	  _numRows(numRows),
-    _numColumns(numColumns),
+	  _numColumns(numColumns),
 	  _renderState(FLAT),
 	  _pixelFormat(pixelFormat) {
 	assert(numRows != 0 && numColumns != 0);
 	_internalBuffer = new FilterPixel[numRows * numColumns];
 	memset(&_panoramaOptions, 0, sizeof(_panoramaOptions));
 	memset(&_tiltOptions, 0, sizeof(_tiltOptions));
-	halfRows = floor((_numRows-1)/2);
-	halfColumns = floor((_numColumns-1)/2);
+	halfRows = floor((_numRows - 1) / 2);
+	halfColumns = floor((_numColumns - 1) / 2);
 	halfWidth = (float)_numColumns / 2.0f - 0.5f;
 	halfHeight = (float)_numRows / 2.0f - 0.5f;
 }
@@ -54,22 +54,22 @@ RenderTable::~RenderTable() {
 void RenderTable::setRenderState(RenderState newState) {
 	_renderState = newState;
 	switch (newState) {
-	  case PANORAMA:
-		  _panoramaOptions.verticalFOV = Math::deg2rad<float>(27.0f);
-		  _panoramaOptions.linearScale = 0.55f;
-		  _panoramaOptions.reverse = false;
-		  _panoramaOptions.zeroPoint = 0;
-		  break;
-	  case TILT:
-		  _tiltOptions.verticalFOV = Math::deg2rad<float>(27.0f);
-		  _tiltOptions.linearScale = 0.65f;
-		  _tiltOptions.reverse = false;
-		  break;
-	  case FLAT:
-		  // Intentionally left empty
-		  break;
-	  default:
-		  break;
+	case PANORAMA:
+		_panoramaOptions.verticalFOV = Math::deg2rad<float>(27.0f);
+		_panoramaOptions.linearScale = 0.55f;
+		_panoramaOptions.reverse = false;
+		_panoramaOptions.zeroPoint = 0;
+		break;
+	case TILT:
+		_tiltOptions.verticalFOV = Math::deg2rad<float>(27.0f);
+		_tiltOptions.linearScale = 0.65f;
+		_tiltOptions.reverse = false;
+		break;
+	case FLAT:
+		// Intentionally left empty
+		break;
+	default:
+		break;
 	}
 }
 
@@ -89,37 +89,37 @@ const Common::Point RenderTable::convertWarpedCoordToFlatCoord(const Common::Poi
 
 /*/
 void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 destWidth, const Common::Rect &subRect) {
-	uint32 destOffset = 0;
+    uint32 destOffset = 0;
   uint32 sourceXIndex = 0;
   uint32 sourceYIndex = 0;
   if(highQuality) {
     //TODO - convert to high quality pixel filtering
-	  for (int16 y = subRect.top; y < subRect.bottom; ++y) {
-		  uint32 sourceOffset = y * _numColumns;
-		  for (int16 x = subRect.left; x < subRect.right; ++x) {
-			  uint32 normalizedX = x - subRect.left;
-			  uint32 index = sourceOffset + x;
-			  // RenderTable only stores offsets from the original coordinates
-			  sourceYIndex = y + _internalBuffer[index].Src.top;
-			  sourceXIndex = x + _internalBuffer[index].Src.left;
-			  destBuffer[destOffset + normalizedX] = sourceBuffer[sourceYIndex * _numColumns + sourceXIndex];
-		  }
-		  destOffset += destWidth;
-	  }
+      for (int16 y = subRect.top; y < subRect.bottom; ++y) {
+          uint32 sourceOffset = y * _numColumns;
+          for (int16 x = subRect.left; x < subRect.right; ++x) {
+              uint32 normalizedX = x - subRect.left;
+              uint32 index = sourceOffset + x;
+              // RenderTable only stores offsets from the original coordinates
+              sourceYIndex = y + _internalBuffer[index].Src.top;
+              sourceXIndex = x + _internalBuffer[index].Src.left;
+              destBuffer[destOffset + normalizedX] = sourceBuffer[sourceYIndex * _numColumns + sourceXIndex];
+          }
+          destOffset += destWidth;
+      }
   }
   else {
-	  for (int16 y = subRect.top; y < subRect.bottom; ++y) {
-		  uint32 sourceOffset = y * _numColumns;
-		  for (int16 x = subRect.left; x < subRect.right; ++x) {
-			  uint32 normalizedX = x - subRect.left;
-			  uint32 index = sourceOffset + x;
-			  // RenderTable only stores offsets from the original coordinates
-			  sourceYIndex = y + _internalBuffer[index].Src.top;
-			  sourceXIndex = x + _internalBuffer[index].Src.left;
-			  destBuffer[destOffset + normalizedX] = sourceBuffer[sourceYIndex * _numColumns + sourceXIndex];
-		  }
-		  destOffset += destWidth;
-	  }
+      for (int16 y = subRect.top; y < subRect.bottom; ++y) {
+          uint32 sourceOffset = y * _numColumns;
+          for (int16 x = subRect.left; x < subRect.right; ++x) {
+              uint32 normalizedX = x - subRect.left;
+              uint32 index = sourceOffset + x;
+              // RenderTable only stores offsets from the original coordinates
+              sourceYIndex = y + _internalBuffer[index].Src.top;
+              sourceXIndex = x + _internalBuffer[index].Src.left;
+              destBuffer[destOffset + normalizedX] = sourceBuffer[sourceYIndex * _numColumns + sourceXIndex];
+          }
+          destOffset += destWidth;
+      }
   }
 }
 //*/
@@ -128,162 +128,160 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 	destOffset = 0;
 	uint16 *sourceBuffer = (uint16 *)srcBuf->getPixels();
 	uint16 *destBuffer = (uint16 *)dstBuf->getPixels();
-	if(highQuality != _highQuality) {
-	  _highQuality = highQuality;
-	  generateRenderTable();
+	if (highQuality != _highQuality) {
+		_highQuality = highQuality;
+		generateRenderTable();
 	}
-  uint32 mutationTime = _system->getMillis();
-  if(_highQuality) {
-    //Apply bilinear interpolation
-	  FilterPixel _curP;
-	  for (int16 y = 0; y < srcBuf->h; ++y) {
-		  sourceOffset = y * _numColumns;
-		  for (int16 x = 0; x < srcBuf->w; ++x) {
-			  _curP = _internalBuffer[sourceOffset + x];
-			  srcIndexYT = y + _curP.Src.top;
-			  srcIndexYB = y + _curP.Src.bottom;
-			  srcIndexXL = x + _curP.Src.left;
-			  srcIndexXR = x + _curP.Src.right;
-        splitColor(sourceBuffer[srcIndexYT * _numColumns + srcIndexXL], rTL, gTL, bTL);
-        splitColor(sourceBuffer[srcIndexYT * _numColumns + srcIndexXR], rTR, gTR, bTR);
-        splitColor(sourceBuffer[srcIndexYB * _numColumns + srcIndexXL], rBL, gBL, bBL);
-        splitColor(sourceBuffer[srcIndexYB * _numColumns + srcIndexXR], rBR, gBR, bBR);
-        rF = _curP.fTL*rTL + _curP.fTR*rTR + _curP.fBL*rBL + _curP.fBR*rBR;
-        gF = _curP.fTL*gTL + _curP.fTR*gTR + _curP.fBL*gBL + _curP.fBR*gBR;
-        bF = _curP.fTL*bTL + _curP.fTR*bTR + _curP.fBL*bBL + _curP.fBR*bBR;
-        destBuffer[destOffset] = mergeColor(rF,gF,bF);
-		    destOffset++;
-	      /*/
-        if(Common::Point(x,y)==testPixel) {
-          debug(2,"\tMutated test pixel %d, %d", x, y);
-          debug(2,"\tfX: %f, fY: %f", _curP.fX, _curP.fY);
-          debug(2,"\tYT: %d, YB: %d, XL: %d XR: %d", srcIndexYT, srcIndexYB, srcIndexXL, srcIndexXR);
-        } 
-        //*/
-      }
-    }
+	uint32 mutationTime = _system->getMillis();
+	if (_highQuality) {
+		//Apply bilinear interpolation
+		FilterPixel _curP;
+		for (int16 y = 0; y < srcBuf->h; ++y) {
+			sourceOffset = y * _numColumns;
+			for (int16 x = 0; x < srcBuf->w; ++x) {
+				_curP = _internalBuffer[sourceOffset + x];
+				srcIndexYT = y + _curP.Src.top;
+				srcIndexYB = y + _curP.Src.bottom;
+				srcIndexXL = x + _curP.Src.left;
+				srcIndexXR = x + _curP.Src.right;
+				splitColor(sourceBuffer[srcIndexYT * _numColumns + srcIndexXL], rTL, gTL, bTL);
+				splitColor(sourceBuffer[srcIndexYT * _numColumns + srcIndexXR], rTR, gTR, bTR);
+				splitColor(sourceBuffer[srcIndexYB * _numColumns + srcIndexXL], rBL, gBL, bBL);
+				splitColor(sourceBuffer[srcIndexYB * _numColumns + srcIndexXR], rBR, gBR, bBR);
+				rF = _curP.fTL * rTL + _curP.fTR * rTR + _curP.fBL * rBL + _curP.fBR * rBR;
+				gF = _curP.fTL * gTL + _curP.fTR * gTR + _curP.fBL * gBL + _curP.fBR * gBR;
+				bF = _curP.fTL * bTL + _curP.fTR * bTR + _curP.fBL * bBL + _curP.fBR * bBR;
+				destBuffer[destOffset] = mergeColor(rF, gF, bF);
+				destOffset++;
+				/*/
+				if(Common::Point(x,y)==testPixel) {
+				debug(2,"\tMutated test pixel %d, %d", x, y);
+				debug(2,"\tfX: %f, fY: %f", _curP.fX, _curP.fY);
+				debug(2,"\tYT: %d, YB: %d, XL: %d XR: %d", srcIndexYT, srcIndexYB, srcIndexXL, srcIndexXR);
+				}
+				//*/
+			}
+		}
+	} else {
+		//Apply nearest-neighbour interpolation
+		for (int16 y = 0; y < srcBuf->h; ++y) {
+			sourceOffset = y * _numColumns;
+			for (int16 x = 0; x < srcBuf->w; ++x) {
+				index = sourceOffset + x;
+				// RenderTable only stores offsets from the original coordinates
+				srcIndexXL = x + (_internalBuffer[index].xDir ? _internalBuffer[index].Src.right : _internalBuffer[index].Src.left);
+				srcIndexYT = y + (_internalBuffer[index].yDir ? _internalBuffer[index].Src.bottom : _internalBuffer[index].Src.top);
+				destBuffer[destOffset] = sourceBuffer[srcIndexYT * _numColumns + srcIndexXL];
+				destOffset++;
+			}
+		}
 	}
-  else {
-    //Apply nearest-neighbour interpolation
-	  for (int16 y = 0; y < srcBuf->h; ++y) {
-		  sourceOffset = y * _numColumns;
-		  for (int16 x = 0; x < srcBuf->w; ++x) {
-			  index = sourceOffset + x;
-			  // RenderTable only stores offsets from the original coordinates
-    		srcIndexXL = x + (_internalBuffer[index].xDir ? _internalBuffer[index].Src.right : _internalBuffer[index].Src.left);			  
-			  srcIndexYT = y + (_internalBuffer[index].yDir ? _internalBuffer[index].Src.bottom : _internalBuffer[index].Src.top);
-			  destBuffer[destOffset] = sourceBuffer[srcIndexYT * _numColumns + srcIndexXL];
-			  destOffset++;
-		  }
-	  }
-  }
-  mutationTime = _system->getMillis() - mutationTime;
-  debug(5,"\tPanorama mutation time %dms, %s quality", mutationTime, _highQuality? "high" : "low");
+	mutationTime = _system->getMillis() - mutationTime;
+	debug(5, "\tPanorama mutation time %dms, %s quality", mutationTime, _highQuality ? "high" : "low");
 }
 
 void RenderTable::generateRenderTable() {
 	switch (_renderState) {
-	  case RenderTable::PANORAMA: {
-      generateLookupTable(false);
-		  break;
-	  }
-	  case RenderTable::TILT:
-	    generateLookupTable(true);
-		  break;
-	  case RenderTable::FLAT:
-		  // Intentionally left empty
-		  break;
-	  default:
-		  break;
+	case RenderTable::PANORAMA: {
+		generateLookupTable(false);
+		break;
+	}
+	case RenderTable::TILT:
+		generateLookupTable(true);
+		break;
+	case RenderTable::FLAT:
+		// Intentionally left empty
+		break;
+	default:
+		break;
 	}
 }
 
 void RenderTable::generateLookupTable(bool tilt) {
-  debug(1,"Generating %s lookup table.", tilt ? "tilt" : "panorama");
-	debug(5,"halfWidth %f, halfHeight %f", halfWidth, halfHeight);
-	debug(5,"halfRows %d, halfColumns %d", halfRows, halfColumns);
-  uint32 generationTime = _system->getMillis();
+	debug(1, "Generating %s lookup table.", tilt ? "tilt" : "panorama");
+	debug(5, "halfWidth %f, halfHeight %f", halfWidth, halfHeight);
+	debug(5, "halfRows %d, halfColumns %d", halfRows, halfColumns);
+	uint32 generationTime = _system->getMillis();
 	float alpha, cosAlpha, polarCoordInCylinderCoords, linearCoordInCylinderCoords, cylinderRadius, xOffset, yOffset;
 	uint32 indexTL, indexBL, indexTR, indexBR;
-	uint x=0;
-	uint y=0;
-	auto outerLoop = [&](uint &polarCoord, float &halfPolarSize, float &scale) {
-    //polarCoord is the coordinate of the working window pixel parallel to the direction of camera rotation
-    //halfPolarSize is the distance from the central axis to the outermost working window pixel in the direction of camera rotation
+	uint x = 0;
+	uint y = 0;
+	auto outerLoop = [&](uint & polarCoord, float & halfPolarSize, float & scale) {
+		//polarCoord is the coordinate of the working window pixel parallel to the direction of camera rotation
+		//halfPolarSize is the distance from the central axis to the outermost working window pixel in the direction of camera rotation
 		//alpha represents the angle in the direction of camera rotation between the view axis and the centre of a pixel at the given polar coordinate
 		alpha = atan(((float)polarCoord - halfPolarSize) / cylinderRadius);
 		// To map the polar coordinate to the cylinder surface coordinates, we just need to calculate the arc length
 		// We also scale it by linearScale
 		polarCoordInCylinderCoords = (cylinderRadius * scale * alpha) + halfPolarSize;
 		cosAlpha = cos(alpha);
-  };	  
-  auto innerLoop = [&](uint &polarCoord, uint &linearCoord, float &halfLinearSize,  float &polarOffset, float &linearOffset) {
+	};
+	auto innerLoop = [&](uint & polarCoord, uint & linearCoord, float & halfLinearSize,  float & polarOffset, float & linearOffset) {
 		// To calculate linear coordinate in cylinder coordinates, we can do similar triangles comparison,
 		// comparing the triangle from the center to the screen and from the center to the edge of the cylinder
 		linearCoordInCylinderCoords = halfLinearSize + ((float)linearCoord - halfLinearSize) * cosAlpha;
 		linearOffset = linearCoordInCylinderCoords - linearCoord;
-    polarOffset = polarCoordInCylinderCoords - polarCoord;
-/*
-    bool _printDebug = (Common::Point(x,y)==testPixel);
-    if(_printDebug) {
-      debug(5,"\tGenerating test pixel %d, %d", x, y);
-      debug(5,"\tOffsets %f,%f", xOffset, yOffset);
-    }
-*/ 
+		polarOffset = polarCoordInCylinderCoords - polarCoord;
+		/*
+		    bool _printDebug = (Common::Point(x,y)==testPixel);
+		    if(_printDebug) {
+		      debug(5,"\tGenerating test pixel %d, %d", x, y);
+		      debug(5,"\tOffsets %f,%f", xOffset, yOffset);
+		    }
+		*/
 		// Only store the (x,y) offsets instead of the absolute positions
 //		_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality, _printDebug);
 		_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality);
-    //Transformation is both horizontally and vertically symmetrical about the camera axis,
-    //We can thus save on trigonometric calculations by computing one quarter of the transformation matrix and then mirroring it in both X & Y:
+		//Transformation is both horizontally and vertically symmetrical about the camera axis,
+		//We can thus save on trigonometric calculations by computing one quarter of the transformation matrix and then mirroring it in both X & Y:
 		_internalBuffer[indexBL] = _internalBuffer[indexTL];
 		_internalBuffer[indexBL].flipV();
 		_internalBuffer[indexTR] = _internalBuffer[indexTL];
 		_internalBuffer[indexTR].flipH();
 		_internalBuffer[indexBR] = _internalBuffer[indexBL];
 		_internalBuffer[indexBR].flipH();
-  };
-  if(tilt) {
-    uint32 columnIndexTL, columnIndexBL, columnIndexTR, columnIndexBR;
-	  cylinderRadius = (halfWidth + 0.5f) / tan(_tiltOptions.verticalFOV);
-	  _tiltOptions.gap = cylinderRadius * atan2((float)(halfHeight / cylinderRadius), 1.0f) * _tiltOptions.linearScale;
-	  for (y = 0; y <= halfRows; ++y) {
-	    outerLoop(y, halfHeight, _tiltOptions.linearScale);
-		  columnIndexTL = y * _numColumns;
-		  columnIndexBL = (_numRows-(y+1)) * _numColumns;
-		  columnIndexTR = columnIndexTL + (_numColumns - 1);
-		  columnIndexBR = columnIndexBL + (_numColumns - 1);
-	    for (x = 0; x <= halfColumns; ++x) {
-			  indexTL = columnIndexTL + x;
-			  indexBL = columnIndexBL + x;
-			  indexTR = columnIndexTR - x;
-			  indexBR = columnIndexBR - x;
-	      innerLoop(y, x, halfWidth, yOffset, xOffset);
-      }
-    }
+	};
+	if (tilt) {
+		uint32 columnIndexTL, columnIndexBL, columnIndexTR, columnIndexBR;
+		cylinderRadius = (halfWidth + 0.5f) / tan(_tiltOptions.verticalFOV);
+		_tiltOptions.gap = cylinderRadius * atan2((float)(halfHeight / cylinderRadius), 1.0f) * _tiltOptions.linearScale;
+		for (y = 0; y <= halfRows; ++y) {
+			outerLoop(y, halfHeight, _tiltOptions.linearScale);
+			columnIndexTL = y * _numColumns;
+			columnIndexBL = (_numRows - (y + 1)) * _numColumns;
+			columnIndexTR = columnIndexTL + (_numColumns - 1);
+			columnIndexBR = columnIndexBL + (_numColumns - 1);
+			for (x = 0; x <= halfColumns; ++x) {
+				indexTL = columnIndexTL + x;
+				indexBL = columnIndexBL + x;
+				indexTR = columnIndexTR - x;
+				indexBR = columnIndexBR - x;
+				innerLoop(y, x, halfWidth, yOffset, xOffset);
+			}
+		}
+	} else {
+		uint32 rowIndexT, rowIndexB, columnIndexL, columnIndexR;
+		cylinderRadius = (halfHeight + 0.5f) / tan(_panoramaOptions.verticalFOV);
+		for (x = 0; x <= halfColumns; ++x) {
+			columnIndexL = x;
+			columnIndexR = (_numColumns - 1) - x;
+			rowIndexT = 0;
+			rowIndexB = _numColumns * (_numRows - 1);
+			outerLoop(x, halfWidth, _panoramaOptions.linearScale);
+			for (y = 0; y <= halfRows; ++y) {
+				indexTL = rowIndexT + columnIndexL;
+				indexBL = rowIndexB + columnIndexL;
+				indexTR = rowIndexT + columnIndexR;
+				indexBR = rowIndexB + columnIndexR;
+				innerLoop(x, y, halfHeight, xOffset, yOffset);
+				rowIndexT += _numColumns;
+				rowIndexB -= _numColumns;
+			}
+		}
 	}
-  else {
-    uint32 rowIndexT, rowIndexB, columnIndexL, columnIndexR;
-    cylinderRadius = (halfHeight + 0.5f) / tan(_panoramaOptions.verticalFOV);
-	  for (x = 0; x <= halfColumns; ++x) {
-  		columnIndexL = x;
-		  columnIndexR = (_numColumns - 1) - x;
-		  rowIndexT = 0;
-		  rowIndexB = _numColumns * (_numRows - 1);
-	    outerLoop(x, halfWidth, _panoramaOptions.linearScale);
-		  for (y = 0; y <= halfRows; ++y) {
-		    indexTL = rowIndexT + columnIndexL;
-		    indexBL = rowIndexB + columnIndexL;
-		    indexTR = rowIndexT + columnIndexR;
-		    indexBR = rowIndexB + columnIndexR;
-		    innerLoop(x, y, halfHeight, xOffset, yOffset);
-		    rowIndexT += _numColumns;
-		    rowIndexB -= _numColumns;
-	    }
-	  }
-  }
-  generationTime = _system->getMillis() - generationTime;		  
-	debug(1,"Render table generated, %s quality", _highQuality ? "high" : "low");
-  debug(1,"\tRender table generation time %dms", generationTime);
+	generationTime = _system->getMillis() - generationTime;
+	debug(1, "Render table generated, %s quality", _highQuality ? "high" : "low");
+	debug(1, "\tRender table generation time %dms", generationTime);
 }
 
 void RenderTable::setPanoramaFoV(float fov) {
@@ -331,24 +329,24 @@ float RenderTable::getTiltGap() {
 }
 
 float RenderTable::getAngle() {
-	switch(_renderState) {
-	  case TILT:
-  		return Math::rad2deg<float>(_tiltOptions.verticalFOV);
-		case PANORAMA:
-		  return Math::rad2deg<float>(_panoramaOptions.verticalFOV);
-	  default:
-  		return 1.0;
+	switch (_renderState) {
+	case TILT:
+		return Math::rad2deg<float>(_tiltOptions.verticalFOV);
+	case PANORAMA:
+		return Math::rad2deg<float>(_panoramaOptions.verticalFOV);
+	default:
+		return 1.0;
 	}
 }
 
 float RenderTable::getLinscale() {
-	switch(_renderState) {
-	  case TILT:
-  		return _tiltOptions.linearScale;
-	  case PANORAMA:
-  		return _panoramaOptions.linearScale;
-	  default:
-  		return 1.0;
+	switch (_renderState) {
+	case TILT:
+		return _tiltOptions.linearScale;
+	case PANORAMA:
+		return _panoramaOptions.linearScale;
+	default:
+		return 1.0;
 	}
 }
 
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index ccb24aea097..8ec49d46a81 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -31,65 +31,64 @@ namespace ZVision {
 
 class FilterPixel {
 public:
-  //Bitfields representing sequential direction of contraction
-  bool xDir = 0; //0 left, 1 right
-  bool yDir = 0; //0 up, 1 down
-  Common::Rect Src = Common::Rect(0,0);  //Coordinates of four panorama image pixels around actual working window pixel
-  
-  float fX, fY, fTL, fTR, fBL, fBR;
-  
+	//Bitfields representing sequential direction of contraction
+	bool xDir = 0; //0 left, 1 right
+	bool yDir = 0; //0 up, 1 down
+	Common::Rect Src = Common::Rect(0, 0); //Coordinates of four panorama image pixels around actual working window pixel
+
+	float fX, fY, fTL, fTR, fBL, fBR;
+
 //  bool _printDebug = false;
-  
-  FilterPixel() {};
+
+	FilterPixel() {};
 //  FilterPixel(float x, float y, bool highQuality=false, bool printDebug=false) {
-  FilterPixel(float x, float y, bool highQuality=false) {
-    Src.left = int16(floor(x));
-    Src.right = int16(ceil(x));
-	  Src.top = int16(floor(y));
-	  Src.bottom = int16(ceil(y));
-/*
-	  _printDebug = printDebug;
-    if(_printDebug)
-      debug(5,"\tTarget pixel offset: %f, %f", x, y);
-*/
-    if(highQuality) {
-      fX = x-(float)Src.left;
-      fY = y-(float)Src.top;
-      fTL = (1-fX)*(1-fY);
-      fTR = fX*(1-fY);
-      fBL = (1-fX)*fY;
-      fBR = fX*fY;
-/*
-      if(_printDebug)
-        debug(5,"fX: %f, fY: %f, fTL:%f, fTR:%f, fBL:%f, fBR:%f", fX, fY, fTL, fTR, fBL, fBR);
-*/
-    }
-	  else {
-      //Nearest neighbour
-		  xDir = (x-Src.left) > 0.5f;
-		  yDir = (y-Src.top) > 0.5f;
-/*
-      if(_printDebug)
-        debug(5,"\tNearest neighbour, xDir: 0x%X, yDir: 0x%X", xDir, yDir);
-*/
-	  }
-  };
-  ~FilterPixel() {};
-  inline void flipH() {
-    Src.left = -Src.left;
-    Src.right = -Src.right;
-  };
-  inline void flipV() {
-    Src.top = -Src.top;
-    Src.bottom = -Src.bottom;
-  };
+	FilterPixel(float x, float y, bool highQuality = false) {
+		Src.left = int16(floor(x));
+		Src.right = int16(ceil(x));
+		Src.top = int16(floor(y));
+		Src.bottom = int16(ceil(y));
+		/*
+		      _printDebug = printDebug;
+		    if(_printDebug)
+		      debug(5,"\tTarget pixel offset: %f, %f", x, y);
+		*/
+		if (highQuality) {
+			fX = x - (float)Src.left;
+			fY = y - (float)Src.top;
+			fTL = (1 - fX) * (1 - fY);
+			fTR = fX * (1 - fY);
+			fBL = (1 - fX) * fY;
+			fBR = fX * fY;
+			/*
+			      if(_printDebug)
+			        debug(5,"fX: %f, fY: %f, fTL:%f, fTR:%f, fBL:%f, fBR:%f", fX, fY, fTL, fTR, fBL, fBR);
+			*/
+		} else {
+			//Nearest neighbour
+			xDir = (x - Src.left) > 0.5f;
+			yDir = (y - Src.top) > 0.5f;
+			/*
+			      if(_printDebug)
+			        debug(5,"\tNearest neighbour, xDir: 0x%X, yDir: 0x%X", xDir, yDir);
+			*/
+		}
+	};
+	~FilterPixel() {};
+	inline void flipH() {
+		Src.left = -Src.left;
+		Src.right = -Src.right;
+	};
+	inline void flipV() {
+		Src.top = -Src.top;
+		Src.bottom = -Src.bottom;
+	};
 };
 
 class RenderTable {
 public:
 	RenderTable(ZVision *engine, uint numRows, uint numColumns, const Graphics::PixelFormat pixelFormat);
 	~RenderTable();
-	
+
 //	Common::Point testPixel = Common::Point(255,0);
 
 public:
@@ -104,28 +103,28 @@ private:
 	OSystem *_system;
 	uint _numRows, _numColumns, halfRows, halfColumns; //Working area width, height; half width, half height, in whole pixels
 	float halfWidth, halfHeight;  //Centre axis to midpoint of outermost pixel
-  FilterPixel *_internalBuffer;
+	FilterPixel *_internalBuffer;
 	RenderState _renderState;
 	bool _highQuality = false;
 	const Graphics::PixelFormat _pixelFormat;
-	
+
 	uint32 index;
-  uint32 sourceOffset, destOffset;
-  uint32 srcIndexXL, srcIndexXR, srcIndexYT, srcIndexYB;
-  uint32 rTL,rTR,rBL,rBR,rF;
-  uint32 gTL,gTR,gBL,gBR,gF;
-  uint32 bTL,bTR,bBL,bBR,bF;
-	
-  inline void splitColor(uint16 &color, uint32 &r, uint32 &g, uint32 &b) {
-    //NB Left & right shifting unnecessary for interpolating & recombining, so not bothering in order to save cycles
-    r = color & 0x001f;
-    g = color & 0x03e0;
-    b = color & 0x7c00;
-  };
-  inline uint16 mergeColor(uint32 &r, uint32 &g, uint32 &b) const {
-    //NB Red uses the lowest bits in RGB555 and so doesn't need its fractional bits masked away after averaging
-    return r | (g & 0x03e0) | (b & 0x7c00);
-  };
+	uint32 sourceOffset, destOffset;
+	uint32 srcIndexXL, srcIndexXR, srcIndexYT, srcIndexYB;
+	uint32 rTL, rTR, rBL, rBR, rF;
+	uint32 gTL, gTR, gBL, gBR, gF;
+	uint32 bTL, bTR, bBL, bBR, bF;
+
+	inline void splitColor(uint16 &color, uint32 &r, uint32 &g, uint32 &b) {
+		//NB Left & right shifting unnecessary for interpolating & recombining, so not bothering in order to save cycles
+		r = color & 0x001f;
+		g = color & 0x03e0;
+		b = color & 0x7c00;
+	};
+	inline uint16 mergeColor(uint32 &r, uint32 &g, uint32 &b) const {
+		//NB Red uses the lowest bits in RGB555 and so doesn't need its fractional bits masked away after averaging
+		return r | (g & 0x03e0) | (b & 0x7c00);
+	};
 
 
 	struct {
@@ -152,23 +151,23 @@ public:
 	const Common::Point convertWarpedCoordToFlatCoord(const Common::Point &point);  //input point in working area coordinates
 
 //	void mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 destWidth, const Common::Rect &subRect);
-  void mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf, bool filter=false);
-	
+	void mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf, bool filter = false);
+
 	template <typename I>
-	Common::String pixelToBinary(I &pixel, bool splitColors=true) {
-	  uint8 bits = sizeof(pixel) << 3;
-    Common::String str("0b");
-    I spaceMask = 0;
-    for(uint8 i = 0; i < 3; i++)
-      spaceMask = (spaceMask << 5) + 0x10;
-	  for(I mask = 0x01 << (bits-1); mask; mask >>= 1) {
-	    if(splitColors && (spaceMask & mask))
-	      str += " ";
-      str += mask & pixel ? "1" : "0";
-    }
-    return str;
+	Common::String pixelToBinary(I &pixel, bool splitColors = true) {
+		uint8 bits = sizeof(pixel) << 3;
+		Common::String str("0b");
+		I spaceMask = 0;
+		for (uint8 i = 0; i < 3; i++)
+			spaceMask = (spaceMask << 5) + 0x10;
+		for (I mask = 0x01 << (bits - 1); mask; mask >>= 1) {
+			if (splitColors && (spaceMask & mask))
+				str += " ";
+			str += mask & pixel ? "1" : "0";
+		}
+		return str;
 	}
-	
+
 	void generateRenderTable();
 
 	void setPanoramaFoV(float fov); //Degrees
@@ -187,7 +186,7 @@ public:
 	float getLinscale();
 
 private:
-  void generateLookupTable(bool tilt = false);
+	void generateLookupTable(bool tilt = false);
 	void generatePanoramaLookupTable();
 //	Common::Point generatePanoramaLookupPoint();
 	void generateTiltLookupTable();
diff --git a/engines/zvision/metaengine.cpp b/engines/zvision/metaengine.cpp
index c839d442815..5601ecd6a47 100644
--- a/engines/zvision/metaengine.cpp
+++ b/engines/zvision/metaengine.cpp
@@ -161,21 +161,21 @@ public:
 
 bool ZVisionMetaEngine::hasFeature(MetaEngineFeature f) const {
 	return
-		(f == kSupportsListSaves) ||
-		(f == kSupportsLoadingDuringStartup) ||
-		(f == kSupportsDeleteSave) ||
-		(f == kSavesSupportMetaInfo) ||
-		(f == kSavesSupportThumbnail) ||
-		(f == kSavesSupportCreationDate) ||
-		(f == kSavesSupportPlayTime) ||
-		(f == kSimpleSavesNames);
+	    (f == kSupportsListSaves) ||
+	    (f == kSupportsLoadingDuringStartup) ||
+	    (f == kSupportsDeleteSave) ||
+	    (f == kSavesSupportMetaInfo) ||
+	    (f == kSavesSupportThumbnail) ||
+	    (f == kSavesSupportCreationDate) ||
+	    (f == kSavesSupportPlayTime) ||
+	    (f == kSimpleSavesNames);
 }
 
 bool ZVision::ZVision::hasFeature(EngineFeature f) const {
 	return
-		(f == kSupportsReturnToLauncher) ||
-		(f == kSupportsLoadingDuringRuntime) ||
-		(f == kSupportsSavingDuringRuntime);
+	    (f == kSupportsReturnToLauncher) ||
+	    (f == kSupportsLoadingDuringRuntime) ||
+	    (f == kSupportsSavingDuringRuntime);
 }
 
 Common::Error ZVision::ZVision::loadGameState(int slot) {
@@ -325,7 +325,7 @@ Common::KeymapArray ZVisionMetaEngine::initKeymaps(const char *target) const {
 }
 
 Common::Error ZVisionMetaEngine::createInstance(OSystem *syst, Engine **engine, const ZVision::ZVisionGameDescription *desc) const {
-	*engine = new ZVision::ZVision(syst,desc);
+	*engine = new ZVision::ZVision(syst, desc);
 	return Common::kNoError;
 }
 
diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index 63d28c23338..552009caa95 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -94,7 +94,7 @@ ActionAssign::~ActionAssign() {
 }
 
 bool ActionAssign::execute() {
-  debug(2,"[%d] = %d", _key, _value->getValue());
+	debug(2, "[%d] = %d", _key, _value->getValue());
 	_scriptManager->setStateValue(_key, _value->getValue());
 	return true;
 }
@@ -111,17 +111,17 @@ ActionAttenuate::ActionAttenuate(ZVision *engine, int32 slotKey, const Common::S
 	_attenuation = 0;
 
 	sscanf(line.c_str(), "%u, %d", &_key, &_attenuation);
-  debug(3,"Created Action: Attenuate, slotKey %d", _slotKey);
-  debug(3,"Attenuate script: %s", line.c_str());
-  debug(3,"Attenuate parameters: key1 %d, attenuation %d", _key, _attenuation);
+	debug(3, "Created Action: Attenuate, slotKey %d", _slotKey);
+	debug(3, "Attenuate script: %s", line.c_str());
+	debug(3, "Attenuate parameters: key1 %d, attenuation %d", _key, _attenuation);
 }
 
 bool ActionAttenuate::execute() {
-  debug(3,"Executing Action: Attenuate, slotkey %d", _slotKey);
+	debug(3, "Executing Action: Attenuate, slotkey %d", _slotKey);
 	ScriptingEffect *fx = _scriptManager->getSideFX(_key);
 	if (fx && fx->getType() == ScriptingEffect::SCRIPTING_EFFECT_AUDIO) {
 		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
-	mus->setVolume((10000 - abs(_attenuation)) / 100 ); //TODO - verify that this is working correctly.
+		mus->setVolume((10000 - abs(_attenuation)) / 100);  //TODO - verify that this is working correctly.
 	}
 	return true;
 }
@@ -164,13 +164,13 @@ ActionCrossfade::ActionCrossfade(ZVision *engine, int32 slotKey, const Common::S
 	sscanf(line.c_str(),
 	       "%u %u %d %d %d %d %d",
 	       &_keyOne, &_keyTwo, &_oneStartVolume, &_twoStartVolume, &_oneEndVolume, &_twoEndVolume, &_timeInMillis);
-  debug(3,"Created Action: CrossFade, slotKey %d", _slotKey);
-  debug(3,"Crossfade script: %s", line.c_str());
-  debug(3,"Crossfade parameters: key1 %u, key2 %u, startVol1 %d, startVol2 %d, endVol1 %d, endVol2 %d, time %dms", _keyOne, _keyTwo, _oneStartVolume, _twoStartVolume, _oneEndVolume, _twoEndVolume, _timeInMillis);
+	debug(3, "Created Action: CrossFade, slotKey %d", _slotKey);
+	debug(3, "Crossfade script: %s", line.c_str());
+	debug(3, "Crossfade parameters: key1 %u, key2 %u, startVol1 %d, startVol2 %d, endVol1 %d, endVol2 %d, time %dms", _keyOne, _keyTwo, _oneStartVolume, _twoStartVolume, _oneEndVolume, _twoEndVolume, _timeInMillis);
 }
 
 bool ActionCrossfade::execute() {
-  debug(3,"Executing Action: CrossFade, slotkey %d", _slotKey);
+	debug(3, "Executing Action: CrossFade, slotkey %d", _slotKey);
 	if (_keyOne) {
 		ScriptingEffect *fx = _scriptManager->getSideFX(_keyOne);
 		if (fx && fx->getType() == ScriptingEffect::SCRIPTING_EFFECT_AUDIO) {
@@ -238,7 +238,7 @@ ActionDelayRender::ActionDelayRender(ZVision *engine, int32 slotKey, const Commo
 }
 
 bool ActionDelayRender::execute() {
-  debug(3,"Executing Action: DelayRender");
+	debug(3, "Executing Action: DelayRender");
 	_engine->setRenderDelay(_framesToDelay);
 	return true;
 }
@@ -286,14 +286,14 @@ bool ActionDisplayMessage::execute() {
 
 ActionDissolve::ActionDissolve(ZVision *engine) :
 	ResultAction(engine, 0) {
-  debug(3,"Created action: Dissolve");
+	debug(3, "Created action: Dissolve");
 }
 
 bool ActionDissolve::execute() {
-  debug(3,"Executing action: Dissolve");
+	debug(3, "Executing action: Dissolve");
 	// Cause black screen flick
 	// Not ideal.  Original engine used a softer dissolve effect; simply turning the screen black is jarring, so disabled for now.
-	//_engine->getRenderManager()->bkgFill(0, 0, 0); //TODO - reimplement this?  
+	//_engine->getRenderManager()->bkgFill(0, 0, 0); //TODO - reimplement this?
 	return true;
 }
 
@@ -318,7 +318,7 @@ ActionDistort::~ActionDistort() {
 }
 
 bool ActionDistort::execute() {
-  debug(3,"Executing Action: Distort");
+	debug(3, "Executing Action: Distort");
 	if (_scriptManager->getSideFX(_distSlot))
 		return true;
 
@@ -438,14 +438,14 @@ ActionKill::ActionKill(ZVision *engine, int32 slotKey, const Common::String &lin
 			_type = ScriptingEffect::SCRIPTING_EFFECT_ALL;
 	} else
 		_key = atoi(keytype);
-  debug(3,"Created Action: Kill, slotKey %d, type %s, target slotKey %d", _slotKey, keytype, _key);
+	debug(3, "Created Action: Kill, slotKey %d, type %s, target slotKey %d", _slotKey, keytype, _key);
 }
 
 bool ActionKill::execute() {
 	if (_type)
 		_scriptManager->killSideFxType((ScriptingEffect::ScriptingEffectType)_type);
 	else {
-    debug(2,"Executing Action: Kill, slotKey %d, target slotKey %d", _slotKey, _key);
+		debug(2, "Executing Action: Kill, slotKey %d, target slotKey %d", _slotKey, _key);
 		_scriptManager->killSideFx(_key);
 	}
 	return true;
@@ -489,29 +489,29 @@ ActionMusic::ActionMusic(ZVision *engine, int32 slotKey, const Common::String &l
 	// Type 4 actions are MIDI commands, not files. These are only used by
 	// Zork: Nemesis, for the flute and piano puzzles (tj4e and ve6f, as well
 	// as vr)
-	switch(type) {
-    case 4:
-		  _midi = true;
-		  int note;
-		  int prog;
-		  sscanf(line.c_str(), "%u %d %d %14s", &type, &prog, &note, volumeBuffer);
-		  _note = note;
-		  _prog = prog;
-		  _loop = false;
-		  break;
-	  default:
-		  _midi = false;
-		  _fileName = Common::String(fileNameBuffer);
-		  _loop = loop == 1 ? true : false;
-		  break;
-  }
-  if (volumeBuffer[0] != '[' && atoi(volumeBuffer) > 100) {
-	  // I thought I saw a case like this in Zork Nemesis, so
-	  // let's guard against it.
-	  warning("\tActionMusic: Adjusting volume for %s from %s to 100", _fileName.toString().c_str(), volumeBuffer);
-	  Common::strcpy_s(volumeBuffer, "100");
-  }
-  _volume = new ValueSlot(_scriptManager, volumeBuffer);
+	switch (type) {
+	case 4:
+		_midi = true;
+		int note;
+		int prog;
+		sscanf(line.c_str(), "%u %d %d %14s", &type, &prog, &note, volumeBuffer);
+		_note = note;
+		_prog = prog;
+		_loop = false;
+		break;
+	default:
+		_midi = false;
+		_fileName = Common::String(fileNameBuffer);
+		_loop = loop == 1 ? true : false;
+		break;
+	}
+	if (volumeBuffer[0] != '[' && atoi(volumeBuffer) > 100) {
+		// I thought I saw a case like this in Zork Nemesis, so
+		// let's guard against it.
+		warning("\tActionMusic: Adjusting volume for %s from %s to 100", _fileName.toString().c_str(), volumeBuffer);
+		Common::strcpy_s(volumeBuffer, "100");
+	}
+	_volume = new ValueSlot(_scriptManager, volumeBuffer);
 
 	// WORKAROUND for a script bug in Zork Nemesis, rooms mq70/mq80.
 	// Fixes an edge case where the player goes to the dark room with the grue
@@ -519,28 +519,28 @@ ActionMusic::ActionMusic(ZVision *engine, int32 slotKey, const Common::String &l
 	// sound effect finishes. Fixes script bug #6794.
 	if (engine->getGameId() == GID_NEMESIS && _slotKey == 14822 && _scriptManager->getStateValue(_slotKey) == 2)
 		_scriptManager->setStateValue(_slotKey, 0);
-		
+
 	//Ensure MusicNodes that were active when game was saved are recreated when it is loaded.
 	//Certain game scripts can become locked-up if this is not the case.
-  if(_engine->getScriptManager()->getStateValue(_slotKey) == 1)
-    if(!_scriptManager->getSideFX(_slotKey)) {
-    debug(1, "Recreating missing musicnode, slotkey %d", _slotKey);
-    execute();
-  }
-      
-  debug(2,"Created Action: Music, slotKey %d, type %u, file %24s, note %u, volume %d, %s", _slotKey, type, fileNameBuffer, _note, _volume->getValue(), _loop ? "looping" : "");
-  debug(4,"Music script: %s", line.c_str());
+	if (_engine->getScriptManager()->getStateValue(_slotKey) == 1)
+		if (!_scriptManager->getSideFX(_slotKey)) {
+			debug(1, "Recreating missing musicnode, slotkey %d", _slotKey);
+			execute();
+		}
+
+	debug(2, "Created Action: Music, slotKey %d, type %u, file %24s, note %u, volume %d, %s", _slotKey, type, fileNameBuffer, _note, _volume->getValue(), _loop ? "looping" : "");
+	debug(4, "Music script: %s", line.c_str());
 }
 
 ActionMusic::~ActionMusic() {
 	if (!_universe)
 		_scriptManager->killSideFx(_slotKey);
 	delete _volume;
-  debug(2,"Destroyed Action: %sMusic, slotkey %d", _universe ? "Universe_" : "", _slotKey);
+	debug(2, "Destroyed Action: %sMusic, slotkey %d", _universe ? "Universe_" : "", _slotKey);
 }
 
 bool ActionMusic::execute() {
-  debug(2,"Executing Action: Music, slotKey %d, volume %d", _slotKey, _volume->getValue());
+	debug(2, "Executing Action: Music, slotKey %d, volume %d", _slotKey, _volume->getValue());
 	if (_scriptManager->getSideFX(_slotKey)) {
 		_scriptManager->killSideFx(_slotKey);
 		_scriptManager->setStateValue(_slotKey, 2);
@@ -551,7 +551,7 @@ bool ActionMusic::execute() {
 	else {
 		if (!_engine->getSearchManager()->hasFile(_fileName))
 			return true;
-    _scriptManager->addSideFX(new MusicNode(_engine, _slotKey, _fileName, _loop, volume));
+		_scriptManager->addSideFX(new MusicNode(_engine, _slotKey, _fileName, _loop, volume));
 	}
 	return true;
 }
@@ -574,29 +574,27 @@ ActionPanTrack::ActionPanTrack(ZVision *engine, int32 slotKey, const Common::Str
 	uint staticScreen = 0;  //Original game scripts do not specify this, but require it to be false to work correctly.
 	sscanf(line.c_str(), "%u %d %u %u %u %u", &_musicSlot, &_pos, &mag, &resetMusicNode, &resetMixerOnDelete, &staticScreen);
 	_resetMusicNode = resetMusicNode > 0;
-  _resetMixerOnDelete = resetMixerOnDelete > 0;
-  _staticScreen = staticScreen > 0;
+	_resetMixerOnDelete = resetMixerOnDelete > 0;
+	_staticScreen = staticScreen > 0;
 	_mag = mag;
-	if(_resetMusicNode) {
-	  if(_scriptManager->getStateValue(_musicSlot) != 2) {
-	    debug(3,"Forcing musicSlot %d to 2", _musicSlot);
-      _scriptManager->setStateValue(_musicSlot, 2); //Not all original game pan_track scripts trigger correctly unless this is set!
-    }
-    else
-      debug(3,"musicSlot %d already set to 2", _musicSlot);
-  }
-  else
-    debug(3,"NOT forcing musicSlot %d to 2", _musicSlot);
-  debug(3,"Created Action: PanTrack, slotkey %d, musicSlot %u, pos %d, mag %d", _slotKey, _musicSlot, _pos, _mag);
+	if (_resetMusicNode) {
+		if (_scriptManager->getStateValue(_musicSlot) != 2) {
+			debug(3, "Forcing musicSlot %d to 2", _musicSlot);
+			_scriptManager->setStateValue(_musicSlot, 2); //Not all original game pan_track scripts trigger correctly unless this is set!
+		} else
+			debug(3, "musicSlot %d already set to 2", _musicSlot);
+	} else
+		debug(3, "NOT forcing musicSlot %d to 2", _musicSlot);
+	debug(3, "Created Action: PanTrack, slotkey %d, musicSlot %u, pos %d, mag %d", _slotKey, _musicSlot, _pos, _mag);
 }
 
 ActionPanTrack::~ActionPanTrack() {
 	_scriptManager->killSideFx(_slotKey);
-  debug(3,"Destroyed Action: PanTrack, slotkey %d", _slotKey);
+	debug(3, "Destroyed Action: PanTrack, slotkey %d", _slotKey);
 }
 
 bool ActionPanTrack::execute() {
-  debug(3,"Executing Action: PanTrack, slotkey %d, musicSlot %u, pos %d, mag %d", _slotKey, _musicSlot, _pos, _mag);
+	debug(3, "Executing Action: PanTrack, slotkey %d, musicSlot %u, pos %d, mag %d", _slotKey, _musicSlot, _pos, _mag);
 	if (_scriptManager->getSideFX(_slotKey))
 		return true;
 	_scriptManager->addSideFX(new PanTrackNode(_engine, _slotKey, _musicSlot, _pos, _mag, _resetMixerOnDelete, _staticScreen));
@@ -656,8 +654,7 @@ bool ActionPreloadAnimation::execute() {
 	if (!nod) {
 		nod = new AnimationEffect(_engine, _slotKey, _fileName, _mask, _framerate, false);
 		_scriptManager->addSideFX(nod);
-	} 
-	else
+	} else
 		nod->stop();
 	_scriptManager->setStateValue(_slotKey, 2);
 	return true;
@@ -726,8 +723,7 @@ bool ActionPlayAnimation::execute() {
 	if (!nod) {
 		nod = new AnimationEffect(_engine, _slotKey, _fileName, _mask, _framerate);
 		_scriptManager->addSideFX(nod);
-	} 
-	else
+	} else
 		nod->stop();
 	if (nod)
 		nod->addPlayNode(_slotKey, _x, _y, _x2, _y2, _start, _end, _loopCount);
@@ -793,7 +789,7 @@ ActionRegion::~ActionRegion() {
 }
 
 bool ActionRegion::execute() {
-  debug(2,"Executing Action: Region");
+	debug(2, "Executing Action: Region");
 	if (_scriptManager->getSideFX(_slotKey))
 		return true;
 	GraphicsEffect *effect = NULL;
@@ -958,7 +954,7 @@ ActionStop::ActionStop(ZVision *engine, int32 slotKey, const Common::String &lin
 }
 
 bool ActionStop::execute() {
-  debug(2,"Executing Action: Stop, key %d", _key);
+	debug(2, "Executing Action: Stop, key %d", _key);
 	_scriptManager->stopSideFx(_key);
 	return true;
 }
@@ -982,11 +978,11 @@ ActionStreamVideo::ActionStreamVideo(ZVision *engine, int32 slotKey, const Commo
 }
 
 bool ActionStreamVideo::execute() {
-  debug(3,"Executing video stream");
+	debug(3, "Executing video stream");
 	Video::VideoDecoder *decoder;
 	Common::Rect destRect = Common::Rect(_x1, _y1, _x2 + 1, _y2 + 1);
-	Common::Rect srcRect = Common::Rect(0,0);
-  debug(3,"Streaming video original scripted destination left=%d, top=%d, right=%d, bottom=%d", destRect.left, destRect.top, destRect.right, destRect.bottom);
+	Common::Rect srcRect = Common::Rect(0, 0);
+	debug(3, "Streaming video original scripted destination left=%d, top=%d, right=%d, bottom=%d", destRect.left, destRect.top, destRect.right, destRect.bottom);
 	Common::String subname = _fileName.baseName();
 	subname.setChar('s', subname.size() - 3);
 	subname.setChar('u', subname.size() - 2);
@@ -997,7 +993,7 @@ bool ActionStreamVideo::execute() {
 
 // NOTE: We only show the hires MPEG2 videos when libmpeg2 and liba52 are compiled in,
 // otherwise we fall back to the lowres ones
-#if defined(USE_MPEG2) && defined(USE_A52)
+	#if defined(USE_MPEG2) && defined(USE_A52)
 	Common::String hiresFileName = _fileName.baseName();
 	hiresFileName.setChar('d', hiresFileName.size() - 8);
 	hiresFileName.setChar('v', hiresFileName.size() - 3);
@@ -1006,26 +1002,25 @@ bool ActionStreamVideo::execute() {
 
 	Common::Path hiresPath(_fileName.getParent().appendComponent(hiresFileName));
 
-	if (_scriptManager->getStateValue(StateKey_MPEGMovies) == 1 &&_engine->getSearchManager()->hasFile(hiresPath)) {
+	if (_scriptManager->getStateValue(StateKey_MPEGMovies) == 1 && _engine->getSearchManager()->hasFile(hiresPath)) {
 		_fileName = hiresPath;
 		switchToHires = true;
-	} 
-	else if (!_engine->getSearchManager()->hasFile(_fileName))
+	} else if (!_engine->getSearchManager()->hasFile(_fileName))
 		return true;
-#else
+	#else
 	if (!_engine->getSearchManager()->hasFile(_fileName))
 		return true;
-#endif
+	#endif
 
 	decoder = _engine->loadAnimation(_fileName);
 	uint16 sub = (subtitleExists) ? _engine->getSubtitleManager()->create(subpath, switchToHires) : 0;
 	_engine->getCursorManager()->showMouse(false);
 	if (switchToHires) {
 		_engine->getRenderManager()->initialize(true);
-    srcRect = Common::Rect(Common::Point(0,69),720, 344);
+		srcRect = Common::Rect(Common::Point(0, 69), 720, 344);
 		//ZGI hi-res video resolution = 720x480, with baked-in letterboxing around content at 720x344 (origin 0,69), interestingly conforming to playfield vertical resolution of 344
 		destRect = _engine->getRenderManager()->getWorkingArea(); //Game scripts only give destRect for normal resolution; we must manually override them for HD videos
-		destRect.moveTo(0,0);
+		destRect.moveTo(0, 0);
 	}
 
 	// WORKAROUND for what appears to be a script bug. When riding with
@@ -1047,9 +1042,9 @@ bool ActionStreamVideo::execute() {
 	if (switchToHires)
 		_engine->getRenderManager()->initialize(false);
 	_engine->getCursorManager()->showMouse(true);
-  _engine->getSubtitleManager()->destroy(sub);
-  _engine->setRenderDelay(2); //Necessary for avoiding redraw of previous scene between sequential videos (eg totemization sequence in ZGI) & when changing location right after a video (e.g. opening temple door in Nemesis)
-  debug(3,"Completed executing video stream");
+	_engine->getSubtitleManager()->destroy(sub);
+	_engine->setRenderDelay(2); //Necessary for avoiding redraw of previous scene between sequential videos (eg totemization sequence in ZGI) & when changing location right after a video (e.g. opening temple door in Nemesis)
+	debug(3, "Completed executing video stream");
 	return true;
 }
 
@@ -1067,7 +1062,7 @@ ActionSyncSound::ActionSyncSound(ZVision *engine, int32 slotKey, const Common::S
 }
 
 bool ActionSyncSound::execute() {
-  debug(3,"Executing Action: SyncSound");
+	debug(3, "Executing Action: SyncSound");
 	ScriptingEffect *fx = _scriptManager->getSideFX(_syncto);
 	if (!fx)
 		return true;
diff --git a/engines/zvision/scripting/actions.h b/engines/zvision/scripting/actions.h
index 5b3fc77fec3..d23ef2023ac 100644
--- a/engines/zvision/scripting/actions.h
+++ b/engines/zvision/scripting/actions.h
@@ -241,7 +241,7 @@ public:
 private:
 	int32 _pos; //Sound source position; NB in panoramas (all original game scripts), this is specified as the X background coordinate; otherwise it is specified in azimuth degrees.
 	uint8  _mag; //Magnitude of effect (not used by original game scripts); 255 for fully directional sound, 0 for fully ambient
-	bool _resetMusicNode; //If true (default, original game scripts have no concept of this), associated music slot value is reset to a value of 2 upon creation of this object; 
+	bool _resetMusicNode; //If true (default, original game scripts have no concept of this), associated music slot value is reset to a value of 2 upon creation of this object;
 	/*
 	* this seems necessary to ensure all original game pan-track effects load correctly, though it is still unclear exactly what the original intent of these values was.
 	* So far, best guess for music slotkey values is: 0 = has never been loaded, 1 = loaded and actively playing now, 2 = has loaded & played & then subsequently been killed.
diff --git a/engines/zvision/scripting/control.cpp b/engines/zvision/scripting/control.cpp
index 0e96dcce780..9132091fc25 100644
--- a/engines/zvision/scripting/control.cpp
+++ b/engines/zvision/scripting/control.cpp
@@ -33,12 +33,12 @@
 namespace ZVision {
 
 void Control::parseFlatControl(ZVision *engine) {
-  debug(1,"Setting render state to FLAT");
+	debug(1, "Setting render state to FLAT");
 	engine->getRenderManager()->getRenderTable()->setRenderState(RenderTable::FLAT);
 }
 
 void Control::parsePanoramaControl(ZVision *engine, Common::SeekableReadStream &stream) {
-  debug(1,"Setting render state to PANORAMA");
+	debug(1, "Setting render state to PANORAMA");
 	RenderTable *renderTable = engine->getRenderManager()->getRenderTable();
 	renderTable->setRenderState(RenderTable::PANORAMA);
 
@@ -74,7 +74,7 @@ void Control::parsePanoramaControl(ZVision *engine, Common::SeekableReadStream &
 
 // Only used in Zork Nemesis, handles tilt controls (ZGI doesn't have a tilt view)
 void Control::parseTiltControl(ZVision *engine, Common::SeekableReadStream &stream) {
-  debug(1,"Setting render state to TILT");
+	debug(1, "Setting render state to TILT");
 	RenderTable *renderTable = engine->getRenderManager()->getRenderTable();
 	renderTable->setRenderState(RenderTable::TILT);
 
diff --git a/engines/zvision/scripting/controls/fist_control.h b/engines/zvision/scripting/controls/fist_control.h
index 7b7ab780f70..ffbd4b986e4 100644
--- a/engines/zvision/scripting/controls/fist_control.h
+++ b/engines/zvision/scripting/controls/fist_control.h
@@ -28,7 +28,7 @@
 #include "common/rect.h"
 
 namespace Video {
-	class VideoDecoder;
+class VideoDecoder;
 }
 
 namespace ZVision {
diff --git a/engines/zvision/scripting/controls/hotmov_control.h b/engines/zvision/scripting/controls/hotmov_control.h
index cdc6fe85c24..fcb1f3bb5b9 100644
--- a/engines/zvision/scripting/controls/hotmov_control.h
+++ b/engines/zvision/scripting/controls/hotmov_control.h
@@ -29,7 +29,7 @@
 #include "common/rect.h"
 
 namespace Video {
-	class VideoDecoder;
+class VideoDecoder;
 }
 
 namespace ZVision {
diff --git a/engines/zvision/scripting/controls/input_control.h b/engines/zvision/scripting/controls/input_control.h
index b99dd4c0c8b..f2ac644363f 100644
--- a/engines/zvision/scripting/controls/input_control.h
+++ b/engines/zvision/scripting/controls/input_control.h
@@ -29,7 +29,7 @@
 #include "common/rect.h"
 
 namespace Video {
-	class VideoDecoder;
+class VideoDecoder;
 }
 
 namespace ZVision {
diff --git a/engines/zvision/scripting/controls/lever_control.h b/engines/zvision/scripting/controls/lever_control.h
index 3abb2525866..e8ead352681 100644
--- a/engines/zvision/scripting/controls/lever_control.h
+++ b/engines/zvision/scripting/controls/lever_control.h
@@ -29,7 +29,7 @@
 #include "common/rect.h"
 
 namespace Video {
-	class VideoDecoder;
+class VideoDecoder;
 }
 
 namespace ZVision {
diff --git a/engines/zvision/scripting/controls/safe_control.h b/engines/zvision/scripting/controls/safe_control.h
index 5bf0e51f5c2..d6b9059336e 100644
--- a/engines/zvision/scripting/controls/safe_control.h
+++ b/engines/zvision/scripting/controls/safe_control.h
@@ -28,7 +28,7 @@
 #include "common/rect.h"
 
 namespace Video {
-	class VideoDecoder;
+class VideoDecoder;
 }
 
 namespace ZVision {
diff --git a/engines/zvision/scripting/effects/animation_effect.cpp b/engines/zvision/scripting/effects/animation_effect.cpp
index 928cd4eba72..4bda3ddf93e 100644
--- a/engines/zvision/scripting/effects/animation_effect.cpp
+++ b/engines/zvision/scripting/effects/animation_effect.cpp
@@ -64,7 +64,7 @@ AnimationEffect::~AnimationEffect() {
 
 		if ((*it)._scaled) {
 			(*it)._scaled->free();
-			delete(*it)._scaled;
+			delete (*it)._scaled;
 		}
 	}
 
@@ -203,7 +203,7 @@ bool AnimationEffect::stop() {
 		_engine->getScriptManager()->setStateValue((*it).slot, 2);
 		if ((*it)._scaled) {
 			(*it)._scaled->free();
-			delete(*it)._scaled;
+			delete (*it)._scaled;
 		}
 	}
 
diff --git a/engines/zvision/scripting/effects/animation_effect.h b/engines/zvision/scripting/effects/animation_effect.h
index 0124ed82e68..d836035245c 100644
--- a/engines/zvision/scripting/effects/animation_effect.h
+++ b/engines/zvision/scripting/effects/animation_effect.h
@@ -32,7 +32,7 @@ struct Surface;
 }
 
 namespace Video {
-	class VideoDecoder;
+class VideoDecoder;
 }
 
 namespace ZVision {
diff --git a/engines/zvision/scripting/effects/distort_effect.cpp b/engines/zvision/scripting/effects/distort_effect.cpp
index b9d6579de31..66cb47bb1e9 100644
--- a/engines/zvision/scripting/effects/distort_effect.cpp
+++ b/engines/zvision/scripting/effects/distort_effect.cpp
@@ -77,24 +77,24 @@ bool DistortNode::process(uint32 deltaTimeInMillis) {
 
 void DistortNode::setParams(float angl, float linScale) {
 	RenderTable *table = _engine->getRenderManager()->getRenderTable();
-	switch(table->getRenderState()) {
-	  case RenderTable::PANORAMA: {
-		  table->setPanoramaFoV(angl);
-		  table->setPanoramaScale(linScale);
-		  table->generateRenderTable();
-		  _engine->getRenderManager()->markDirty();
-		  break;
-	  }
-	  case RenderTable::TILT: {
-		  table->setTiltFoV(angl);
-		  table->setTiltScale(linScale);
-		  table->generateRenderTable();
-		  _engine->getRenderManager()->markDirty();
-		  break;
-	  }
-	  default:
-	    break;
-	}    
+	switch (table->getRenderState()) {
+	case RenderTable::PANORAMA: {
+		table->setPanoramaFoV(angl);
+		table->setPanoramaScale(linScale);
+		table->generateRenderTable();
+		_engine->getRenderManager()->markDirty();
+		break;
+	}
+	case RenderTable::TILT: {
+		table->setTiltFoV(angl);
+		table->setTiltScale(linScale);
+		table->generateRenderTable();
+		_engine->getRenderManager()->markDirty();
+		break;
+	}
+	default:
+		break;
+	}
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 7c42e6e3517..7e1e30f26e9 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -41,30 +41,29 @@
 namespace ZVision {
 
 void MusicNodeBASE::setDirection(Math::Angle azimuth, uint8 magnitude) {
-  if(_engine->getScriptManager()->getStateValue(StateKey_Qsound) >= 1) {
-    _azimuth = azimuth;
-    _directionality = magnitude;
-    _balance = ((int)(127*_azimuth.getSine())*_directionality)/255;
-  }
-  else
-    setBalance(0);
+	if (_engine->getScriptManager()->getStateValue(StateKey_Qsound) >= 1) {
+		_azimuth = azimuth;
+		_directionality = magnitude;
+		_balance = ((int)(127 * _azimuth.getSine()) * _directionality) / 255;
+	} else
+		setBalance(0);
 	updateMixer();
 }
 
 void MusicNodeBASE::setBalance(int8 balance) {
-  _balance = balance;
-  _azimuth.setDegrees(0);
-  _directionality = 255;
+	_balance = balance;
+	_azimuth.setDegrees(0);
+	_directionality = 255;
 	updateMixer();
 }
 
 void MusicNodeBASE::updateMixer() {
-  if(_engine->getScriptManager()->getStateValue(StateKey_Qsound) >= 1)
-    volumeOut = _engine->getVolumeManager()->convert(_volume, _azimuth, _directionality);  //Apply game-specific volume profile and then attenuate according to azimuth
-  else
+	if (_engine->getScriptManager()->getStateValue(StateKey_Qsound) >= 1)
+		volumeOut = _engine->getVolumeManager()->convert(_volume, _azimuth, _directionality);  //Apply game-specific volume profile and then attenuate according to azimuth
+	else
 //    volumeOut = _engine->getVolumeManager()->convert(_volume, kVolumeLinear);  //Apply linear volume profile and ignore azimuth
-    volumeOut = _engine->getVolumeManager()->convert(_volume);  //Apply game-specific volume profile and ignore azimuth
-  outputMixer();
+		volumeOut = _engine->getVolumeManager()->convert(_volume);  //Apply game-specific volume profile and ignore azimuth
+	outputMixer();
 }
 
 MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool loop, uint8 volume)
@@ -73,7 +72,7 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 	_volume = volume;
 	_balance = 0;
 	_fade = false;
-  fadeStartVol = volume;
+	fadeStartVol = volume;
 	fadeEndVol = 0;
 	fadeTime = 0;
 	fadeElapsed = 0;
@@ -87,20 +86,18 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 		Common::File *file = new Common::File();
 		if (_engine->getSearchManager()->openFile(*file, filename))
 			audioStream = Audio::makeWAVStream(file, DisposeAfterUse::YES);
-	} 
-	else
+	} else
 		audioStream = makeRawZorkStream(filename, _engine);
-		
+
 	if (audioStream) {
 		_stereo = audioStream->isStereo();
 		if (_loop) {
 			Audio::LoopingAudioStream *loopingAudioStream = new Audio::LoopingAudioStream(audioStream, 0, DisposeAfterUse::YES);
 			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, loopingAudioStream, -1, _volume);
-		}
-		else
+		} else
 			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, audioStream, -1, _volume);
 		if (_key != StateKey_NotSet) {
-		  debug(3,"setting musicnode state value to 1");
+			debug(3, "setting musicnode state value to 1");
 			_engine->getScriptManager()->setStateValue(_key, 1);
 		}
 
@@ -112,7 +109,7 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 
 		Common::Path subpath(filename.getParent().appendComponent(subname));
 		if (_engine->getSearchManager()->hasFile(subpath))
-		  _sub = _engine->getSubtitleManager()->create(subpath, _handle); //NB automatic subtitle!
+			_sub = _engine->getSubtitleManager()->create(subpath, _handle); //NB automatic subtitle!
 		_loaded = true;
 		updateMixer();
 	}
@@ -135,7 +132,7 @@ void MusicNode::outputMixer() {
 }
 
 void MusicNode::setFade(int32 time, uint8 target) {
-  fadeStartVol = _volume;
+	fadeStartVol = _volume;
 	fadeEndVol = target;
 	fadeElapsed = 0;
 	fadeTime = time <= 0 ? 0 : (uint32)time;
@@ -147,25 +144,24 @@ bool MusicNode::process(uint32 deltaTimeInMillis) {
 		return stop();
 	else {
 		if (_fade) {
-			debug(3,"Fading music, endVol %d, startVol %d, current %d, fade time %d, elapsed time %dms", fadeEndVol, fadeStartVol, _volume, fadeTime, fadeElapsed);
-		  uint8 _newvol = 0;
-		  fadeElapsed += deltaTimeInMillis;
-		  if( (fadeTime <= 0) | (fadeElapsed >= fadeTime) ) {
-        _newvol = fadeEndVol;
-		    _fade = false;
-		  }
-		  else {
-		    if(fadeEndVol > fadeStartVol)
-		      _newvol = fadeStartVol + (fadeElapsed*(fadeEndVol - fadeStartVol))/fadeTime;
-	      else
-  		    _newvol = fadeStartVol - (fadeElapsed*(fadeStartVol - fadeEndVol))/fadeTime;
-	    }
-		  if (_volume != _newvol)
-			  setVolume(_newvol);
+			debug(3, "Fading music, endVol %d, startVol %d, current %d, fade time %d, elapsed time %dms", fadeEndVol, fadeStartVol, _volume, fadeTime, fadeElapsed);
+			uint8 _newvol = 0;
+			fadeElapsed += deltaTimeInMillis;
+			if ((fadeTime <= 0) | (fadeElapsed >= fadeTime)) {
+				_newvol = fadeEndVol;
+				_fade = false;
+			} else {
+				if (fadeEndVol > fadeStartVol)
+					_newvol = fadeStartVol + (fadeElapsed * (fadeEndVol - fadeStartVol)) / fadeTime;
+				else
+					_newvol = fadeStartVol - (fadeElapsed * (fadeStartVol - fadeEndVol)) / fadeTime;
+			}
+			if (_volume != _newvol)
+				setVolume(_newvol);
 		}
-	  /*  //Redundant with switch to automatic subtitles
+		/*  //Redundant with switch to automatic subtitles
 		if (_sub && _engine->getScriptManager()->getStateValue(StateKey_Subtitles) == 1)
-			_engine->getSubtitleManager()->update(_engine->_mixer->getSoundElapsedTime(_handle) / 100, _sub);
+		  _engine->getSubtitleManager()->update(_engine->_mixer->getSoundElapsedTime(_handle) / 100, _sub);
 		//*/
 	}
 	return false;
@@ -173,79 +169,78 @@ bool MusicNode::process(uint32 deltaTimeInMillis) {
 
 void MusicNode::setVolume(uint8 newVolume) {
 	if (_loaded) {
-	  _volume = newVolume;
-    updateMixer();
-  }
+		_volume = newVolume;
+		updateMixer();
+	}
 }
 
 
 PanTrackNode::PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos, uint8 mag, bool resetMixerOnDelete, bool staticScreen)
 	: ScriptingEffect(engine, key, SCRIPTING_EFFECT_PANTRACK),
-	_slot(slot),
-	sourcePos(0),
-	viewPos(0),
-	_mag(mag),
-	_width(0),
-	_pos(pos),
-	_staticScreen(staticScreen),
-	_resetMixerOnDelete(resetMixerOnDelete) {
-  debug(3,"Created PanTrackNode, key %d, slot %d", _key, _slot);
-	process(0); 	// Try to set pan value for music node immediately
+	  _slot(slot),
+	  sourcePos(0),
+	  viewPos(0),
+	  _mag(mag),
+	  _width(0),
+	  _pos(pos),
+	  _staticScreen(staticScreen),
+	  _resetMixerOnDelete(resetMixerOnDelete) {
+	debug(3, "Created PanTrackNode, key %d, slot %d", _key, _slot);
+	process(0);     // Try to set pan value for music node immediately
 }
 
 PanTrackNode::~PanTrackNode() {
-  debug(1,"Deleting PanTrackNode, key %d, slot %d", _key, _slot);
-	ScriptManager * scriptManager = _engine->getScriptManager();
+	debug(1, "Deleting PanTrackNode, key %d, slot %d", _key, _slot);
+	ScriptManager *scriptManager = _engine->getScriptManager();
 	ScriptingEffect *fx = scriptManager->getSideFX(_slot);
-  if (fx && fx->getType() == SCRIPTING_EFFECT_AUDIO && _resetMixerOnDelete) {
-    debug(1,"Resetting mixer, slot %d", _slot);
-	  MusicNodeBASE *mus = (MusicNodeBASE *)fx;
-    mus->setBalance(0);
-  }
-  else
-    debug(1,"NOT resetting mixer, slot %d", _slot);
+	if (fx && fx->getType() == SCRIPTING_EFFECT_AUDIO && _resetMixerOnDelete) {
+		debug(1, "Resetting mixer, slot %d", _slot);
+		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
+		mus->setBalance(0);
+	} else
+		debug(1, "NOT resetting mixer, slot %d", _slot);
 }
 
 bool PanTrackNode::process(uint32 deltaTimeInMillis) {
-  debug(3,"Processing PanTrackNode, key %d", _key);
-	ScriptManager * scriptManager = _engine->getScriptManager();
+	debug(3, "Processing PanTrackNode, key %d", _key);
+	ScriptManager *scriptManager = _engine->getScriptManager();
 	ScriptingEffect *fx = scriptManager->getSideFX(_slot);
 	if (fx && fx->getType() == SCRIPTING_EFFECT_AUDIO) {
 		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
-		if(!_staticScreen)
-		  //Original game scripted behaviour
-	    switch(_engine->getRenderManager()->getRenderTable()->getRenderState()) {
-	      case RenderTable::PANORAMA :
-	        debug(3,"PanTrackNode in panorama mode");
-	          _width = _engine->getRenderManager()->getBkgSize().x;
-	          if(_width) {
-	            sourcePos.setDegrees(360*_pos/_width);
-      	      viewPos.setDegrees(360*scriptManager->getStateValue(StateKey_ViewPos)/_width);
-    	      }
-    	      else {
-    	        warning("Encountered zero background width whilst processing PanTrackNode in panoramic mode!");
-	            //sourcePos.setDegrees(0);
-	            //viewPos.setDegrees(0);
-	          }
-	        break;	
-	      case RenderTable::FLAT :
-	      case RenderTable::TILT :
-	      default :
-	        debug(3,"PanTrackNode in FLAT/TILT mode");
-	        sourcePos.setDegrees(0);
-	        viewPos.setDegrees(0);
-	        break;
-      }
-    else {
-      //Used for auxiliary scripts only
-      sourcePos.setDegrees(_pos);
-      viewPos.setDegrees(0);
-    }
+		if (!_staticScreen)
+			//Original game scripted behaviour
+			switch (_engine->getRenderManager()->getRenderTable()->getRenderState()) {
+			case RenderTable::PANORAMA :
+				debug(3, "PanTrackNode in panorama mode");
+				_width = _engine->getRenderManager()->getBkgSize().x;
+				if (_width) {
+					sourcePos.setDegrees(360 * _pos / _width);
+					viewPos.setDegrees(360 * scriptManager->getStateValue(StateKey_ViewPos) / _width);
+				} else {
+					warning("Encountered zero background width whilst processing PanTrackNode in panoramic mode!");
+					//sourcePos.setDegrees(0);
+					//viewPos.setDegrees(0);
+				}
+				break;
+			case RenderTable::FLAT :
+			// fall through
+			case RenderTable::TILT :
+			// fall through
+			default :
+				debug(3, "PanTrackNode in FLAT/TILT mode");
+				sourcePos.setDegrees(0);
+				viewPos.setDegrees(0);
+				break;
+			} else {
+			//Used for auxiliary scripts only
+			sourcePos.setDegrees(_pos);
+			viewPos.setDegrees(0);
+		}
 		Math::Angle azimuth;
 		azimuth = sourcePos - viewPos;
-		debug(3,"soundPos: %f, viewPos: %f, azimuth: %f, width %d", sourcePos.getDegrees(), viewPos.getDegrees(), azimuth.getDegrees(), _width);
-    //azimuth is sound source position relative to player, clockwise from centre of camera axis to front when viewed top-down
-    mus->setDirection(azimuth, _mag);
+		debug(3, "soundPos: %f, viewPos: %f, azimuth: %f, width %d", sourcePos.getDegrees(), viewPos.getDegrees(), azimuth.getDegrees(), _width);
+		//azimuth is sound source position relative to player, clockwise from centre of camera axis to front when viewed top-down
+		mus->setDirection(azimuth, _mag);
 	}
 	return false;
 }
@@ -258,7 +253,7 @@ MusicMidiNode::MusicMidiNode(ZVision *engine, uint32 key, uint8 program, uint8 n
 	_pan = 0;
 	_chan = _engine->getMidiManager()->getFreeChannel();
 	if (_chan >= 0) {
-	  updateMixer();
+		updateMixer();
 		_engine->getMidiManager()->setProgram(_chan, _prog);
 		_engine->getMidiManager()->noteOn(_chan, _noteNumber, _volume);
 	}
@@ -282,15 +277,15 @@ bool MusicMidiNode::process(uint32 deltaTimeInMillis) {
 
 void MusicMidiNode::setVolume(uint8 newVolume) {
 	if (_chan >= 0) {
-	  _volume = newVolume;
-	  updateMixer();
+		_volume = newVolume;
+		updateMixer();
 	}
 }
 
 void MusicMidiNode::outputMixer() {
 	_engine->getMidiManager()->setBalance(_chan, _balance);
 	_engine->getMidiManager()->setPan(_chan, _pan);
-  _engine->getMidiManager()->setVolume(_chan, volumeOut);
+	_engine->getMidiManager()->setVolume(_chan, volumeOut);
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/effects/music_effect.h b/engines/zvision/scripting/effects/music_effect.h
index 78110b5c2c0..8fbcedaeab8 100644
--- a/engines/zvision/scripting/effects/music_effect.h
+++ b/engines/zvision/scripting/effects/music_effect.h
@@ -49,18 +49,20 @@ public:
 	bool process(uint32 deltaTimeInMillis) override = 0;
 
 	virtual void setVolume(uint8 volume) = 0;
-	uint8 getVolume() {return _volume;};
+	uint8 getVolume() {
+		return _volume;
+	};
 	virtual void setFade(int32 time, uint8 target) = 0;
 	virtual void setBalance(int8 balance);  //NB Overrides effects of setDirection()
 	void setDirection(Math::Angle azimuth, uint8 magnitude = 255);  //NB Overrides effects of setBalance()
 protected:
-  void updateMixer();
-  virtual void outputMixer() = 0;
-  
-  uint8 _volume = 0;
+	void updateMixer();
+	virtual void outputMixer() = 0;
+
+	uint8 _volume = 0;
 	int8 _balance = 0;
-  Math::Angle _azimuth;
-  uint8 _directionality;  //0 = fully ambient, 255 = fully directional
+	Math::Angle _azimuth;
+	uint8 _directionality;  //0 = fully ambient, 255 = fully directional
 	uint8 volumeOut = 0;
 };
 
@@ -81,7 +83,7 @@ public:
 	void setFade(int32 time, uint8 target) override;
 
 private:
-  void outputMixer() override;
+	void outputMixer() override;
 	bool _loop;
 	bool _fade;
 	uint8 fadeStartVol;
@@ -112,7 +114,7 @@ public:
 	void setFade(int32 time, uint8 target) override;
 
 private:
-  void outputMixer() override;
+	void outputMixer() override;
 	int8 _chan;
 	uint8 _noteNumber;
 	int8 _pan;
@@ -121,14 +123,14 @@ private:
 
 class PanTrackNode : public ScriptingEffect {
 public:
-	PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos, uint8 mag=255, bool resetMixerOnDelete=false, bool staticScreen=false);
+	PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos, uint8 mag = 255, bool resetMixerOnDelete = false, bool staticScreen = false);
 	~PanTrackNode() override;
 	bool process(uint32 deltaTimeInMillis) override;
 
 private:
 	uint32 _slot;
 	int16 _width, _pos;
-  Math::Angle sourcePos, viewPos;
+	Math::Angle sourcePos, viewPos;
 	uint8 _mag;
 	bool _resetMixerOnDelete;
 	bool _staticScreen;
diff --git a/engines/zvision/scripting/effects/syncsound_effect.cpp b/engines/zvision/scripting/effects/syncsound_effect.cpp
index 4bbd00fed4d..7207a8008d7 100644
--- a/engines/zvision/scripting/effects/syncsound_effect.cpp
+++ b/engines/zvision/scripting/effects/syncsound_effect.cpp
@@ -74,10 +74,10 @@ bool SyncSoundNode::process(uint32 deltaTimeInMillis) {
 	else {
 		if (_engine->getScriptManager()->getSideFX(_syncto) == NULL)
 			return stop();
-  /*  //Redundant with switch to automatic subtitles
-		if (_sub && _engine->getScriptManager()->getStateValue(StateKey_Subtitles) == 1)
-			_engine->getSubtitleManager()->update(_engine->_mixer->getSoundElapsedTime(_handle) / 100, _sub);
-	//*/
+		/*  //Redundant with switch to automatic subtitles
+		  if (_sub && _engine->getScriptManager()->getStateValue(StateKey_Subtitles) == 1)
+		      _engine->getSubtitleManager()->update(_engine->_mixer->getSoundElapsedTime(_handle) / 100, _sub);
+		//*/
 	}
 	return false;
 }
diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index 82e2b81c78c..8c79de6a109 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -28,7 +28,7 @@
 namespace ZVision {
 
 enum {
-  kFocusNone = -1,
+	kFocusNone = -1,
 	kFocusItems = 0,
 	kFocusMagic = 1,
 	kFocusMain = 2
@@ -36,203 +36,203 @@ enum {
 
 MenuManager::MenuManager(ZVision *engine, const Common::Rect menuArea, const MenuParams params) :
 	_engine(engine),
-  _params(params),
+	_params(params),
 	menuBarFlag(0xFFFF),
 	_menuArea(menuArea),
-  menuOrigin(menuArea.origin()),
-  menuTriggerArea(menuOrigin,_menuArea.width(),_params.triggerHeight),
-  mainScroller(params.activePos, params.idlePos, params.period) {
-	
+	menuOrigin(menuArea.origin()),
+	menuTriggerArea(menuOrigin, _menuArea.width(), _params.triggerHeight),
+	mainScroller(params.activePos, params.idlePos, params.period) {
+
 	enableFlags.set_size(6);
-  for(int8 i = 0; i < 4; i++) {
-	  //Generate button hotspot areas
-	  menuHotspots[i] = Common::Rect(_params.wxButs[i][1], _menuArea.top, _params.wxButs[i][1]+_params.wxButs[i][0], _menuArea.bottom);
-    //Initialise button animation frames
-    mainFrames[i] = _params.idleFrame;
+	for (int8 i = 0; i < 4; i++) {
+		//Generate button hotspot areas
+		menuHotspots[i] = Common::Rect(_params.wxButs[i][1], _menuArea.top, _params.wxButs[i][1] + _params.wxButs[i][0], _menuArea.bottom);
+		//Initialise button animation frames
+		mainFrames[i] = _params.idleFrame;
 	}
 	for (int i = 0; i < 4; i++)
-    buttonAnim[i] = new LinearScroller(_params.activeFrame,_params.idleFrame,_params.buttonPeriod);
+		buttonAnim[i] = new LinearScroller(_params.activeFrame, _params.idleFrame, _params.buttonPeriod);
 	setFocus(kFocusNone); //Ensure focus list is initialised
-	mainArea = Common::Rect(_params.wMain,hMainMenu);
-	mainArea.moveTo(menuOrigin+mainScroller.Pos);
+	mainArea = Common::Rect(_params.wMain, hMainMenu);
+	mainArea.moveTo(menuOrigin + mainScroller.Pos);
 }
 
 MenuManager::~MenuManager() {
 	for (int i = 0; i < 4; i++)
-	  delete buttonAnim[i];
+		delete buttonAnim[i];
 	mainBack.free();
 }
 
 void MenuManager::setEnable(uint16 flags) {
-	  static const uint16 flagMasks[6] = {0x8,0x4,0x2,0x1,0x100,0x200};  //Enum order: save,restore,prefs,quit,items,magic
-		menuBarFlag = flags;
-		for(uint i=0; i<=5; i++) {
-      if(menuBarFlag & flagMasks[i])
-        enableFlags.set(i);
-      else
-        enableFlags.unset(i);
-    }		  
+	static const uint16 flagMasks[6] = {0x8, 0x4, 0x2, 0x1, 0x100, 0x200}; //Enum order: save,restore,prefs,quit,items,magic
+	menuBarFlag = flags;
+	for (uint i = 0; i <= 5; i++) {
+		if (menuBarFlag & flagMasks[i])
+			enableFlags.set(i);
+		else
+			enableFlags.unset(i);
 	}
+}
 
 void MenuManager::onMouseUp(const Common::Point &Pos) {
-  if(menuFocus.front() == kFocusMain) {
-    mouseOnItem = mouseOverMain(Pos);
-    if(mouseOnItem == mainClicked)
-      //Activate clicked action from main menu
-      switch(mouseOnItem) {
-        case kMainMenuSave:
-		      _engine->getScriptManager()->changeLocation('g', 'j', 's', 'e', 0);
-		      setFocus(kFocusNone);
-		      mainScroller.reset();
-		      redraw = true;
-		      break;
-	      case kMainMenuLoad:
-		      _engine->getScriptManager()->changeLocation('g', 'j', 'r', 'e', 0);
-		      setFocus(kFocusNone);
-		      mainScroller.reset();
-		      redraw = true;
-		      break;
-        case kMainMenuPrefs:
-		      _engine->getScriptManager()->changeLocation('g', 'j', 'p', 'e', 0);
-		      setFocus(kFocusNone);
-		      mainScroller.reset();
-		      redraw = true;
-	        break;
-        case kMainMenuExit:
-		      _engine->ifQuit();
-		      break;
-	      default:
-	        break;
-      }
-  }
-  mainClicked = -1;
+	if (menuFocus.front() == kFocusMain) {
+		mouseOnItem = mouseOverMain(Pos);
+		if (mouseOnItem == mainClicked)
+			//Activate clicked action from main menu
+			switch (mouseOnItem) {
+			case kMainMenuSave:
+				_engine->getScriptManager()->changeLocation('g', 'j', 's', 'e', 0);
+				setFocus(kFocusNone);
+				mainScroller.reset();
+				redraw = true;
+				break;
+			case kMainMenuLoad:
+				_engine->getScriptManager()->changeLocation('g', 'j', 'r', 'e', 0);
+				setFocus(kFocusNone);
+				mainScroller.reset();
+				redraw = true;
+				break;
+			case kMainMenuPrefs:
+				_engine->getScriptManager()->changeLocation('g', 'j', 'p', 'e', 0);
+				setFocus(kFocusNone);
+				mainScroller.reset();
+				redraw = true;
+				break;
+			case kMainMenuExit:
+				_engine->ifQuit();
+				break;
+			default:
+				break;
+			}
+	}
+	mainClicked = -1;
 }
 
 void MenuManager::onMouseDown(const Common::Point &Pos) {
-  if(menuFocus.front() == kFocusMain) {
-    mouseOnItem = mouseOverMain(Pos);
-    //Show clicked graphic
-    if((mouseOnItem>=0) && (mouseOnItem<4))
-      if(enableFlags.get(mouseOnItem)) {
-        mainClicked = mouseOnItem;
-        redraw = true;
-      }
-  }
-  debug(1, "mouse position %d %d", Pos.x, Pos.y);
-  debug(1, "panorama position %d %d", Pos.x, Pos.y);
+	if (menuFocus.front() == kFocusMain) {
+		mouseOnItem = mouseOverMain(Pos);
+		//Show clicked graphic
+		if ((mouseOnItem >= 0) && (mouseOnItem < 4))
+			if (enableFlags.get(mouseOnItem)) {
+				mainClicked = mouseOnItem;
+				redraw = true;
+			}
+	}
+	debug(1, "mouse position %d %d", Pos.x, Pos.y);
+	debug(1, "panorama position %d %d", Pos.x, Pos.y);
 }
 
 void MenuManager::onMouseMove(const Common::Point &Pos) {
-  bool nowInMenu = inMenu(Pos);
-  if(nowInMenu != prevInMenu)
-    redraw = true;
-  prevInMenu = nowInMenu;
-    
+	bool nowInMenu = inMenu(Pos);
+	if (nowInMenu != prevInMenu)
+		redraw = true;
+	prevInMenu = nowInMenu;
+
 	int lastItem = mouseOnItem;
-  
-  switch(menuFocus.front()) {
-    case kFocusMain:
-      //Inform game scripting engine that mouse is in main menu
-	    if(_engine->getScriptManager()->getStateValue(StateKey_MenuState) != 2)
-		    _engine->getScriptManager()->setStateValue(StateKey_MenuState, 2);
-      mouseOnItem = mouseOverMain(Pos);
-	    break;
-	  case kFocusNone:
-		  //Inform game scripting engine that mouse is not in any menu
-		  if(_engine->getScriptManager()->getStateValue(StateKey_MenuState) != 0)
-			  _engine->getScriptManager()->setStateValue(StateKey_MenuState, 0);
-		  mouseOnItem = -1;
-		  break;
+
+	switch (menuFocus.front()) {
+	case kFocusMain:
+		//Inform game scripting engine that mouse is in main menu
+		if (_engine->getScriptManager()->getStateValue(StateKey_MenuState) != 2)
+			_engine->getScriptManager()->setStateValue(StateKey_MenuState, 2);
+		mouseOnItem = mouseOverMain(Pos);
+		break;
+	case kFocusNone:
+		//Inform game scripting engine that mouse is not in any menu
+		if (_engine->getScriptManager()->getStateValue(StateKey_MenuState) != 0)
+			_engine->getScriptManager()->setStateValue(StateKey_MenuState, 0);
+		mouseOnItem = -1;
+		break;
 	}
-  mainScroller.setActive(menuFocus.front()==kFocusMain);
-  //Update button animation status
-  for (int i = 0; i < 4; i++)
-    if(menuFocus[0] == kFocusMain && mouseOnItem == i)
-      buttonAnim[i]->setActive(true);
-    else
- 	    buttonAnim[i]->setActive(false);
-  if(lastItem != mouseOnItem)
-    redraw = true;
+	mainScroller.setActive(menuFocus.front() == kFocusMain);
+	//Update button animation status
+	for (int i = 0; i < 4; i++)
+		if (menuFocus[0] == kFocusMain && mouseOnItem == i)
+			buttonAnim[i]->setActive(true);
+		else
+			buttonAnim[i]->setActive(false);
+	if (lastItem != mouseOnItem)
+		redraw = true;
 }
 
 int MenuManager::mouseOverMain(const Common::Point &Pos) {
-  //Common::Rect mainHotspot(28,hSideMenu);
-  //mainHotspot.moveTo(mainOrigin + mainScroller.Pos);
-  for(int8 i = 0; i < 4; i++) {
-    if(enableFlags.get(i) && menuHotspots[i].contains(Pos))
-      return i;
-  }
-  return -1;
+	//Common::Rect mainHotspot(28,hSideMenu);
+	//mainHotspot.moveTo(mainOrigin + mainScroller.Pos);
+	for (int8 i = 0; i < 4; i++) {
+		if (enableFlags.get(i) && menuHotspots[i].contains(Pos))
+			return i;
+	}
+	return -1;
 }
 
 void MenuManager::process(uint32 deltatime) {
-	if(mainScroller.update(deltatime)) {
-	  mainArea.moveTo(menuOrigin+mainScroller.Pos);
-    for (int i = 0; i < 4; i++)
-      menuHotspots[i].moveTo(menuOrigin + Common::Point(_params.wxButs[i][1], mainScroller.Pos.y));
+	if (mainScroller.update(deltatime)) {
+		mainArea.moveTo(menuOrigin + mainScroller.Pos);
+		for (int i = 0; i < 4; i++)
+			menuHotspots[i].moveTo(menuOrigin + Common::Point(_params.wxButs[i][1], mainScroller.Pos.y));
 		redraw = true;
 	}
-  //Update button highlight animation frame
-  for(int i = 0; i < 4; i++)
-    if(buttonAnim[i]->update(deltatime)) {
-      mainFrames[i] = buttonAnim[i]->Pos;
-      redraw = true;
-    }
-	if(redraw) {
-	  _engine->getRenderManager()->clearMenuSurface();
-  	redrawAll();
-  	redraw = false;
-  }
+	//Update button highlight animation frame
+	for (int i = 0; i < 4; i++)
+		if (buttonAnim[i]->update(deltatime)) {
+			mainFrames[i] = buttonAnim[i]->Pos;
+			redraw = true;
+		}
+	if (redraw) {
+		_engine->getRenderManager()->clearMenuSurface();
+		redrawAll();
+		redraw = false;
+	}
 }
 
 void MenuNemesis::redrawAll() {
-  redrawMain();
+	redrawMain();
 }
 
 void MenuManager::redrawMain() {
-  //Draw menu background
-  _engine->getRenderManager()->blitSurfaceToMenu(mainBack, mainScroller.Pos.x, mainScroller.Pos.y, 0);
-  //Draw buttons
-  if(menuFocus.front() == kFocusMain)
-    for(int8 i = 0; i < 4; i++) {
-      if(enableFlags.get(i) && (mainFrames[i]>=0)) {
-        if(mainClicked == i)
-	        _engine->getRenderManager()->blitSurfaceToMenu(mainButtons[i][_params.clickedFrame], _params.wxButs[i][1], mainScroller.Pos.y, 0);        
-        else
-	        _engine->getRenderManager()->blitSurfaceToMenu(mainButtons[i][mainFrames[i]], _params.wxButs[i][1], mainScroller.Pos.y, 0);
-      }
-    }
-  clean = false;
+	//Draw menu background
+	_engine->getRenderManager()->blitSurfaceToMenu(mainBack, mainScroller.Pos.x, mainScroller.Pos.y, 0);
+	//Draw buttons
+	if (menuFocus.front() == kFocusMain)
+		for (int8 i = 0; i < 4; i++) {
+			if (enableFlags.get(i) && (mainFrames[i] >= 0)) {
+				if (mainClicked == i)
+					_engine->getRenderManager()->blitSurfaceToMenu(mainButtons[i][_params.clickedFrame], _params.wxButs[i][1], mainScroller.Pos.y, 0);
+				else
+					_engine->getRenderManager()->blitSurfaceToMenu(mainButtons[i][mainFrames[i]], _params.wxButs[i][1], mainScroller.Pos.y, 0);
+			}
+		}
+	clean = false;
 }
 
 void MenuManager::setFocus(int8 currentFocus) {
-  menuFocus.set(currentFocus);
-  assert(menuFocus.size() <= 4);
+	menuFocus.set(currentFocus);
+	assert(menuFocus.size() <= 4);
 }
 
 MenuZGI::MenuZGI(ZVision *engine, const Common::Rect menuArea) :
 	MenuManager(engine, menuArea, zgiParams),
-	itemsScroller(Common::Point(0,0), Common::Point(wSideMenuTab-wSideMenu,0), sideMenuPeriod),
-	magicScroller(Common::Point(-wSideMenu,0), Common::Point(-wSideMenuTab,0), sideMenuPeriod),
+	itemsScroller(Common::Point(0, 0), Common::Point(wSideMenuTab - wSideMenu, 0), sideMenuPeriod),
+	magicScroller(Common::Point(-wSideMenu, 0), Common::Point(-wSideMenuTab, 0), sideMenuPeriod),
 	itemsOrigin(menuArea.left, menuArea.top),
 	magicOrigin(menuArea.right, menuArea.top) {
 
-  magicArea = Common::Rect(magicOrigin + magicScroller.Pos, wSideMenu, hSideMenu);
-  itemsArea = Common::Rect(itemsOrigin + itemsScroller.Pos, wSideMenu, hSideMenu);
-	
-  //Buffer main menu background
+	magicArea = Common::Rect(magicOrigin + magicScroller.Pos, wSideMenu, hSideMenu);
+	itemsArea = Common::Rect(itemsOrigin + itemsScroller.Pos, wSideMenu, hSideMenu);
+
+	//Buffer main menu background
 	_engine->getRenderManager()->readImageToSurface("gmzau031.tga", mainBack, false);
-	
+
 	char buf[24];
 	for (int i = 0; i < 4; i++) {
-	  //Buffer menu buttons
+		//Buffer menu buttons
 		Common::sprintf_s(buf, "gmzmu%2.2x1.tga", i);
 		_engine->getRenderManager()->readImageToSurface(buf, mainButtons[i][0], false);
 		Common::sprintf_s(buf, "gmznu%2.2x1.tga", i);
 		_engine->getRenderManager()->readImageToSurface(buf, mainButtons[i][1], false);
 	}
 	for (int i = 1; i < 4; i++) {
-	  //Buffer full menu backgrounds
+		//Buffer full menu backgrounds
 		Common::sprintf_s(buf, "gmzau%2.2x1.tga", i);
 		_engine->getRenderManager()->readImageToSurface(buf, menuBack[i - 1], false);
 	}
@@ -247,36 +247,36 @@ MenuZGI::MenuZGI(ZVision *engine, const Common::Rect menuArea) :
 		magicId[i] = 0;
 	}
 	//Initialise focus sequence
-  setFocus(kFocusMain);
-  setFocus(kFocusMagic);
-  setFocus(kFocusItems);
-  setFocus(kFocusNone);
+	setFocus(kFocusMain);
+	setFocus(kFocusMagic);
+	setFocus(kFocusItems);
+	setFocus(kFocusNone);
 }
 
 MenuZGI::~MenuZGI() {
 	for (int i = 0; i < 3; i++)
 		menuBack[i].free();
-		
+
 	for (int i = 0; i < 4; i++)
-    for(int j = 0; j < 2; j++)
-		  mainButtons[i][j].free();
-		  
+		for (int j = 0; j < 2; j++)
+			mainButtons[i][j].free();
+
 	for (int i = 0; i < 50; i++) {
-		if(items[i][0]) {
+		if (items[i][0]) {
 			items[i][0]->free();
 			delete items[i][0];
 		}
-		if(items[i][1]) {
+		if (items[i][1]) {
 			items[i][1]->free();
 			delete items[i][1];
 		}
 	}
 	for (int i = 0; i < 12; i++) {
-		if(magic[i][0]) {
+		if (magic[i][0]) {
 			magic[i][0]->free();
 			delete magic[i][0];
 		}
-		if(magic[i][1]) {
+		if (magic[i][1]) {
 			magic[i][1]->free();
 			delete magic[i][1];
 		}
@@ -284,279 +284,278 @@ MenuZGI::~MenuZGI() {
 }
 
 bool MenuZGI::inMenu(const Common::Point &Pos) {
-  return menuTriggerArea.contains(Pos) || (menuFocus.front() != kFocusNone);
+	return menuTriggerArea.contains(Pos) || (menuFocus.front() != kFocusNone);
 }
 
 void MenuZGI::onMouseUp(const Common::Point &Pos) {
-	if(inMenu(Pos))
-	  //redraw = true;
+	if (inMenu(Pos))
+		//redraw = true;
 		switch (menuFocus.front()) {
-		  case kFocusItems:
-			  if(enableFlags.get(kItemsMenu)) {
-				  int itemCount = _engine->getScriptManager()->getStateValue(StateKey_Inv_TotalSlots);
-				  if(itemCount == 0)
-					  itemCount = 20;
-          int i = mouseOverItem(Pos,itemCount);
-          if(i != -1) {
-				    int32 mouseItem = _engine->getScriptManager()->getStateValue(StateKey_InventoryItem);
-				    if(mouseItem >= 0  && mouseItem < 0xE0) {
-					    _engine->getScriptManager()->inventoryDrop(mouseItem);
-					    _engine->getScriptManager()->inventoryAdd(_engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + i));
-					    _engine->getScriptManager()->setStateValue(StateKey_Inv_StartSlot + i, mouseItem);
-					    redraw = true;         
-            }
-          }
-		    }
-			  break;
-		  case kFocusMagic:
-			  if(enableFlags.get(kMagicMenu)) {
-			    int i = mouseOverMagic(Pos);
-			    if(i != -1) {
-				    uint itemnum = _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + i);
-				    if(itemnum != 0) {
-					    if(_engine->getScriptManager()->getStateValue(StateKey_Reversed_Spellbooc) == 1)
-						    itemnum = 0xEE + i;
-					    else
-						    itemnum = 0xE0 + i;
-					    }
-				    if(itemnum)
-					    if(_engine->getScriptManager()->getStateValue(StateKey_InventoryItem) == 0 || _engine->getScriptManager()->getStateValue(StateKey_InventoryItem) >= 0xE0)
-					      _engine->getScriptManager()->setStateValue(StateKey_Active_Spell, itemnum);
-			    }
-			  }
-			  break;
-		  case kFocusMain:
-        MenuManager::onMouseUp(Pos);
-			  break;
-		  default:
-			  break;
-		  }
+		case kFocusItems:
+			if (enableFlags.get(kItemsMenu)) {
+				int itemCount = _engine->getScriptManager()->getStateValue(StateKey_Inv_TotalSlots);
+				if (itemCount == 0)
+					itemCount = 20;
+				int i = mouseOverItem(Pos, itemCount);
+				if (i != -1) {
+					int32 mouseItem = _engine->getScriptManager()->getStateValue(StateKey_InventoryItem);
+					if (mouseItem >= 0  && mouseItem < 0xE0) {
+						_engine->getScriptManager()->inventoryDrop(mouseItem);
+						_engine->getScriptManager()->inventoryAdd(_engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + i));
+						_engine->getScriptManager()->setStateValue(StateKey_Inv_StartSlot + i, mouseItem);
+						redraw = true;
+					}
+				}
+			}
+			break;
+		case kFocusMagic:
+			if (enableFlags.get(kMagicMenu)) {
+				int i = mouseOverMagic(Pos);
+				if (i != -1) {
+					uint itemnum = _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + i);
+					if (itemnum != 0) {
+						if (_engine->getScriptManager()->getStateValue(StateKey_Reversed_Spellbooc) == 1)
+							itemnum = 0xEE + i;
+						else
+							itemnum = 0xE0 + i;
+					}
+					if (itemnum)
+						if (_engine->getScriptManager()->getStateValue(StateKey_InventoryItem) == 0 || _engine->getScriptManager()->getStateValue(StateKey_InventoryItem) >= 0xE0)
+							_engine->getScriptManager()->setStateValue(StateKey_Active_Spell, itemnum);
+				}
+			}
+			break;
+		case kFocusMain:
+			MenuManager::onMouseUp(Pos);
+			break;
+		default:
+			break;
+		}
 }
 
 void MenuZGI::onMouseMove(const Common::Point &Pos) {
-  if(!inMenu(Pos)) {
-    mainScroller.reset();
-    magicScroller.reset();
-    itemsScroller.reset();
-  }
-
-  //Set focus to topmost layer of menus that mouse is currently over
-  for(uint8 i=0; i<menuFocus.size(); i++) {
-    switch(menuFocus[i]) {
-      case kFocusItems:
-        if(itemsArea.contains(Pos)) {
-          setFocus(kFocusItems);
-          i = menuFocus.size()+1;
-        }
-        break;
-      case kFocusMagic:
-        if(magicArea.contains(Pos)) {
-          setFocus(kFocusMagic);
-          i = menuFocus.size()+1;
-        }
-        break;
-      case kFocusMain:
-        if(mainArea.contains(Pos)) {
-          setFocus(kFocusMain);
-          i = menuFocus.size()+1;
-        }
-        break;
-      default:
-        setFocus(kFocusNone);
-        break;
-    }
-  }    
-  itemsScroller.setActive(menuFocus.front()==kFocusItems);
-  magicScroller.setActive(menuFocus.front()==kFocusMagic);  
-	if(menuFocus.front() != kFocusNone) {
+	if (!inMenu(Pos)) {
+		mainScroller.reset();
+		magicScroller.reset();
+		itemsScroller.reset();
+	}
+
+	//Set focus to topmost layer of menus that mouse is currently over
+	for (uint8 i = 0; i < menuFocus.size(); i++) {
+		switch (menuFocus[i]) {
+		case kFocusItems:
+			if (itemsArea.contains(Pos)) {
+				setFocus(kFocusItems);
+				i = menuFocus.size() + 1;
+			}
+			break;
+		case kFocusMagic:
+			if (magicArea.contains(Pos)) {
+				setFocus(kFocusMagic);
+				i = menuFocus.size() + 1;
+			}
+			break;
+		case kFocusMain:
+			if (mainArea.contains(Pos)) {
+				setFocus(kFocusMain);
+				i = menuFocus.size() + 1;
+			}
+			break;
+		default:
+			setFocus(kFocusNone);
+			break;
+		}
+	}
+	itemsScroller.setActive(menuFocus.front() == kFocusItems);
+	magicScroller.setActive(menuFocus.front() == kFocusMagic);
+	if (menuFocus.front() != kFocusNone) {
 		switch (menuFocus.front()) {
-		  case kFocusItems:
-			  if(enableFlags.get(kItemsMenu)) {
-				  int itemCount = _engine->getScriptManager()->getStateValue(StateKey_Inv_TotalSlots);
-				  if(itemCount == 0)
-					  itemCount = 20;
-				  else if(itemCount > 50)
-					  itemCount = 50;					  
-				  int lastItem = mouseOnItem;
-			    mouseOnItem = mouseOverItem(Pos, itemCount);
-				  if(lastItem != mouseOnItem)
-					  if(_engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + mouseOnItem) || _engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + lastItem))
-						  redraw = true;
-			  }
-			  break;
-		  case kFocusMagic:
-			  if(enableFlags.get(kMagicMenu)) {
-				  int lastItem = mouseOnItem;
-			    mouseOnItem = mouseOverMagic(Pos);
-				  if(lastItem != mouseOnItem)
-					  if(_engine->getScriptManager()->getStateValue(StateKey_Spell_1 + mouseOnItem) || _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + lastItem))
-						  redraw = true;
-			  }
-			  break;
-		  case kFocusMain:
-		    break;
-    }
-	} 
-  MenuManager::onMouseMove(Pos);
+		case kFocusItems:
+			if (enableFlags.get(kItemsMenu)) {
+				int itemCount = _engine->getScriptManager()->getStateValue(StateKey_Inv_TotalSlots);
+				if (itemCount == 0)
+					itemCount = 20;
+				else if (itemCount > 50)
+					itemCount = 50;
+				int lastItem = mouseOnItem;
+				mouseOnItem = mouseOverItem(Pos, itemCount);
+				if (lastItem != mouseOnItem)
+					if (_engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + mouseOnItem) || _engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + lastItem))
+						redraw = true;
+			}
+			break;
+		case kFocusMagic:
+			if (enableFlags.get(kMagicMenu)) {
+				int lastItem = mouseOnItem;
+				mouseOnItem = mouseOverMagic(Pos);
+				if (lastItem != mouseOnItem)
+					if (_engine->getScriptManager()->getStateValue(StateKey_Spell_1 + mouseOnItem) || _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + lastItem))
+						redraw = true;
+			}
+			break;
+		case kFocusMain:
+			break;
+		}
+	}
+	MenuManager::onMouseMove(Pos);
 }
 
 int MenuZGI::mouseOverItem(const Common::Point &Pos, int itemCount) {
-  int itemWidth = (wSideMenu - 28) / itemCount;
-  Common::Rect itemHotspot = Common::Rect(28,hSideMenu);
-  itemHotspot.moveTo(itemsOrigin + itemsScroller.Pos);
-  for (int i = 0; i < itemCount; i++) {
-	  if(itemHotspot.contains(Pos))
-      return i;
-	  itemHotspot.translate(itemWidth,0);
-  }
-  return -1;
+	int itemWidth = (wSideMenu - 28) / itemCount;
+	Common::Rect itemHotspot = Common::Rect(28, hSideMenu);
+	itemHotspot.moveTo(itemsOrigin + itemsScroller.Pos);
+	for (int i = 0; i < itemCount; i++) {
+		if (itemHotspot.contains(Pos))
+			return i;
+		itemHotspot.translate(itemWidth, 0);
+	}
+	return -1;
 }
 
 int MenuZGI::mouseOverMagic(const Common::Point &Pos) {
-  Common::Rect magicHotspot(28,hSideMenu);
-  magicHotspot.moveTo(magicOrigin + magicScroller.Pos);
-  magicHotspot.translate(28,0); //Offset from end of menu
-  for (int i = 0; i < 12; i++) {
-    if(magicHotspot.contains(Pos))
-      return i;
-  magicHotspot.translate(magicWidth,0);
-  }
-  return -1;
+	Common::Rect magicHotspot(28, hSideMenu);
+	magicHotspot.moveTo(magicOrigin + magicScroller.Pos);
+	magicHotspot.translate(28, 0); //Offset from end of menu
+	for (int i = 0; i < 12; i++) {
+		if (magicHotspot.contains(Pos))
+			return i;
+		magicHotspot.translate(magicWidth, 0);
+	}
+	return -1;
 }
 
 void MenuZGI::process(uint32 deltatime) {
-	if(itemsScroller.update(deltatime)) {
-	  itemsArea.moveTo(itemsOrigin+itemsScroller.Pos);
-	  redraw = true;
-  }
-  if(magicScroller.update(deltatime)) {
-	  magicArea.moveTo(magicOrigin+magicScroller.Pos);
-	  redraw = true;
-  }
-  MenuManager::process(deltatime);
+	if (itemsScroller.update(deltatime)) {
+		itemsArea.moveTo(itemsOrigin + itemsScroller.Pos);
+		redraw = true;
+	}
+	if (magicScroller.update(deltatime)) {
+		magicArea.moveTo(magicOrigin + magicScroller.Pos);
+		redraw = true;
+	}
+	MenuManager::process(deltatime);
 }
 
 void MenuZGI::redrawAll() {
-  if(MenuManager::inMenu())
-    for(int8 i=menuFocus.size()-1; i>=0; i--)
-      switch (menuFocus[i]) {
-        case kFocusItems:
-          if(enableFlags.get(kItemsMenu)) {
-            redrawItems();
-          }
-    	    break;
-        case kFocusMagic:
-          if(enableFlags.get(kMagicMenu)) {
-            redrawMagic();
-          }
-	        break;
-        case kFocusMain:
-          redrawMain(); 
-	        break;
-        default:
-	        break;
-      }
+	if (MenuManager::inMenu())
+		for (int8 i = menuFocus.size() - 1; i >= 0; i--)
+			switch (menuFocus[i]) {
+			case kFocusItems:
+				if (enableFlags.get(kItemsMenu)) {
+					redrawItems();
+				}
+				break;
+			case kFocusMagic:
+				if (enableFlags.get(kMagicMenu)) {
+					redrawMagic();
+				}
+				break;
+			case kFocusMain:
+				redrawMain();
+				break;
+			default:
+				break;
+			}
 }
 
 void MenuZGI::redrawMagic() {
-  const int16 yOrigin = _menuArea.width();
-  _engine->getRenderManager()->blitSurfaceToMenu(menuBack[kFocusMagic], yOrigin+magicScroller.Pos.x, 0, 0);
-  for (int i = 0; i < 12; i++) {
-    bool inrect = false;
-    if(mouseOnItem == i)
-	    inrect = true;
-    uint curItemId = _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + i);
-    if(curItemId) {
-	    if(_engine->getScriptManager()->getStateValue(StateKey_Reversed_Spellbooc) == 1)
-		    curItemId = 0xEE + i;
-	    else
-		    curItemId = 0xE0 + i;
-    }
-    if(curItemId != 0) {
-	    if(itemId[i] != curItemId) {
-		    char buf[16];
-		    Common::sprintf_s(buf, "gmzwu%2.2x1.tga", curItemId);
-		    magic[i][0] = _engine->getRenderManager()->loadImage(buf, false);
-		    Common::sprintf_s(buf, "gmzxu%2.2x1.tga", curItemId);
-		    magic[i][1] = _engine->getRenderManager()->loadImage(buf, false);
-		    magicId[i] = curItemId;
-	    }
-	    if(inrect)
-		    _engine->getRenderManager()->blitSurfaceToMenu(*magic[i][1], yOrigin + magicScroller.Pos.x + 28 + magicWidth*i, 0, 0);
-	    else
-		    _engine->getRenderManager()->blitSurfaceToMenu(*magic[i][0], yOrigin + magicScroller.Pos.x + 28 + magicWidth*i, 0, 0);
-    } 
-    else {
-	    if(magic[i][0]) {
-		    magic[i][0]->free();
-		    delete magic[i][0];
-		    magic[i][0] = NULL;
-	    }
-	    if(magic[i][1]) {
-		    magic[i][1]->free();
-		    delete magic[i][1];
-		    magic[i][1] = NULL;
-	    }
-	    magicId[i] = 0;
-    }
-  }
-  clean = false;
+	const int16 yOrigin = _menuArea.width();
+	_engine->getRenderManager()->blitSurfaceToMenu(menuBack[kFocusMagic], yOrigin + magicScroller.Pos.x, 0, 0);
+	for (int i = 0; i < 12; i++) {
+		bool inrect = false;
+		if (mouseOnItem == i)
+			inrect = true;
+		uint curItemId = _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + i);
+		if (curItemId) {
+			if (_engine->getScriptManager()->getStateValue(StateKey_Reversed_Spellbooc) == 1)
+				curItemId = 0xEE + i;
+			else
+				curItemId = 0xE0 + i;
+		}
+		if (curItemId != 0) {
+			if (itemId[i] != curItemId) {
+				char buf[16];
+				Common::sprintf_s(buf, "gmzwu%2.2x1.tga", curItemId);
+				magic[i][0] = _engine->getRenderManager()->loadImage(buf, false);
+				Common::sprintf_s(buf, "gmzxu%2.2x1.tga", curItemId);
+				magic[i][1] = _engine->getRenderManager()->loadImage(buf, false);
+				magicId[i] = curItemId;
+			}
+			if (inrect)
+				_engine->getRenderManager()->blitSurfaceToMenu(*magic[i][1], yOrigin + magicScroller.Pos.x + 28 + magicWidth * i, 0, 0);
+			else
+				_engine->getRenderManager()->blitSurfaceToMenu(*magic[i][0], yOrigin + magicScroller.Pos.x + 28 + magicWidth * i, 0, 0);
+		} else {
+			if (magic[i][0]) {
+				magic[i][0]->free();
+				delete magic[i][0];
+				magic[i][0] = NULL;
+			}
+			if (magic[i][1]) {
+				magic[i][1]->free();
+				delete magic[i][1];
+				magic[i][1] = NULL;
+			}
+			magicId[i] = 0;
+		}
+	}
+	clean = false;
 }
 
 void MenuZGI::redrawItems() {
-  _engine->getRenderManager()->blitSurfaceToMenu(menuBack[kFocusItems], itemsScroller.Pos.x, 0, 0);
-  int itemCount = _engine->getScriptManager()->getStateValue(StateKey_Inv_TotalSlots);
-  if(itemCount == 0)
-    itemCount = 20;
-  else if(itemCount > 50)
-    itemCount = 50;
-  int itemWidth = (wSideMenu - 28) / itemCount;
-
-  for (int i = 0; i < itemCount; i++) {
-    bool inrect = false;
-    if(mouseOnItem == i)
-	    inrect = true;
-    uint curItemId = _engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + i);
-
-    if(curItemId != 0) {
-	    if(itemId[i] != curItemId) {
-		    char buf[16];
-		    Common::sprintf_s(buf, "gmzwu%2.2x1.tga", curItemId);
-		    items[i][0] = _engine->getRenderManager()->loadImage(buf, false);
-		    Common::sprintf_s(buf, "gmzxu%2.2x1.tga", curItemId);
-		    items[i][1] = _engine->getRenderManager()->loadImage(buf, false);
-		    itemId[i] = curItemId;
-	    }
-	    if(inrect)
-		    _engine->getRenderManager()->blitSurfaceToMenu(*items[i][1], itemsScroller.Pos.x + itemWidth*i, 0, 0);
-	    else
-		    _engine->getRenderManager()->blitSurfaceToMenu(*items[i][0], itemsScroller.Pos.x + itemWidth*i, 0, 0);
-    } else {
-	    if(items[i][0]) {
-		    items[i][0]->free();
-		    delete items[i][0];
-		    items[i][0] = NULL;
-	    }
-	    if(items[i][1]) {
-		    items[i][1]->free();
-		    delete items[i][1];
-		    items[i][1] = NULL;
-	    }
-	    itemId[i] = 0;
-    }
-  }
-  clean = false;
+	_engine->getRenderManager()->blitSurfaceToMenu(menuBack[kFocusItems], itemsScroller.Pos.x, 0, 0);
+	int itemCount = _engine->getScriptManager()->getStateValue(StateKey_Inv_TotalSlots);
+	if (itemCount == 0)
+		itemCount = 20;
+	else if (itemCount > 50)
+		itemCount = 50;
+	int itemWidth = (wSideMenu - 28) / itemCount;
+
+	for (int i = 0; i < itemCount; i++) {
+		bool inrect = false;
+		if (mouseOnItem == i)
+			inrect = true;
+		uint curItemId = _engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + i);
+
+		if (curItemId != 0) {
+			if (itemId[i] != curItemId) {
+				char buf[16];
+				Common::sprintf_s(buf, "gmzwu%2.2x1.tga", curItemId);
+				items[i][0] = _engine->getRenderManager()->loadImage(buf, false);
+				Common::sprintf_s(buf, "gmzxu%2.2x1.tga", curItemId);
+				items[i][1] = _engine->getRenderManager()->loadImage(buf, false);
+				itemId[i] = curItemId;
+			}
+			if (inrect)
+				_engine->getRenderManager()->blitSurfaceToMenu(*items[i][1], itemsScroller.Pos.x + itemWidth * i, 0, 0);
+			else
+				_engine->getRenderManager()->blitSurfaceToMenu(*items[i][0], itemsScroller.Pos.x + itemWidth * i, 0, 0);
+		} else {
+			if (items[i][0]) {
+				items[i][0]->free();
+				delete items[i][0];
+				items[i][0] = NULL;
+			}
+			if (items[i][1]) {
+				items[i][1]->free();
+				delete items[i][1];
+				items[i][1] = NULL;
+			}
+			itemId[i] = 0;
+		}
+	}
+	clean = false;
 }
 
 MenuNemesis::MenuNemesis(ZVision *engine, const Common::Rect menuArea) :
 	MenuManager(engine, menuArea, nemesisParams) {
 
-  //Buffer menu background image
+	//Buffer menu background image
 	_engine->getRenderManager()->readImageToSurface("bar.tga", mainBack, false);
-	
+
 	char buf[24];
 	for (int i = 0; i < 4; i++) {
-    //Buffer menu buttons
+		//Buffer menu buttons
 		for (int j = 0; j < 6; j++) {
 			Common::sprintf_s(buf, "butfrm%d%d.tga", i + 1, j);
 			_engine->getRenderManager()->readImageToSurface(buf, mainButtons[i][j], false);
@@ -572,17 +571,17 @@ MenuNemesis::~MenuNemesis() {
 }
 
 bool MenuNemesis::inMenu(const Common::Point &Pos) {
-  return menuTriggerArea.contains(Pos) || (menuFocus.front() != kFocusNone);
+	return menuTriggerArea.contains(Pos) || (menuFocus.front() != kFocusNone);
 }
 
 void MenuNemesis::onMouseMove(const Common::Point &Pos) {
-  //Trigger main menu scrolldown to get mouse over main trigger area
-  //Set focus to topmost layer of menus that mouse is currently over
-  if(mainArea.contains(Pos) || menuTriggerArea.contains(Pos))
-    setFocus(kFocusMain);
-  else
-    setFocus(kFocusNone);
-  MenuManager::onMouseMove(Pos);
+	//Trigger main menu scrolldown to get mouse over main trigger area
+	//Set focus to topmost layer of menus that mouse is currently over
+	if (mainArea.contains(Pos) || menuTriggerArea.contains(Pos))
+		setFocus(kFocusMain);
+	else
+		setFocus(kFocusNone);
+	MenuManager::onMouseMove(Pos);
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/menu.h b/engines/zvision/scripting/menu.h
index 23ca91d8cad..56d86eb19e1 100644
--- a/engines/zvision/scripting/menu.h
+++ b/engines/zvision/scripting/menu.h
@@ -44,44 +44,44 @@ enum {
 };
 
 struct MenuParams {
-  int16 wxButs[4][2];   //Widths & X positions of main menu buttons; {Save, Restore, Prefs, Quit}
-  int16 wMain;  //Width of main menu background
-  int8 idleFrame; //Frame to display of unselected main menu button
-  int8 activeFrame; //Frame to display of selected main menu button when mouse is down
-  int8 clickedFrame; //Frame to display of selected main menu button when mouse is down
-  Common::Point activePos;  //Fully scrolled main menu position, relative to origin of menu area
-  Common::Point idlePos;  //Fully retracted main menu position, relative to origin of menu area
-  int16 period; //Duration of main menu scrolldown
-  int16 triggerHeight;  //Height of menu trigger area when inactive
-  int16 buttonPeriod; //Duration of main menu button animation
+	int16 wxButs[4][2];   //Widths & X positions of main menu buttons; {Save, Restore, Prefs, Quit}
+	int16 wMain;  //Width of main menu background
+	int8 idleFrame; //Frame to display of unselected main menu button
+	int8 activeFrame; //Frame to display of selected main menu button when mouse is down
+	int8 clickedFrame; //Frame to display of selected main menu button when mouse is down
+	Common::Point activePos;  //Fully scrolled main menu position, relative to origin of menu area
+	Common::Point idlePos;  //Fully retracted main menu position, relative to origin of menu area
+	int16 period; //Duration of main menu scrolldown
+	int16 triggerHeight;  //Height of menu trigger area when inactive
+	int16 buttonPeriod; //Duration of main menu button animation
 };
 
 //NB - menu area is same width as working window.
 
 static const MenuParams nemesisParams {
-  { {120 , -1}, {144, 120}, {128, 264}, {120, 392} },
-  512,
-  -1,
-  4,
-  5,
-  Common::Point(0,0),
-  Common::Point(0,-32),
-  500,
-  2,
-  500
+	{ {120, -1}, {144, 120}, {128, 264}, {120, 392} },
+	512,
+	-1,
+	4,
+	5,
+	Common::Point(0, 0),
+	Common::Point(0, -32),
+	500,
+	2,
+	500
 };
 
 static const MenuParams zgiParams {
-  { {135 , 50}, {135, 185}, {135, 320}, {135, 455} },
-  580,
-  0,
-  1,
-  1,
-  Common::Point(30,0),
-  Common::Point(30,-20),
-  250,
-  32,
-  0
+	{ {135, 50}, {135, 185}, {135, 320}, {135, 455} },
+	580,
+	0,
+	1,
+	1,
+	Common::Point(30, 0),
+	Common::Point(30, -20),
+	250,
+	32,
+	0
 };
 
 class MenuManager {
@@ -92,8 +92,12 @@ public:
 	virtual void onMouseDown(const Common::Point &Pos);
 	virtual void onMouseUp(const Common::Point &Pos);
 	virtual void process(uint32 deltaTimeInMillis);
-  bool inMenu() {return prevInMenu;};
-  virtual bool inMenu(const Common::Point &Pos) {return false;}; //For widescreen mod; used to suspend panning, tilting & scripting triggers when the mouse is within the working window but also in the menu.
+	bool inMenu() {
+		return prevInMenu;
+	};
+	virtual bool inMenu(const Common::Point &Pos) {
+		return false;
+	}; //For widescreen mod; used to suspend panning, tilting & scripting triggers when the mouse is within the working window but also in the menu.
 
 	void mainMouseDown(const Common::Point &Pos); //Show clicked graphic under selected button
 	bool mainMouseMove(const Common::Point &Pos); //return true if selected button has changed
@@ -103,40 +107,40 @@ public:
 		return menuBarFlag;
 	}
 	bool getEnable(uint8 flag) {
-	  return enableFlags.get(flag);
+		return enableFlags.get(flag);
 	}
-	
+
 protected:
-  virtual void redrawAll() {};
-  void redrawMain();
+	virtual void redrawAll() {};
+	void redrawMain();
 	int mouseOverMain(const Common::Point &Pos);
 	void setFocus(int8 currentFocus);
-	
+
 //	bool inMenu = false;  //True if menus are currently visible
 	bool prevInMenu = false;
 	bool redraw = true;
 	int mouseOnItem = -1;
 	static const uint8 hMainMenu = 32;
-  int8 mainClicked = -1;
+	int8 mainClicked = -1;
 
 	ZVision *_engine;
-  const MenuParams _params;
+	const MenuParams _params;
 	uint16 menuBarFlag;
-  const Common::Rect _menuArea;
+	const Common::Rect _menuArea;
 	const Common::Point menuOrigin;
-  const Common::Rect menuTriggerArea;
+	const Common::Rect menuTriggerArea;
 	Graphics::Surface mainBack;
 	Graphics::Surface mainButtons[4][6];
 	Common::BitArray enableFlags;
-  Common::Rect mainArea;
+	Common::Rect mainArea;
 	Common::Rect menuHotspots[4];
-  int8 mainFrames[4]; //Frame to display of each main menu button; first row is currently displayed, 2nd row is backbuffer for idle animations
-  Scroller mainScroller;
+	int8 mainFrames[4]; //Frame to display of each main menu button; first row is currently displayed, 2nd row is backbuffer for idle animations
+	Scroller mainScroller;
 	FocusList<int8> menuFocus;  //Order in which menus have most recently had focus; determines current mouse focus & order in which to redraw them.
 	bool clean = false; //Whether or not to blank
-  LinearScroller* buttonAnim[4];
+	LinearScroller *buttonAnim[4];
 };
- 
+
 class MenuZGI: public MenuManager {
 public:
 	MenuZGI(ZVision *engine, Common::Rect menuArea);
@@ -144,9 +148,9 @@ public:
 	void onMouseMove(const Common::Point &Pos) override;  //NB Pos is in screen coordinates
 	void onMouseUp(const Common::Point &Pos) override;
 	void process(uint32 deltaTimeInMillis) override;
-  bool inMenu(const Common::Point &Pos) override;
+	bool inMenu(const Common::Point &Pos) override;
 private:
-  void redrawAll() override;
+	void redrawAll() override;
 	Graphics::Surface menuBack[3];
 	Graphics::Surface *items[50][2];
 	uint itemId[50];
@@ -158,21 +162,21 @@ private:
 	void redrawMagic();
 	int mouseOverItem(const Common::Point &Pos, int itemCount);
 	int mouseOverMagic(const Common::Point &Pos);
-	
+
 	static const uint16 hSideMenu = 32;
 	static const uint16 wSideMenu = 600;
 	static const uint16 wSideMenuTab = 20;
-  static const int16 magicWidth = 47;
+	static const int16 magicWidth = 47;
 
-  const int16 sideMenuPeriod = 300;
+	const int16 sideMenuPeriod = 300;
 
-  Scroller itemsScroller, magicScroller;
+	Scroller itemsScroller, magicScroller;
 
-  const Common::Point magicOrigin;
-  const Common::Point itemsOrigin;
+	const Common::Point magicOrigin;
+	const Common::Point itemsOrigin;
 
-  Common::Rect magicArea;
-  Common::Rect itemsArea;
+	Common::Rect magicArea;
+	Common::Rect itemsArea;
 };
 
 class MenuNemesis: public MenuManager {
@@ -180,9 +184,9 @@ public:
 	MenuNemesis(ZVision *engine, Common::Rect menuArea);
 	~MenuNemesis() override;
 	void onMouseMove(const Common::Point &Pos) override;
-  bool inMenu(const Common::Point &Pos) override;
+	bool inMenu(const Common::Point &Pos) override;
 private:
-  void redrawAll() override;
+	void redrawAll() override;
 };
 
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/scr_file_handling.cpp b/engines/zvision/scripting/scr_file_handling.cpp
index f42ec387f72..93e8026cf1f 100644
--- a/engines/zvision/scripting/scr_file_handling.cpp
+++ b/engines/zvision/scripting/scr_file_handling.cpp
@@ -45,53 +45,51 @@
 namespace ZVision {
 
 void ScriptManager::parseScrFile(const Common::Path &fileName, ScriptScope &scope) {
-  auto parse = [&](Common::File &file) {
-	  while (!file.eos()) {
-		  Common::String line = file.readLine();
-		  if (file.err())
-			  error("Error parsing scr file: %s", fileName.toString().c_str());
-		  trimCommentsAndWhiteSpace(&line);
-		  if (line.empty())
-			  continue;
-		  if (line.matchString("puzzle:*", true)) {
-			  Puzzle *puzzle = new Puzzle();
-			  sscanf(line.c_str(), "puzzle:%u", &(puzzle->key));
-			  if (getStateFlag(puzzle->key) & Puzzle::ONCE_PER_INST)
-				  setStateValue(puzzle->key, 0);
-			  parsePuzzle(puzzle, file);
-			  scope.puzzles.push_back(puzzle);
-		  } 
-		  else if (line.matchString("control:*", true)) {
-			  Control *ctrl = parseControl(line, file);
-			  if (ctrl)
-				  scope.controls.push_back(ctrl);
-		  }
-	  }
+	auto parse = [&](Common::File & file) {
+		while (!file.eos()) {
+			Common::String line = file.readLine();
+			if (file.err())
+				error("Error parsing scr file: %s", fileName.toString().c_str());
+			trimCommentsAndWhiteSpace(&line);
+			if (line.empty())
+				continue;
+			if (line.matchString("puzzle:*", true)) {
+				Puzzle *puzzle = new Puzzle();
+				sscanf(line.c_str(), "puzzle:%u", &(puzzle->key));
+				if (getStateFlag(puzzle->key) & Puzzle::ONCE_PER_INST)
+					setStateValue(puzzle->key, 0);
+				parsePuzzle(puzzle, file);
+				scope.puzzles.push_back(puzzle);
+			} else if (line.matchString("control:*", true)) {
+				Control *ctrl = parseControl(line, file);
+				if (ctrl)
+					scope.controls.push_back(ctrl);
+			}
+		}
 	};
-	
+
 	Common::File mainFile;
 	Common::File auxFile;
 	Common::String auxFileName = fileName.toString();
-  replace(auxFileName, Common::String(".scr"), Common::String(".aux"));
-  debug(1,"Auxiliary filename %s", auxFileName.c_str());
-  Common::Path auxFilePath(auxFileName);
-  debug(1,"Auxiliary path %s", auxFilePath.toString().c_str());
-  
+	replace(auxFileName, Common::String(".scr"), Common::String(".aux"));
+	debug(1, "Auxiliary filename %s", auxFileName.c_str());
+	Common::Path auxFilePath(auxFileName);
+	debug(1, "Auxiliary path %s", auxFilePath.toString().c_str());
+
 	if (!_engine->getSearchManager()->openFile(mainFile, fileName))
 		error("Script file not found: %s", fileName.toString().c_str());
 	else {
-    debug(1,"Parsing primary script file");
-  	parse(mainFile);
-  	//TODO - add config option to disable/enable auxiliary scripting
-	  if (auxFile.exists(auxFilePath)) {
-	    debug(1,"Auxiliary script file found");
-	    if (auxFile.open(auxFilePath)) {
-	      debug(1,"Parsing auxiliary script file %s", auxFilePath.toString().c_str());
-        parse(auxFile);
-      }
-      else
-        debug(1,"Unable to open auxiliary script file %s", auxFilePath.toString().c_str());
-    }
+		debug(1, "Parsing primary script file");
+		parse(mainFile);
+		//TODO - add config option to disable/enable auxiliary scripting
+		if (auxFile.exists(auxFilePath)) {
+			debug(1, "Auxiliary script file found");
+			if (auxFile.open(auxFilePath)) {
+				debug(1, "Parsing auxiliary script file %s", auxFilePath.toString().c_str());
+				parse(auxFile);
+			} else
+				debug(1, "Unable to open auxiliary script file %s", auxFilePath.toString().c_str());
+		}
 	}
 	scope.procCount = 0;
 }
@@ -104,56 +102,57 @@ void ScriptManager::parsePuzzle(Puzzle *puzzle, Common::SeekableReadStream &stre
 			parseCriteria(stream, puzzle->criteriaList, puzzle->key);
 		else if (line.matchString("results {", true)) {
 			parseResults(stream, puzzle->resultActions, puzzle->key);
-      //WORKAROUNDS:
-      switch(_engine->getGameId()) {
-        case GID_NEMESIS: {
-			      // WORKAROUND for a script bug in Zork Nemesis, room ve5e (tuning
-			      // fork box closeup). If the player leaves the screen while the
-			      // box is open, puzzle 19398 shows the animation where the box
-			      // closes, but the box state (state variable 19397) is not updated.
-			      // We insert the missing assignment for the box state here.
-			      // Fixes bug #6803.
-			      if (puzzle->key == 19398)
-				      puzzle->resultActions.push_back(new ActionAssign(_engine, 11, "19397, 0"));
-			    }
-          break;
-        case GID_GRANDINQUISITOR: {
-			      switch(puzzle->key) {
-			        case 10836:
-			          // WORKAROUND for bug #10604. If the player is looking at the
-			          // cigar box when Antharia Jack returns to examine the lamp,
-			          // pp1f_video_flag remains 1. Later, when the player returns
-			          // to pick up the lantern, the game will try to play the
-			          // cutscene again, but since that script has already been
-			          // run the player gets stuck in a dark room instead. We have
-			          // to add the assignment action to the front, or it won't be
-			          // reached because changing the location terminates the script.
-			          //
-			          // Fixing it this way only keeps the bug from happening. It
-			          // will not repair old savegames.
-			          //
-			          // Note that the bug only affects the DVD version. The CD
-			          // version doesn't have a separate room for the cutscene.
-			          if (_engine->getFeatures() & ADGF_DVD)
-				          puzzle->resultActions.push_front(new ActionAssign(_engine, 11, "10803, 0"));
-			          break;
-              // WORKAROUND for a script bug in Zork: Grand Inquisitor, room dc10.
-              // Background heartbeat sound effect never terminates upon location change.
-			        case 2341:
-			        case 2344:
-			        case 17545:
-      					puzzle->resultActions.push_front(new ActionKill(_engine, 11, "02310"));
-      					break;
-      				default:
-      				  break;
-			      }
-		      }
-          break;
-        default:
-          break;
-      }
-		} 
-		else if (line.matchString("flags {", true))
+			//WORKAROUNDS:
+			switch (_engine->getGameId()) {
+			case GID_NEMESIS: {
+				// WORKAROUND for a script bug in Zork Nemesis, room ve5e (tuning
+				// fork box closeup). If the player leaves the screen while the
+				// box is open, puzzle 19398 shows the animation where the box
+				// closes, but the box state (state variable 19397) is not updated.
+				// We insert the missing assignment for the box state here.
+				// Fixes bug #6803.
+				if (puzzle->key == 19398)
+					puzzle->resultActions.push_back(new ActionAssign(_engine, 11, "19397, 0"));
+			}
+			break;
+			case GID_GRANDINQUISITOR: {
+				switch (puzzle->key) {
+				case 10836:
+					// WORKAROUND for bug #10604. If the player is looking at the
+					// cigar box when Antharia Jack returns to examine the lamp,
+					// pp1f_video_flag remains 1. Later, when the player returns
+					// to pick up the lantern, the game will try to play the
+					// cutscene again, but since that script has already been
+					// run the player gets stuck in a dark room instead. We have
+					// to add the assignment action to the front, or it won't be
+					// reached because changing the location terminates the script.
+					//
+					// Fixing it this way only keeps the bug from happening. It
+					// will not repair old savegames.
+					//
+					// Note that the bug only affects the DVD version. The CD
+					// version doesn't have a separate room for the cutscene.
+					if (_engine->getFeatures() & ADGF_DVD)
+						puzzle->resultActions.push_front(new ActionAssign(_engine, 11, "10803, 0"));
+					break;
+				// WORKAROUND for a script bug in Zork: Grand Inquisitor, room dc10.
+				// Background heartbeat sound effect never terminates upon location change.
+				case 2341:
+				// fall through
+				case 2344:
+				// fall through
+				case 17545:
+					puzzle->resultActions.push_front(new ActionKill(_engine, 11, "02310"));
+					break;
+				default:
+					break;
+				}
+			}
+			break;
+			default:
+				break;
+			}
+		} else if (line.matchString("flags {", true))
 			setStateFlag(puzzle->key, parseFlags(stream));
 		line = stream.readLine();
 		trimCommentsAndWhiteSpace(&line);
@@ -177,43 +176,43 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 		return false;
 	// Create a new List to hold the CriteriaEntries
 	criteriaList.push_back(Common::List<Puzzle::CriteriaEntry>());
-	
+
 	//WORKAROUNDS
-  switch(_engine->getGameId()) {
-    case GID_NEMESIS:
-	    // WORKAROUND for a script bug in Zork: Nemesis, room td9e (fist puzzle)
-	    // Since we patch the script that triggers when manipulating the left fist
-	    // (below), we add an additional check for the left fist sound, so that it
-	    // doesn't get killed immediately when the left fist animation starts.
-	    // Together with the workaround below, it fixes bug #6783.
-	    if (key == 3594) {
-		    Puzzle::CriteriaEntry entry;
-		    entry.key = 567;
-		    entry.criteriaOperator = Puzzle::NOT_EQUAL_TO;
-		    entry.argumentIsAKey = false;
-		    entry.argument = 1;
-		    criteriaList.back().push_back(entry);
-	    }
-      break;
-    case GID_GRANDINQUISITOR:
-	    // WORKAROUND for a script bug in Zork: Grand Inquisitor, room me2j
-	    // (Closing the Time Tunnels). When the time tunnel is open the game
-	    // shows a close-up of only the tunnel, instead of showing the entire
-	    // booth. However, the scripts that draw the lever in its correct
-	    // state do not test this flag, causing it to be drawn when it should
-	    // not be. This fixes bug #6770.
-	    if (key == 9536) {
-		    Puzzle::CriteriaEntry entry;
-		    entry.key = 9404; // me2j_time_tunnel_open
-		    entry.criteriaOperator = Puzzle::EQUAL_TO;
-		    entry.argumentIsAKey = false;
-		    entry.argument = 0;
-		    criteriaList.back().push_back(entry);
-	    }
-      break;
-    default:
-      break;
-  }
+	switch (_engine->getGameId()) {
+	case GID_NEMESIS:
+		// WORKAROUND for a script bug in Zork: Nemesis, room td9e (fist puzzle)
+		// Since we patch the script that triggers when manipulating the left fist
+		// (below), we add an additional check for the left fist sound, so that it
+		// doesn't get killed immediately when the left fist animation starts.
+		// Together with the workaround below, it fixes bug #6783.
+		if (key == 3594) {
+			Puzzle::CriteriaEntry entry;
+			entry.key = 567;
+			entry.criteriaOperator = Puzzle::NOT_EQUAL_TO;
+			entry.argumentIsAKey = false;
+			entry.argument = 1;
+			criteriaList.back().push_back(entry);
+		}
+		break;
+	case GID_GRANDINQUISITOR:
+		// WORKAROUND for a script bug in Zork: Grand Inquisitor, room me2j
+		// (Closing the Time Tunnels). When the time tunnel is open the game
+		// shows a close-up of only the tunnel, instead of showing the entire
+		// booth. However, the scripts that draw the lever in its correct
+		// state do not test this flag, causing it to be drawn when it should
+		// not be. This fixes bug #6770.
+		if (key == 9536) {
+			Puzzle::CriteriaEntry entry;
+			entry.key = 9404; // me2j_time_tunnel_open
+			entry.criteriaOperator = Puzzle::EQUAL_TO;
+			entry.argumentIsAKey = false;
+			entry.argument = 0;
+			criteriaList.back().push_back(entry);
+		}
+		break;
+	default:
+		break;
+	}
 
 	while (!stream.eos() && !line.contains('}')) {
 		Puzzle::CriteriaEntry entry;
@@ -257,8 +256,7 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 		if (token.contains('[')) {
 			sscanf(token.c_str(), "[%u]", &(entry.argument));
 			entry.argumentIsAKey = true;
-		} 
-		else {
+		} else {
 			sscanf(token.c_str(), "%u", &(entry.argument));
 			entry.argumentIsAKey = false;
 		}
@@ -282,7 +280,7 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 			entry.criteriaOperator = Puzzle::NOT_EQUAL_TO;
 			entry.argument = 2;
 		}
-		
+
 		criteriaList.back().push_back(entry);
 		line = stream.readLine();
 		trimCommentsAndWhiteSpace(&line);
@@ -299,31 +297,31 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 	// TODO: Re-order the if-then statements in order of highest occurrence
 	//While within results block
 	while (!stream.eos() && !line.contains('}')) {
-	  //Skip empty lines
+		//Skip empty lines
 		if (line.empty()) {
 			line = stream.readLine();
 			trimCommentsAndWhiteSpace(&line);
 			line.toLowercase();
 			continue;
 		}
-    debug(4,"Result line: %s", line.c_str());	
+		debug(4, "Result line: %s", line.c_str());
 		const char *chrs = line.c_str();
 		uint pos;
-/*/
-		//Iterate along line until colon encountered
-		for (pos = 0; pos < line.size(); pos++) {
-			if (chrs[pos] == ':')
-				break;
-		}
-/*/
-	  if(line.matchString("action:*", true))
-      pos = 6;
-	  else if(line.matchString("event:*", true))
-	    pos = 5;
-	  else if(line.matchString("background:*", true))
-	    pos = 10;
-	  else
-	    continue;
+		/*/
+		        //Iterate along line until colon encountered
+		        for (pos = 0; pos < line.size(); pos++) {
+		            if (chrs[pos] == ':')
+		                break;
+		        }
+		/*/
+		if (line.matchString("action:*", true))
+			pos = 6;
+		else if (line.matchString("event:*", true))
+			pos = 5;
+		else if (line.matchString("background:*", true))
+			pos = 10;
+		else
+			continue;
 //*/
 		if (pos < line.size()) {  //Stuff left
 			uint startpos = pos + 1;  //first character after colon
@@ -331,7 +329,7 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 			for (pos = startpos; pos < line.size(); pos++)
 				if (chrs[pos] == ':' || chrs[pos] == '(')
 					break;
-			debug(4,"startpos %d, pos %d, line.size %d", startpos, pos, line.size());
+			debug(4, "startpos %d, pos %d, line.size %d", startpos, pos, line.size());
 			int32 slot = 11;  //Non-setting default slot
 			Common::String args = "";
 			Common::String act(chrs + startpos, chrs + pos);
@@ -354,117 +352,115 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 					args = Common::String(chrs + startpos, chrs + pos);
 				}
 			}
-				debug(4,"Action string: '%s', slot %d, arguments string '%s'", act.c_str(), slot, args.c_str());
+			debug(4, "Action string: '%s', slot %d, arguments string '%s'", act.c_str(), slot, args.c_str());
 
-				// Parse for the action type
-				if (act.matchString("add", true)) {
-					actionList.push_back(new ActionAdd(_engine, slot, args));
-				} else if (act.matchString("animplay", true)) {
-					actionList.push_back(new ActionPlayAnimation(_engine, slot, args));
-				} else if (act.matchString("animpreload", true)) {
-					actionList.push_back(new ActionPreloadAnimation(_engine, slot, args));
-				} else if (act.matchString("animunload", true)) {
-					// Only used by ZGI (locations cd6e, cd6k, dg2f, dg4e, dv1j)
-					actionList.push_back(new ActionUnloadAnimation(_engine, slot, args));
-				} else if (act.matchString("attenuate", true)) {
-					actionList.push_back(new ActionAttenuate(_engine, slot, args));
-				} else if (act.matchString("assign", true)) {
-	        if (_engine->getGameId() == GID_GRANDINQUISITOR && key == 17761) {
-	          // WORKAROUND for a script bug in Zork: Grand Inquisitor, room tp1e.
-            // Background looping sound effect continuously restarts on every game cycle.
-            // This is caused by resetting itself to zero as a result of itself.
-            // Simple fix is to simply not generate this result assignment action at all.
-	        }
-	        else 
-  					actionList.push_back(new ActionAssign(_engine, slot, args));
-				} else if (act.matchString("change_location", true)) {
-					actionList.push_back(new ActionChangeLocation(_engine, slot, args));
-				} else if (act.matchString("crossfade", true)) {
-					actionList.push_back(new ActionCrossfade(_engine, slot, args));
+			// Parse for the action type
+			if (act.matchString("add", true)) {
+				actionList.push_back(new ActionAdd(_engine, slot, args));
+			} else if (act.matchString("animplay", true)) {
+				actionList.push_back(new ActionPlayAnimation(_engine, slot, args));
+			} else if (act.matchString("animpreload", true)) {
+				actionList.push_back(new ActionPreloadAnimation(_engine, slot, args));
+			} else if (act.matchString("animunload", true)) {
+				// Only used by ZGI (locations cd6e, cd6k, dg2f, dg4e, dv1j)
+				actionList.push_back(new ActionUnloadAnimation(_engine, slot, args));
+			} else if (act.matchString("attenuate", true)) {
+				actionList.push_back(new ActionAttenuate(_engine, slot, args));
+			} else if (act.matchString("assign", true)) {
+				if (_engine->getGameId() == GID_GRANDINQUISITOR && key == 17761) {
+					// WORKAROUND for a script bug in Zork: Grand Inquisitor, room tp1e.
+					// Background looping sound effect continuously restarts on every game cycle.
+					// This is caused by resetting itself to zero as a result of itself.
+					// Simple fix is to simply not generate this result assignment action at all.
+				} else
+					actionList.push_back(new ActionAssign(_engine, slot, args));
+			} else if (act.matchString("change_location", true)) {
+				actionList.push_back(new ActionChangeLocation(_engine, slot, args));
+			} else if (act.matchString("crossfade", true)) {
+				actionList.push_back(new ActionCrossfade(_engine, slot, args));
 //					debug(1,"\tpush.ActionCrossFade, script line: %s", line.c_str());
-				} else if (act.matchString("cursor", true)) {
-					actionList.push_back(new ActionCursor(_engine, slot, args));
-				} else if (act.matchString("debug", true)) {
-					// Not used. Purposely left empty
-				} else if (act.matchString("delay_render", true)) {
-					actionList.push_back(new ActionDelayRender(_engine, slot, args));
-				} else if (act.matchString("disable_control", true)) {
-					actionList.push_back(new ActionDisableControl(_engine, slot, args));
-				} else if (act.matchString("disable_venus", true)) {
-					// Not used. Purposely left empty
-				} else if (act.matchString("display_message", true)) {
-					actionList.push_back(new ActionDisplayMessage(_engine, slot, args));
-				} else if (act.matchString("dissolve", true)) {
-					actionList.push_back(new ActionDissolve(_engine));
-				} else if (act.matchString("distort", true)) {
-					// Only used by Zork: Nemesis for the "treatment" puzzle in the Sanitarium (aj30)
-					actionList.push_back(new ActionDistort(_engine, slot, args));
-				} else if (act.matchString("enable_control", true)) {
-					actionList.push_back(new ActionEnableControl(_engine, slot, args));
-				} else if (act.matchString("flush_mouse_events", true)) {
-					actionList.push_back(new ActionFlushMouseEvents(_engine, slot));
-				} else if (act.matchString("inventory", true)) {
-					actionList.push_back(new ActionInventory(_engine, slot, args));
-				} else if (act.matchString("kill", true)) {
-					// Only used by ZGI
-					actionList.push_back(new ActionKill(_engine, slot, args));
-				} else if (act.matchString("menu_bar_enable", true)) {
-					actionList.push_back(new ActionMenuBarEnable(_engine, slot, args));
-				} else if (act.matchString("music", true)) {
-					actionList.push_back(new ActionMusic(_engine, slot, args, false));
+			} else if (act.matchString("cursor", true)) {
+				actionList.push_back(new ActionCursor(_engine, slot, args));
+			} else if (act.matchString("debug", true)) {
+				// Not used. Purposely left empty
+			} else if (act.matchString("delay_render", true)) {
+				actionList.push_back(new ActionDelayRender(_engine, slot, args));
+			} else if (act.matchString("disable_control", true)) {
+				actionList.push_back(new ActionDisableControl(_engine, slot, args));
+			} else if (act.matchString("disable_venus", true)) {
+				// Not used. Purposely left empty
+			} else if (act.matchString("display_message", true)) {
+				actionList.push_back(new ActionDisplayMessage(_engine, slot, args));
+			} else if (act.matchString("dissolve", true)) {
+				actionList.push_back(new ActionDissolve(_engine));
+			} else if (act.matchString("distort", true)) {
+				// Only used by Zork: Nemesis for the "treatment" puzzle in the Sanitarium (aj30)
+				actionList.push_back(new ActionDistort(_engine, slot, args));
+			} else if (act.matchString("enable_control", true)) {
+				actionList.push_back(new ActionEnableControl(_engine, slot, args));
+			} else if (act.matchString("flush_mouse_events", true)) {
+				actionList.push_back(new ActionFlushMouseEvents(_engine, slot));
+			} else if (act.matchString("inventory", true)) {
+				actionList.push_back(new ActionInventory(_engine, slot, args));
+			} else if (act.matchString("kill", true)) {
+				// Only used by ZGI
+				actionList.push_back(new ActionKill(_engine, slot, args));
+			} else if (act.matchString("menu_bar_enable", true)) {
+				actionList.push_back(new ActionMenuBarEnable(_engine, slot, args));
+			} else if (act.matchString("music", true)) {
+				actionList.push_back(new ActionMusic(_engine, slot, args, false));
 //					debug(1,"\tpush.ActionMusic, script line: %s", line.c_str());
-				} else if (act.matchString("pan_track", true)) {
-					actionList.push_back(new ActionPanTrack(_engine, slot, args));
+			} else if (act.matchString("pan_track", true)) {
+				actionList.push_back(new ActionPanTrack(_engine, slot, args));
 //					debug(1,"\tpush.ActionPanTrack, script line: %s", line.c_str());
-				} else if (act.matchString("playpreload", true)) {
-					actionList.push_back(new ActionPlayPreloadAnimation(_engine, slot, args));
-				} else if (act.matchString("preferences", true)) {
-					actionList.push_back(new ActionPreferences(_engine, slot, args));
-				} else if (act.matchString("quit", true)) {
-					actionList.push_back(new ActionQuit(_engine, slot));
-				} else if (act.matchString("random", true)) {
-					actionList.push_back(new ActionRandom(_engine, slot, args));
-				} else if (act.matchString("region", true)) {
-					// Only used by Zork: Nemesis
-					actionList.push_back(new ActionRegion(_engine, slot, args));
-				} else if (act.matchString("restore_game", true)) {
-					// Only used by ZGI to load the restart game slot, r.svr.
-					// Used by the credits screen.
-					actionList.push_back(new ActionRestoreGame(_engine, slot, args));
-				} else if (act.matchString("rotate_to", true)) {
-					actionList.push_back(new ActionRotateTo(_engine, slot, args));
-				} else if (act.matchString("save_game", true)) {
-					// Not used. Purposely left empty
-				} else if (act.matchString("set_partial_screen", true)) {
-					actionList.push_back(new ActionSetPartialScreen(_engine, slot, args));
-				} else if (act.matchString("set_screen", true)) {
-					actionList.push_back(new ActionSetScreen(_engine, slot, args));
-				} else if (act.matchString("set_venus", true)) {
-					// Not used. Purposely left empty
-				} else if (act.matchString("stop", true)) {
-					actionList.push_back(new ActionStop(_engine, slot, args));
-				} else if (act.matchString("streamvideo", true)) {
-					actionList.push_back(new ActionStreamVideo(_engine, slot, args));
-				} else if (act.matchString("syncsound", true)) {
-					actionList.push_back(new ActionSyncSound(_engine, slot, args));
-				} else if (act.matchString("timer", true)) {
-					actionList.push_back(new ActionTimer(_engine, slot, args));
-				} else if (act.matchString("ttytext", true)) {
-					actionList.push_back(new ActionTtyText(_engine, slot, args));
-				} else if (act.matchString("universe_music", true)) {
-          if (_engine->getGameId() == GID_GRANDINQUISITOR && slot == 2310 && false) { //DISABLED - not effective, sound stops on all zoom-ins for some reason?
-          // WORKAROUND for a script bug in Zork: Grand Inquisitor, room dc10.
-          // Background looping sound effect never terminates upon location change.
-          // Seems that it should have been "music" instead of "universe_music."
-			      actionList.push_back(new ActionMusic(_engine, slot, args, false));
-          }
-          else 
-				    actionList.push_back(new ActionMusic(_engine, slot, args, true));
-				} else if (act.matchString("copy_file", true)) {
-					// Not used. Purposely left empty
-				} else {
-					warning("Unhandled result action type: %s", line.c_str());
-				}
+			} else if (act.matchString("playpreload", true)) {
+				actionList.push_back(new ActionPlayPreloadAnimation(_engine, slot, args));
+			} else if (act.matchString("preferences", true)) {
+				actionList.push_back(new ActionPreferences(_engine, slot, args));
+			} else if (act.matchString("quit", true)) {
+				actionList.push_back(new ActionQuit(_engine, slot));
+			} else if (act.matchString("random", true)) {
+				actionList.push_back(new ActionRandom(_engine, slot, args));
+			} else if (act.matchString("region", true)) {
+				// Only used by Zork: Nemesis
+				actionList.push_back(new ActionRegion(_engine, slot, args));
+			} else if (act.matchString("restore_game", true)) {
+				// Only used by ZGI to load the restart game slot, r.svr.
+				// Used by the credits screen.
+				actionList.push_back(new ActionRestoreGame(_engine, slot, args));
+			} else if (act.matchString("rotate_to", true)) {
+				actionList.push_back(new ActionRotateTo(_engine, slot, args));
+			} else if (act.matchString("save_game", true)) {
+				// Not used. Purposely left empty
+			} else if (act.matchString("set_partial_screen", true)) {
+				actionList.push_back(new ActionSetPartialScreen(_engine, slot, args));
+			} else if (act.matchString("set_screen", true)) {
+				actionList.push_back(new ActionSetScreen(_engine, slot, args));
+			} else if (act.matchString("set_venus", true)) {
+				// Not used. Purposely left empty
+			} else if (act.matchString("stop", true)) {
+				actionList.push_back(new ActionStop(_engine, slot, args));
+			} else if (act.matchString("streamvideo", true)) {
+				actionList.push_back(new ActionStreamVideo(_engine, slot, args));
+			} else if (act.matchString("syncsound", true)) {
+				actionList.push_back(new ActionSyncSound(_engine, slot, args));
+			} else if (act.matchString("timer", true)) {
+				actionList.push_back(new ActionTimer(_engine, slot, args));
+			} else if (act.matchString("ttytext", true)) {
+				actionList.push_back(new ActionTtyText(_engine, slot, args));
+			} else if (act.matchString("universe_music", true)) {
+				if (_engine->getGameId() == GID_GRANDINQUISITOR && slot == 2310 && false) { //DISABLED - not effective, sound stops on all zoom-ins for some reason?
+					// WORKAROUND for a script bug in Zork: Grand Inquisitor, room dc10.
+					// Background looping sound effect never terminates upon location change.
+					// Seems that it should have been "music" instead of "universe_music."
+					actionList.push_back(new ActionMusic(_engine, slot, args, false));
+				} else
+					actionList.push_back(new ActionMusic(_engine, slot, args, true));
+			} else if (act.matchString("copy_file", true)) {
+				// Not used. Purposely left empty
+			} else {
+				warning("Unhandled result action type: %s", line.c_str());
+			}
 		}
 		line = stream.readLine();
 		trimCommentsAndWhiteSpace(&line);
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index 7e702a11130..23368283e5f 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -54,9 +54,9 @@ ScriptManager::~ScriptManager() {
 }
 
 void ScriptManager::initialize(bool restarted) {
-  if(restarted) {
-	  _globalState.clear();
-	  _globalStateFlags.clear();
+	if (restarted) {
+		_globalState.clear();
+		_globalStateFlags.clear();
 	}
 	cleanScriptScope(universe);
 	cleanScriptScope(world);
@@ -67,31 +67,32 @@ void ScriptManager::initialize(bool restarted) {
 	_currentLocation.room = 0;
 	_currentLocation.view = 0;
 	_changeLocationDelayCycles = 0;
-  if(restarted) {
-	  for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); iter++)
-		  delete(*iter);
-	  _activeSideFx.clear();
-	  _referenceTable.clear();
-	  switch(_engine->getGameId()) {
-      case GID_GRANDINQUISITOR:
-        //Bypass logo video
-        setStateValue(16966, 1);  
-        //Ensure post-logo screen redraw is not inhibited in CD version
-        setStateValue(5813, 1);
-        //Bypass additional logo videos in DVD version
-        setStateValue(19810, 1);
-        setStateValue(19848, 1);
-        break;
-      case GID_NEMESIS:
-      default:
-        break;
-    }
+	if (restarted) {
+		for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); iter++)
+			delete (*iter);
+		_activeSideFx.clear();
+		_referenceTable.clear();
+		switch (_engine->getGameId()) {
+		case GID_GRANDINQUISITOR:
+			//Bypass logo video
+			setStateValue(16966, 1);
+			//Ensure post-logo screen redraw is not inhibited in CD version
+			setStateValue(5813, 1);
+			//Bypass additional logo videos in DVD version
+			setStateValue(19810, 1);
+			setStateValue(19848, 1);
+			break;
+		case GID_NEMESIS:
+		// fall through
+		default:
+			break;
+		}
 	}
 	parseScrFile("universe.scr", universe);
 	changeLocation('g', 'a', 'r', 'y', 0);
 	_controlEvents.clear();
-	if(restarted)
-	  _engine->loadSettings();
+	if (restarted)
+		_engine->loadSettings();
 }
 
 void ScriptManager::update(uint deltaTimeMillis) {
@@ -109,7 +110,7 @@ void ScriptManager::update(uint deltaTimeMillis) {
 			ChangeLocationReal(false);
 	}
 	updateNodes(deltaTimeMillis);
-	debug(5,"Script nodes updated");
+	debug(5, "Script nodes updated");
 	if (!execScope(nodeview))
 		return;
 	if (!execScope(room))
@@ -136,8 +137,7 @@ bool ScriptManager::execScope(ScriptScope &scope) {
 			if (!checkPuzzleCriteria(*PuzzleIter, scope.procCount))
 				return false;
 		}
-	} 
-	else {
+	} else {
 		for (PuzzleList::iterator PuzzleIter = scope.execQueue->begin(); PuzzleIter != scope.execQueue->end(); ++PuzzleIter) {
 			if (!checkPuzzleCriteria(*PuzzleIter, scope.procCount))
 				return false;
@@ -179,10 +179,9 @@ void ScriptManager::updateNodes(uint deltaTimeMillis) {
 	// If process() returns true, it means the node can be deleted
 	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end();) {
 		if ((*iter)->process(deltaTimeMillis)) {
-			delete(*iter);  // Remove the node
+			delete (*iter); // Remove the node
 			iter = _activeSideFx.erase(iter);
-		} 
-		else
+		} else
 			++iter;
 	}
 }
@@ -195,22 +194,22 @@ void ScriptManager::updateControls(uint deltaTimeMillis) {
 		Common::Event _event = _controlEvents.front();
 		Common::Point imageCoord;
 		switch (_event.type) {
-		  case Common::EVENT_LBUTTONDOWN:
-			  imageCoord = _engine->getRenderManager()->screenSpaceToImageSpace(_event.mouse);
-			  onMouseDown(_event.mouse, imageCoord);
-			  break;
-		  case Common::EVENT_LBUTTONUP:
-			  imageCoord = _engine->getRenderManager()->screenSpaceToImageSpace(_event.mouse);
-			  onMouseUp(_event.mouse, imageCoord);
-			  break;
-		  case Common::EVENT_KEYDOWN:
-			  onKeyDown(_event.kbd);
-			  break;
-		  case Common::EVENT_KEYUP:
-			  onKeyUp(_event.kbd);
-			  break;
-		  default:
-			  break;
+		case Common::EVENT_LBUTTONDOWN:
+			imageCoord = _engine->getRenderManager()->screenSpaceToImageSpace(_event.mouse);
+			onMouseDown(_event.mouse, imageCoord);
+			break;
+		case Common::EVENT_LBUTTONUP:
+			imageCoord = _engine->getRenderManager()->screenSpaceToImageSpace(_event.mouse);
+			onMouseUp(_event.mouse, imageCoord);
+			break;
+		case Common::EVENT_KEYDOWN:
+			onKeyDown(_event.kbd);
+			break;
+		case Common::EVENT_KEYUP:
+			onKeyUp(_event.kbd);
+			break;
+		default:
+			break;
 		}
 		_controlEvents.pop_front();
 	}
@@ -244,20 +243,20 @@ bool ScriptManager::checkPuzzleCriteria(Puzzle *puzzle, uint counter) {
 				argumentValue = entryIter->argument;
 			// Do the comparison
 			switch (entryIter->criteriaOperator) {
-			  case Puzzle::EQUAL_TO:
-				  criteriaMet = getStateValue(entryIter->key) == argumentValue;
-				  break;
-			  case Puzzle::NOT_EQUAL_TO:
-				  criteriaMet = getStateValue(entryIter->key) != argumentValue;
-				  break;
-			  case Puzzle::GREATER_THAN:
-				  criteriaMet = getStateValue(entryIter->key) > argumentValue;
-				  break;
-			  case Puzzle::LESS_THAN:
-				  criteriaMet = getStateValue(entryIter->key) < argumentValue;
-				  break;
-			  default:
-				  break;
+			case Puzzle::EQUAL_TO:
+				criteriaMet = getStateValue(entryIter->key) == argumentValue;
+				break;
+			case Puzzle::NOT_EQUAL_TO:
+				criteriaMet = getStateValue(entryIter->key) != argumentValue;
+				break;
+			case Puzzle::GREATER_THAN:
+				criteriaMet = getStateValue(entryIter->key) > argumentValue;
+				break;
+			case Puzzle::LESS_THAN:
+				criteriaMet = getStateValue(entryIter->key) < argumentValue;
+				break;
+			default:
+				break;
 			}
 			// If one check returns false, don't keep checking
 			if (!criteriaMet)
@@ -295,10 +294,10 @@ void ScriptManager::cleanScriptScope(ScriptScope &scope) {
 	scope.scopeQueue = &scope.privQueueOne;
 	scope.execQueue = &scope.privQueueTwo;
 	for (PuzzleList::iterator iter = scope.puzzles.begin(); iter != scope.puzzles.end(); ++iter)
-		delete(*iter);
+		delete (*iter);
 	scope.puzzles.clear();
 	for (ControlList::iterator iter = scope.controls.begin(); iter != scope.controls.end(); ++iter)
-		delete(*iter);
+		delete (*iter);
 	scope.controls.clear();
 	scope.procCount = 0;
 }
@@ -306,7 +305,7 @@ void ScriptManager::cleanScriptScope(ScriptScope &scope) {
 int ScriptManager::getStateValue(uint32 key) {
 	if (_globalState.contains(key))
 		return _globalState[key];
-  else
+	else
 		return 0;
 }
 
@@ -407,7 +406,7 @@ ScriptingEffect *ScriptManager::getSideFX(uint32 key) {
 void ScriptManager::deleteSideFx(uint32 key) {
 	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); ++iter) {
 		if ((*iter)->getKey() == key) {
-			delete(*iter);
+			delete (*iter);
 			_activeSideFx.erase(iter);
 			break;
 		}
@@ -419,7 +418,7 @@ void ScriptManager::stopSideFx(uint32 key) {
 		if ((*iter)->getKey() == key) {
 			bool ret = (*iter)->stop();
 			if (ret) {
-				delete(*iter);
+				delete (*iter);
 				_activeSideFx.erase(iter);
 			}
 			break;
@@ -431,7 +430,7 @@ void ScriptManager::killSideFx(uint32 key) {
 	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); ++iter) {
 		if ((*iter)->getKey() == key) {
 			(*iter)->kill();
-			delete(*iter);
+			delete (*iter);
 			_activeSideFx.erase(iter);
 			break;
 		}
@@ -442,16 +441,15 @@ void ScriptManager::killSideFxType(ScriptingEffect::ScriptingEffectType type) {
 	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end();) {
 		if ((*iter)->getType() & type) {
 			(*iter)->kill();
-			delete(*iter);
+			delete (*iter);
 			iter = _activeSideFx.erase(iter);
-		} 
-		else
+		} else
 			++iter;
 	}
 }
 
 void ScriptManager::onMouseDown(const Common::Point &screenSpacePos, const Common::Point &backgroundImageSpacePos) {
-  debug(1,"Mouse panorama/script coordinates %d x %d", backgroundImageSpacePos.x, backgroundImageSpacePos.y);
+	debug(1, "Mouse panorama/script coordinates %d x %d", backgroundImageSpacePos.x, backgroundImageSpacePos.y);
 	if (!_activeControls)
 		return;
 	for (ControlList::iterator iter = _activeControls->reverse_begin(); iter != _activeControls->end(); iter--) {
@@ -498,7 +496,7 @@ void ScriptManager::onKeyUp(Common::KeyState keyState) {
 }
 
 void ScriptManager::changeLocation(const Location &_newLocation) {
-  
+
 	changeLocation(_newLocation.world, _newLocation.room, _newLocation.node, _newLocation.view, _newLocation.offset);
 }
 
@@ -517,8 +515,7 @@ void ScriptManager::changeLocation(char _world, char _room, char _node, char _vi
 			_nextLocation.node = getStateValue(StateKey_LastNode);
 			_nextLocation.view = getStateValue(StateKey_LastView);
 			_nextLocation.offset = getStateValue(StateKey_LastViewPos);
-		} 
-		else {
+		} else {
 			_nextLocation.world = getStateValue(StateKey_Menu_LastWorld);
 			_nextLocation.room = getStateValue(StateKey_Menu_LastRoom);
 			_nextLocation.node = getStateValue(StateKey_Menu_LastNode);
@@ -547,8 +544,7 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 				_nextLocation.view = _currentLocation.view;
 				_nextLocation.offset = _currentLocation.offset;
 				return;
-			} 
-			else {
+			} else {
 				_currentLocation.world = 'g';
 				_currentLocation.room = '0';
 				_currentLocation.node = '0';
@@ -565,8 +561,7 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 			setStateValue(StateKey_LastNode, getStateValue(StateKey_Node));
 			setStateValue(StateKey_LastView, getStateValue(StateKey_View));
 			setStateValue(StateKey_LastViewPos, getStateValue(StateKey_ViewPos));
-		} 
-		else {
+		} else {
 			setStateValue(StateKey_Menu_LastWorld, getStateValue(StateKey_World));
 			setStateValue(StateKey_Menu_LastRoom, getStateValue(StateKey_Room));
 			setStateValue(StateKey_Menu_LastNode, getStateValue(StateKey_Node));
@@ -578,8 +573,7 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 	if (enteringMenu) {
 		if (isSaveScreen && !leavingMenu)
 			_engine->getSaveManager()->prepareSaveBuffer();
-	} 
-	else if (leavingMenu)
+	} else if (leavingMenu)
 		_engine->getSaveManager()->flushSaveBuffer();
 
 	setStateValue(StateKey_World, _nextLocation.world);
@@ -606,8 +600,7 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 		fileName = Common::Path(Common::String::format("%c.scr", _nextLocation.world));
 		parseScrFile(fileName, world);
 		addPuzzlesToReferenceTable(world);
-	} 
-	else if (_nextLocation.room != _currentLocation.room) {
+	} else if (_nextLocation.room != _currentLocation.room) {
 		cleanScriptScope(nodeview);
 		cleanScriptScope(room);
 		addPuzzlesToReferenceTable(world);
@@ -617,8 +610,7 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 		fileName = Common::Path(Common::String::format("%c%c.scr", _nextLocation.world, _nextLocation.room));
 		parseScrFile(fileName, room);
 		addPuzzlesToReferenceTable(room);
-	} 
-	else if (_nextLocation.node != _currentLocation.node || _nextLocation.view != _currentLocation.view) {
+	} else if (_nextLocation.node != _currentLocation.node || _nextLocation.view != _currentLocation.view) {
 		cleanScriptScope(nodeview);
 		addPuzzlesToReferenceTable(room);
 		addPuzzlesToReferenceTable(world);
@@ -670,7 +662,7 @@ void ScriptManager::serialize(Common::WriteStream *stream) {
 	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); ++iter)
 		(*iter)->serialize(stream);
 	stream->writeUint32BE(MKTAG('F', 'L', 'A', 'G'));
-	int32 slots = _engine->getGameId() == GID_NEMESIS ? 31000 : 21000;  
+	int32 slots = _engine->getGameId() == GID_NEMESIS ? 31000 : 21000;
 	//Original games use key values up to 29500 and 19737, respectively
 	//Values 30001~31000 and 20001~21000 are now set aside for auxiliary scripting to add extra directional audio effects.
 	stream->writeUint32LE(slots * 2);
@@ -694,7 +686,7 @@ void ScriptManager::deserialize(Common::SeekableReadStream *stream) {
 	_currentLocation.room = 0;
 	_currentLocation.view = 0;
 	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); iter++)
-		delete(*iter);
+		delete (*iter);
 	_activeSideFx.clear();
 	_referenceTable.clear();
 	if (stream->readUint32BE() != MKTAG('Z', 'N', 'S', 'G') || stream->readUint32LE() != 4) {
@@ -716,27 +708,27 @@ void ScriptManager::deserialize(Common::SeekableReadStream *stream) {
 		uint32 tag = stream->readUint32BE();
 		uint32 tagSize = stream->readUint32LE();
 		switch (tag) {
-		  case MKTAG('T', 'I', 'M', 'R'): {
-			  uint32 key = stream->readUint32LE();
-			  uint32 time = stream->readUint32LE();
-			  if (_engine->getGameId() == GID_GRANDINQUISITOR)
-				  time /= 100;
-			  else if (_engine->getGameId() == GID_NEMESIS)
-				  time /= 1000;
-			  addSideFX(new TimerNode(_engine, key, time));
-			  }
-		    break;
-		  case MKTAG('F', 'L', 'A', 'G'):
-			  for (uint32 i = 0; i < tagSize / 2; i++)
-				  setStateFlagSilent(i, stream->readUint16LE());
-			  break;
-		  case MKTAG('P', 'U', 'Z', 'Z'):
-			  for (uint32 i = 0; i < tagSize / 2; i++)
-				  setStateValueSilent(i, stream->readUint16LE());
-			  break;
-		  default:
-			  stream->seek(tagSize, SEEK_CUR);
-			  break;
+		case MKTAG('T', 'I', 'M', 'R'): {
+			uint32 key = stream->readUint32LE();
+			uint32 time = stream->readUint32LE();
+			if (_engine->getGameId() == GID_GRANDINQUISITOR)
+				time /= 100;
+			else if (_engine->getGameId() == GID_NEMESIS)
+				time /= 1000;
+			addSideFX(new TimerNode(_engine, key, time));
+		}
+		break;
+		case MKTAG('F', 'L', 'A', 'G'):
+			for (uint32 i = 0; i < tagSize / 2; i++)
+				setStateFlagSilent(i, stream->readUint16LE());
+			break;
+		case MKTAG('P', 'U', 'Z', 'Z'):
+			for (uint32 i = 0; i < tagSize / 2; i++)
+				setStateValueSilent(i, stream->readUint16LE());
+			break;
+		default:
+			stream->seek(tagSize, SEEK_CUR);
+			break;
 		}
 	}
 	_nextLocation = nextLocation;
@@ -802,8 +794,7 @@ ValueSlot::ValueSlot(ScriptManager *scriptManager, const char *slotValue):
 	if (isSlot) {
 		slot = true;
 		value = atoi(isSlot + 1);
-	} 
-	else {
+	} else {
 		slot = false;
 		value = atoi(slotValue);
 	}
@@ -814,8 +805,7 @@ int16 ValueSlot::getValue() {
 			return _scriptManager->getStateValue(value);
 		else
 			return 0;
-	}
-	else
+	} else
 		return value;
 }
 
diff --git a/engines/zvision/scripting/script_manager.h b/engines/zvision/scripting/script_manager.h
index 67927b02fbc..15b8bb22dc7 100644
--- a/engines/zvision/scripting/script_manager.h
+++ b/engines/zvision/scripting/script_manager.h
@@ -111,25 +111,25 @@ struct Location {
 	uint32 offset;
 };
 
-inline bool operator==(const Location& lhs, const Location& rhs) {
+inline bool operator==(const Location &lhs, const Location &rhs) {
 	return (
-		lhs.world == rhs.world &&
-		lhs.room == rhs.room &&
-		lhs.node == rhs.node &&
-		lhs.view == rhs.view
-	);
+	           lhs.world == rhs.world &&
+	           lhs.room == rhs.room &&
+	           lhs.node == rhs.node &&
+	           lhs.view == rhs.view
+	       );
 }
 
-inline bool operator==(const Location& lhs, const char* rhs) {
+inline bool operator==(const Location &lhs, const char *rhs) {
 	Common::String lhsStr = Common::String::format("%c%c%c%c", lhs.world, lhs.room, lhs.node, lhs.view);
 	return lhsStr == rhs;
 }
 
-inline bool operator!=(const Location& lhs, const Location& rhs) {
+inline bool operator!=(const Location &lhs, const Location &rhs) {
 	return !(lhs == rhs);
 }
 
-inline bool operator!=(const Location& lhs, const char* rhs) {
+inline bool operator!=(const Location &lhs, const char *rhs) {
 	return !(lhs == rhs);
 }
 
@@ -366,16 +366,16 @@ private:
 	Control *parseControl(Common::String &line, Common::SeekableReadStream &stream);
 };
 
-	/**
-	 * Instances of this polymorphic class function either as a store of a single value, or as a "slot" that returns a StateValue
-	 *
-	 * @param line      The line initially read
-	 * @param slotValue A text string containing a number, which may be enclosed within square braces.
-	 *  If square braces are not present, getValue() will return slotValue.
-   *  If square braces are present, getValue() will return the StateValue to which slotValue is the key.
-   *
-   * Once instantiated, the value and nature of slotValue may not be changed.
-	 */
+/**
+ * Instances of this polymorphic class function either as a store of a single value, or as a "slot" that returns a StateValue
+ *
+ * @param line      The line initially read
+ * @param slotValue A text string containing a number, which may be enclosed within square braces.
+ *  If square braces are not present, getValue() will return slotValue.
+*  If square braces are present, getValue() will return the StateValue to which slotValue is the key.
+*
+* Once instantiated, the value and nature of slotValue may not be changed.
+ */
 class ValueSlot {
 public:
 	ValueSlot(ScriptManager *scriptManager, const char *slotValue);
diff --git a/engines/zvision/sound/midi.cpp b/engines/zvision/sound/midi.cpp
index b2135e4548b..b91f95c28f8 100644
--- a/engines/zvision/sound/midi.cpp
+++ b/engines/zvision/sound/midi.cpp
@@ -31,20 +31,19 @@ namespace ZVision {
 MidiManager::MidiManager() {
 	MidiDriver::DeviceHandle dev = MidiDriver::detectDevice(MDT_MIDI | MDT_ADLIB);  //NB Bug current in MT-32 emulation: MIDI channel 0 does not play anything!
 	_driver = MidiDriver::createMidi(dev);
-  if (_driver->open()) {
-	  warning("Can't open MIDI, no MIDI output!");
-	  available = false;
-	  }
-	else {
-	  Common::String driverName = MidiDriver::getDeviceString(dev,MidiDriver::DeviceStringType::kDriverName);
-	  Common::String deviceName = MidiDriver::getDeviceString(dev,MidiDriver::DeviceStringType::kDeviceName);
-	  mt32workaround = driverName.contains("MT-32");
-    debug(1,"MIDI opened, driver type: %s, device name: %s", driverName.c_str(), deviceName.c_str());
-    if(mt32workaround)
-      debug(1,"Blocking use of MIDI channel 0 to work around bug in MT-32 emulation.");
-	  available = true;
-	  maxChannels = _driver->MIDI_CHANNEL_COUNT;
-  }
+	if (_driver->open()) {
+		warning("Can't open MIDI, no MIDI output!");
+		available = false;
+	} else {
+		Common::String driverName = MidiDriver::getDeviceString(dev, MidiDriver::DeviceStringType::kDriverName);
+		Common::String deviceName = MidiDriver::getDeviceString(dev, MidiDriver::DeviceStringType::kDeviceName);
+		mt32workaround = driverName.contains("MT-32");
+		debug(1, "MIDI opened, driver type: %s, device name: %s", driverName.c_str(), deviceName.c_str());
+		if (mt32workaround)
+			debug(1, "Blocking use of MIDI channel 0 to work around bug in MT-32 emulation.");
+		available = true;
+		maxChannels = _driver->MIDI_CHANNEL_COUNT;
+	}
 }
 
 MidiManager::~MidiManager() {
@@ -54,10 +53,10 @@ MidiManager::~MidiManager() {
 }
 
 void MidiManager::send(uint8 status, uint8 data1, uint8 data2) {
-  assert(status & 0x80 && "Malformed MIDI status byte");
-  assert(!(data1 & 0x80) && "Malformed MIDI data byte 1");
-  assert(!(data2 & 0x80) && "Malformed MIDI data byte 2");
-  _driver->send(status | (data1 << 8) | (data2 << 16) );
+	assert(status & 0x80 && "Malformed MIDI status byte");
+	assert(!(data1 & 0x80) && "Malformed MIDI data byte 1");
+	assert(!(data2 & 0x80) && "Malformed MIDI data byte 2");
+	_driver->send(status | (data1 << 8) | (data2 << 16));
 }
 
 void MidiManager::stop() {
@@ -69,8 +68,8 @@ void MidiManager::noteOn(uint8 channel, uint8 note, uint8 velocity) {
 	assert(channel <= 15);
 	activeChannels[channel].playing = true;
 	activeChannels[channel].note = note;
-  send(0x90 | channel, note, velocity);
-	debug(1,"MIDI note on, channel %d, note %d, velocity %d", channel, note, velocity);
+	send(0x90 | channel, note, velocity);
+	debug(1, "MIDI note on, channel %d, note %d, velocity %d", channel, note, velocity);
 }
 
 void MidiManager::noteOff(uint8 channel) {
@@ -82,7 +81,7 @@ void MidiManager::noteOff(uint8 channel) {
 }
 
 int8 MidiManager::getFreeChannel() {
-  uint8 start = mt32workaround ? 1 : 0; //MT-32 emulator driver currently fails to play anything when sent notes on channel 0.  Quick & dirty fix, since we only need a few notes for Nemesis music puzzles.  Inform maintainer of MT-32 emulator code of bug for proper fix in the future & then remove this nasty hack once that's sorted out.
+	uint8 start = mt32workaround ? 1 : 0; //MT-32 emulator driver currently fails to play anything when sent notes on channel 0.  Quick & dirty fix, since we only need a few notes for Nemesis music puzzles.  Inform maintainer of MT-32 emulator code of bug for proper fix in the future & then remove this nasty hack once that's sorted out.
 	for (uint8 i = start; i < 16; i++)
 		if (!activeChannels[i].playing)
 			return i;
@@ -91,27 +90,27 @@ int8 MidiManager::getFreeChannel() {
 
 void MidiManager::setVolume(uint8 channel, uint8 volume) {
 	assert(channel <= 15);
-	debug(1,"MIDI volume out %d", volume >> 1);
-  send(0xB0 | channel, 0x07, volume >> 1);
+	debug(1, "MIDI volume out %d", volume >> 1);
+	send(0xB0 | channel, 0x07, volume >> 1);
 }
 
 void MidiManager::setBalance(uint8 channel, int8 balance) {
 	assert(channel <= 15);
 	uint8 _balance = (uint8)(balance + 128);
-	debug(1,"MIDI balance out %d", _balance >> 1);
-  send(0xB0 | channel, 0x08, _balance >> 1);
+	debug(1, "MIDI balance out %d", _balance >> 1);
+	send(0xB0 | channel, 0x08, _balance >> 1);
 }
 
 void MidiManager::setPan(uint8 channel, int8 pan) {
 	assert(channel <= 15);
 	uint8 _pan = (uint8)(pan + 128);
-	debug(1,"MIDI pan in %d, out %d", pan, _pan >> 1);
-  send(0xB0 | channel, 0x0A, _pan >> 1);
+	debug(1, "MIDI pan in %d, out %d", pan, _pan >> 1);
+	send(0xB0 | channel, 0x0A, _pan >> 1);
 }
 
 void MidiManager::setProgram(uint8 channel, uint8 prog) {
 	assert(channel <= 15);
-  send(0xC0 | channel, prog);
+	send(0xC0 | channel, prog);
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/sound/midi.h b/engines/zvision/sound/midi.h
index 774a4534dba..43aa8362b17 100644
--- a/engines/zvision/sound/midi.h
+++ b/engines/zvision/sound/midi.h
@@ -41,20 +41,20 @@ public:
 
 	int8 getFreeChannel();  //Negative if none available
 	bool isAvailable() {
-	  return available;
+		return available;
 	};
 
 protected:
-  bool available = false;
-  bool mt32workaround = false;
+	bool available = false;
+	bool mt32workaround = false;
 	struct chan {
 		bool playing;
 		uint8 note;
 		chan() : playing(false), note(0) {};
 	};
-  void send(uint8 status, uint8 data1=0x00, uint8 data2=0x00);
-  uint8 startChannel = 0;
-  uint8 maxChannels = 16;
+	void send(uint8 status, uint8 data1 = 0x00, uint8 data2 = 0x00);
+	uint8 startChannel = 0;
+	uint8 maxChannels = 16;
 	MidiDriver *_driver;
 	chan activeChannels[16];
 };
diff --git a/engines/zvision/sound/volume_manager.cpp b/engines/zvision/sound/volume_manager.cpp
index b28c47798f1..7766dbc3a31 100644
--- a/engines/zvision/sound/volume_manager.cpp
+++ b/engines/zvision/sound/volume_manager.cpp
@@ -27,43 +27,43 @@ namespace ZVision {
 
 //Power law with exponent 1.5.
 static constexpr uint8 powerLaw[256] = {
-    0,  0,  0,  0,  1,  1,  1,  1,  1,  2,  2,  2,  3,  3,  3,  4, 
-    4,  4,  5,  5,  6,  6,  6,  7,  7,  8,  8,  9,  9, 10, 10, 11,
-   11, 12, 12, 13, 14, 14, 15, 15, 16, 16, 17, 18, 18, 19, 20, 20,
-   21, 21, 22, 23, 23, 24, 25, 26, 26, 27, 28, 28, 29, 30, 31, 31,
-   32, 33, 34, 34, 35, 36, 37, 37, 38, 39, 40, 41, 41, 42, 43, 44,
-   45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 53, 54, 55, 56, 57, 58,
-   59, 60, 61, 62, 63, 64, 65, 65, 66, 67, 68, 69, 70, 71, 72, 73,
-   74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 88, 89, 90,
-   91, 92, 93, 94, 95, 96, 97, 98, 99,100,102,103,104,105,106,107,
-  108,109,110,112,113,114,115,116,117,119,120,121,122,123,124,126,
-  127,128,129,130,132,133,134,135,136,138,139,140,141,142,144,145,
-  146,147,149,150,151,152,154,155,156,158,159,160,161,163,164,165,
-  167,168,169,171,172,173,174,176,177,178,180,181,182,184,185,187,
-  188,189,191,192,193,195,196,197,199,200,202,203,204,206,207,209,
-  210,211,213,214,216,217,218,220,221,223,224,226,227,228,230,231,
-  233,234,236,237,239,240,242,243,245,246,248,249,251,252,254,255
-  };
-  
+  0,  0,  0,  0,  1,  1,  1,  1,  1,  2,  2,  2,  3,  3,  3,  4, 
+  4,  4,  5,  5,  6,  6,  6,  7,  7,  8,  8,  9,  9, 10, 10, 11,
+ 11, 12, 12, 13, 14, 14, 15, 15, 16, 16, 17, 18, 18, 19, 20, 20,
+ 21, 21, 22, 23, 23, 24, 25, 26, 26, 27, 28, 28, 29, 30, 31, 31,
+ 32, 33, 34, 34, 35, 36, 37, 37, 38, 39, 40, 41, 41, 42, 43, 44,
+ 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 53, 54, 55, 56, 57, 58,
+ 59, 60, 61, 62, 63, 64, 65, 65, 66, 67, 68, 69, 70, 71, 72, 73,
+ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 88, 89, 90,
+ 91, 92, 93, 94, 95, 96, 97, 98, 99,100,102,103,104,105,106,107,
+108,109,110,112,113,114,115,116,117,119,120,121,122,123,124,126,
+127,128,129,130,132,133,134,135,136,138,139,140,141,142,144,145,
+146,147,149,150,151,152,154,155,156,158,159,160,161,163,164,165,
+167,168,169,171,172,173,174,176,177,178,180,181,182,184,185,187,
+188,189,191,192,193,195,196,197,199,200,202,203,204,206,207,209,
+210,211,213,214,216,217,218,220,221,223,224,226,227,228,230,231,
+233,234,236,237,239,240,242,243,245,246,248,249,251,252,254,255
+};
+
 static constexpr uint8 logPower[256] = {
-    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 
-    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,
-    1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
-    1,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  3,  3,  3,  3,  3,
-    3,  4,  4,  4,  4,  5,  5,  5,  5,  6,  6,  6,  7,  7,  7,  8,
-    8,  9,  9, 10, 10, 11, 11, 12, 13, 13, 14, 15, 16, 17, 18, 19,
-   20, 21, 22, 23, 24, 26, 27, 29, 30, 32, 34, 36, 38, 40, 42, 45,
-   47, 50, 52, 55, 58, 62, 65, 69, 73, 77, 81, 86, 90, 96,101,107,
-  113,119,126,133,140,148,156,165,174,184,194,205,217,229,241,255
-  };
-  
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 
+  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,
+  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
+  1,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  3,  3,  3,  3,  3,
+  3,  4,  4,  4,  4,  5,  5,  5,  5,  6,  6,  6,  7,  7,  7,  8,
+  8,  9,  9, 10, 10, 11, 11, 12, 13, 13, 14, 15, 16, 17, 18, 19,
+ 20, 21, 22, 23, 24, 26, 27, 29, 30, 32, 34, 36, 38, 40, 42, 45,
+ 47, 50, 52, 55, 58, 62, 65, 69, 73, 77, 81, 86, 90, 96,101,107,
+113,119,126,133,140,148,156,165,174,184,194,205,217,229,241,255
+};
+
 //*/
 static constexpr uint8 logAmplitude[256] = {
   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  
@@ -132,59 +132,60 @@ static constexpr uint8 directionalAmplitude[181] = {
 };
 
 VolumeManager::VolumeManager(ZVision *engine, volumeScaling mode) :
-  _engine(engine),
-  _mode(mode) {
+	_engine(engine),
+	_mode(mode) {
 };
-  
+
 uint8 VolumeManager::convert(uint8 inputValue) {
-  return convert(inputValue, _mode);
+	return convert(inputValue, _mode);
 };
-  
+
 uint8 VolumeManager::convert(uint8 inputValue, Math::Angle azimuth, uint8 directionality) {
-  return convert(inputValue, _mode, azimuth, directionality);
+	return convert(inputValue, _mode, azimuth, directionality);
 };
 
 uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode, Math::Angle azimuth, uint8 directionality) {
-  uint8 index = abs(round(azimuth.getDegrees(-180)));
-  uint32 output = convert(inputValue, mode);
-  uint32 directionalOutput = (output * directionalAmplitude[index]) * directionality;
-  directionalOutput /= 255;
-  output *= (255-directionality);
-  output = (output + directionalOutput)/255;
-  debug(4,"Directionally converted output %d", output);
-  return output;
+	uint8 index = abs(round(azimuth.getDegrees(-180)));
+	uint32 output = convert(inputValue, mode);
+	uint32 directionalOutput = (output * directionalAmplitude[index]) * directionality;
+	directionalOutput /= 255;
+	output *= (255 - directionality);
+	output = (output + directionalOutput) / 255;
+	debug(4, "Directionally converted output %d", output);
+	return output;
 };
 
 uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode) {
-  uint16 scaledInput = inputValue * 255;
-  scaledInput /= scriptScale;
-  uint8 output = 0;
-  switch(mode) {
-    case kVolumeLogPower:
-      output = logPower[scaledInput];
-      break;
-    case kVolumeLogAmplitude:
-      output = logAmplitude[scaledInput];
-      break;
-    case kVolumePowerLaw:
-      output = powerLaw[scaledInput];
-      break;
-    case kVolumeParabolic:
-      output = pow(scaledInput,2)/255;
-      break;
-    case kVolumeCubic:
-      output = pow(scaledInput,3)/pow(255,2);
-      break;
-    case kVolumeQuartic:
-      output = pow(scaledInput,4)/pow(255,3);
-      break;
-    case kVolumeLinear:
-    default:
-      output = scaledInput;
-      break;
-  }
-  debug(4,"Scripted volume %d, scaled volume %d, converted output %d", inputValue, scaledInput, output);
-  return output;
+	uint16 scaledInput = inputValue * 255;
+	scaledInput /= scriptScale;
+	uint8 output = 0;
+	switch (mode) {
+	case kVolumeLogPower:
+		output = logPower[scaledInput];
+		break;
+	case kVolumeLogAmplitude:
+		output = logAmplitude[scaledInput];
+		break;
+	case kVolumePowerLaw:
+		output = powerLaw[scaledInput];
+		break;
+	case kVolumeParabolic:
+		output = pow(scaledInput, 2) / 255;
+		break;
+	case kVolumeCubic:
+		output = pow(scaledInput, 3) / pow(255, 2);
+		break;
+	case kVolumeQuartic:
+		output = pow(scaledInput, 4) / pow(255, 3);
+		break;
+	case kVolumeLinear:
+	// fall through
+	default:
+		output = scaledInput;
+		break;
+	}
+	debug(4, "Scripted volume %d, scaled volume %d, converted output %d", inputValue, scaledInput, output);
+	return output;
 };
 
 } // End of namespace ZVision
diff --git a/engines/zvision/sound/volume_manager.h b/engines/zvision/sound/volume_manager.h
index 4bdd784aafb..6624a565552 100644
--- a/engines/zvision/sound/volume_manager.h
+++ b/engines/zvision/sound/volume_manager.h
@@ -29,29 +29,33 @@
 namespace ZVision {
 
 enum volumeScaling {
-  kVolumeLinear,
-  kVolumePowerLaw,
-  kVolumeParabolic,
-  kVolumeCubic,
-  kVolumeQuartic,
-  kVolumeLogPower,
-  kVolumeLogAmplitude
+	kVolumeLinear,
+	kVolumePowerLaw,
+	kVolumeParabolic,
+	kVolumeCubic,
+	kVolumeQuartic,
+	kVolumeLogPower,
+	kVolumeLogAmplitude
 };
 
 class VolumeManager {
 public:
-  VolumeManager(ZVision *engine, volumeScaling mode);
-  ~VolumeManager() {};
-  volumeScaling getMode() {return _mode;};
-  void setMode(volumeScaling mode) {_mode = mode;};
-  uint8 convert(uint8 inputValue);
-  uint8 convert(uint8 inputValue, volumeScaling mode);
-  uint8 convert(uint8 inputValue, Math::Angle azimuth, uint8 directionality=255);
-  uint8 convert(uint8 inputValue, volumeScaling mode, Math::Angle azimuth, uint8 directionality=255);
+	VolumeManager(ZVision *engine, volumeScaling mode);
+	~VolumeManager() {};
+	volumeScaling getMode() {
+		return _mode;
+	};
+	void setMode(volumeScaling mode) {
+		_mode = mode;
+	};
+	uint8 convert(uint8 inputValue);
+	uint8 convert(uint8 inputValue, volumeScaling mode);
+	uint8 convert(uint8 inputValue, Math::Angle azimuth, uint8 directionality = 255);
+	uint8 convert(uint8 inputValue, volumeScaling mode, Math::Angle azimuth, uint8 directionality = 255);
 private:
 	ZVision *_engine;
-  uint scriptScale = 100; //Z-Vision scripts internally use a volume scale of 0-100; ScummVM uses a scale of 0-255.
-  volumeScaling _mode = kVolumeLinear;
+	uint scriptScale = 100; //Z-Vision scripts internally use a volume scale of 0-100; ScummVM uses a scale of 0-255.
+	volumeScaling _mode = kVolumeLinear;
 };
 
 } // End of namespace ZVision
diff --git a/engines/zvision/sound/zork_raw.cpp b/engines/zvision/sound/zork_raw.cpp
index ba33d9898f5..60016d6ee23 100644
--- a/engines/zvision/sound/zork_raw.cpp
+++ b/engines/zvision/sound/zork_raw.cpp
@@ -37,18 +37,19 @@ namespace ZVision {
 
 const int16 RawChunkStream::_stepAdjustmentTable[8] = { -1, -1, -1, 1, 4, 7, 10, 12};
 
-const int32 RawChunkStream::_amplitudeLookupTable[89] = {0x0007, 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E,
-														 0x0010, 0x0011, 0x0013, 0x0015, 0x0017, 0x0019, 0x001C, 0x001F,
-														 0x0022, 0x0025, 0x0029, 0x002D, 0x0032, 0x0037, 0x003C, 0x0042,
-														 0x0049, 0x0050, 0x0058, 0x0061, 0x006B, 0x0076, 0x0082, 0x008F,
-														 0x009D, 0x00AD, 0x00BE, 0x00D1, 0x00E6, 0x00FD, 0x0117, 0x0133,
-														 0x0151, 0x0173, 0x0198, 0x01C1, 0x01EE, 0x0220, 0x0256, 0x0292,
-														 0x02D4, 0x031C, 0x036C, 0x03C3, 0x0424, 0x048E, 0x0502, 0x0583,
-														 0x0610, 0x06AB, 0x0756, 0x0812, 0x08E0, 0x09C3, 0x0ABD, 0x0BD0,
-														 0x0CFF, 0x0E4C, 0x0FBA, 0x114C, 0x1307, 0x14EE, 0x1706, 0x1954,
-														 0x1BDC, 0x1EA5, 0x21B6, 0x2515, 0x28CA, 0x2CDF, 0x315B, 0x364B,
-														 0x3BB9, 0x41B2, 0x4844, 0x4F7E, 0x5771, 0x602F, 0x69CE, 0x7462, 0x7FFF
-														};
+const int32 RawChunkStream::_amplitudeLookupTable[89] = {
+	0x0007, 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E,
+	0x0010, 0x0011, 0x0013, 0x0015, 0x0017, 0x0019, 0x001C, 0x001F,
+	0x0022, 0x0025, 0x0029, 0x002D, 0x0032, 0x0037, 0x003C, 0x0042,
+	0x0049, 0x0050, 0x0058, 0x0061, 0x006B, 0x0076, 0x0082, 0x008F,
+	0x009D, 0x00AD, 0x00BE, 0x00D1, 0x00E6, 0x00FD, 0x0117, 0x0133,
+	0x0151, 0x0173, 0x0198, 0x01C1, 0x01EE, 0x0220, 0x0256, 0x0292,
+	0x02D4, 0x031C, 0x036C, 0x03C3, 0x0424, 0x048E, 0x0502, 0x0583,
+	0x0610, 0x06AB, 0x0756, 0x0812, 0x08E0, 0x09C3, 0x0ABD, 0x0BD0,
+	0x0CFF, 0x0E4C, 0x0FBA, 0x114C, 0x1307, 0x14EE, 0x1706, 0x1954,
+	0x1BDC, 0x1EA5, 0x21B6, 0x2515, 0x28CA, 0x2CDF, 0x315B, 0x364B,
+	0x3BB9, 0x41B2, 0x4844, 0x4F7E, 0x5771, 0x602F, 0x69CE, 0x7462, 0x7FFF
+};
 
 RawChunkStream::RawChunkStream(bool stereo) {
 	if (stereo)
@@ -231,9 +232,9 @@ bool RawZorkStream::rewind() {
 }
 
 Audio::RewindableAudioStream *makeRawZorkStream(Common::SeekableReadStream *stream,
-		int rate,
-		bool stereo,
-		DisposeAfterUse::Flag disposeAfterUse) {
+        int rate,
+        bool stereo,
+        DisposeAfterUse::Flag disposeAfterUse) {
 	if (stereo)
 		assert(stream->size() % 2 == 0);
 
diff --git a/engines/zvision/sound/zork_raw.h b/engines/zvision/sound/zork_raw.h
index 257896a542f..47803188e2e 100644
--- a/engines/zvision/sound/zork_raw.h
+++ b/engines/zvision/sound/zork_raw.h
@@ -130,9 +130,9 @@ public:
  * @return           The new SeekableAudioStream (or 0 on failure).
  */
 Audio::RewindableAudioStream *makeRawZorkStream(Common::SeekableReadStream *stream,
-		int rate,
-		bool stereo,
-		DisposeAfterUse::Flag disposeAfterUse = DisposeAfterUse::YES);
+        int rate,
+        bool stereo,
+        DisposeAfterUse::Flag disposeAfterUse = DisposeAfterUse::YES);
 
 Audio::RewindableAudioStream *makeRawZorkStream(const Common::Path &filePath, ZVision *engine);
 
diff --git a/engines/zvision/text/subtitle_manager.cpp b/engines/zvision/text/subtitle_manager.cpp
index 25fe86344f0..d48f196d717 100644
--- a/engines/zvision/text/subtitle_manager.cpp
+++ b/engines/zvision/text/subtitle_manager.cpp
@@ -29,128 +29,127 @@
 namespace ZVision {
 
 SubtitleManager::SubtitleManager(ZVision *engine, const ScreenLayout layout, const Graphics::PixelFormat pixelFormat, bool doubleFPS) :
-  _engine(engine),
-  _system(engine->_system),
-  _renderManager(engine->getRenderManager()),
+	_engine(engine),
+	_system(engine->_system),
+	_renderManager(engine->getRenderManager()),
 	_pixelFormat(pixelFormat),
-  _textOffset( layout.workingArea.origin() - layout.textArea.origin() ),
-  _textArea( layout.textArea.width(), layout.textArea.height() ),
-  redraw(false),
+	_textOffset(layout.workingArea.origin() - layout.textArea.origin()),
+	_textArea(layout.textArea.width(), layout.textArea.height()),
+	redraw(false),
 	_doubleFPS(doubleFPS),
-  _subId(0)
-  {
+	_subId(0) {
 }
 
 SubtitleManager::~SubtitleManager() {
-  //Delete all subtitles referenced in subslist
-  for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
-    delete it->_value;
+	//Delete all subtitles referenced in subslist
+	for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
+		delete it->_value;
 		_subsList.erase(it);
 		_subsFocus.clear();
-  }
+	}
 }
 
 void SubtitleManager::process(int32 deltatime) {
-  for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
-    //Update all automatic subtitles
-    if (it->_value->selfUpdate())
-      redraw = true;
-  	//Update all subtitles' respective deletion timers
+	for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
+		//Update all automatic subtitles
+		if (it->_value->selfUpdate())
+			redraw = true;
+		//Update all subtitles' respective deletion timers
 		if (it->_value->process(deltatime)) {
-      debug(4,"Deleting subtitle, subId=%d", it->_key);
-			_subsFocus.remove(it->_key);			
-		  delete it->_value;
+			debug(4, "Deleting subtitle, subId=%d", it->_key);
+			_subsFocus.remove(it->_key);
+			delete it->_value;
 			_subsList.erase(it);
 			redraw = true;
-	  }
-  }
-	if(_subsList.size() == 0)
-	  if(_subId != 0) {
-      debug(4,"Resetting subId to 0");
-	    _subId = 0;
-      _subsFocus.clear();
-    }
+		}
+	}
+	if (_subsList.size() == 0)
+		if (_subId != 0) {
+			debug(4, "Resetting subId to 0");
+			_subId = 0;
+			_subsFocus.clear();
+		}
 	if (redraw) {
-    debug(4,"Redrawing subtitles");
-	  //Blank subtitle buffer
-	  _renderManager->clearTextSurface();
-    //Render just the most recent subtitle
-  	if(_subsFocus.size()) {
-  	  uint16 curSub = _subsFocus.get();
-      debug(4,"Rendering subtitle %d", curSub);     
-      Subtitle *sub = _subsList[curSub];
-		  if (sub->lineId >= 0) { 
-			  Graphics::Surface textSurface;
-			  textSurface.create(sub->r.width(), sub->r.height(), _engine->_resourcePixelFormat);
-			  textSurface.fillRect(Common::Rect(sub->r.width(), sub->r.height()), -1); //TODO Unnecessary operation?  Check later.
-			  _engine->getTextRenderer()->drawTextWithWordWrapping(sub->_lines[sub->lineId].subStr, textSurface, _engine->isWidescreen());
-			  _renderManager->blitSurfaceToText(textSurface, sub->r.left, sub->r.top, -1);
-			  textSurface.free();
-			  sub->redraw = false;
-		  }
-	  }
-	redraw = false;
+		debug(4, "Redrawing subtitles");
+		//Blank subtitle buffer
+		_renderManager->clearTextSurface();
+		//Render just the most recent subtitle
+		if (_subsFocus.size()) {
+			uint16 curSub = _subsFocus.get();
+			debug(4, "Rendering subtitle %d", curSub);
+			Subtitle *sub = _subsList[curSub];
+			if (sub->lineId >= 0) {
+				Graphics::Surface textSurface;
+				textSurface.create(sub->r.width(), sub->r.height(), _engine->_resourcePixelFormat);
+				textSurface.fillRect(Common::Rect(sub->r.width(), sub->r.height()), -1); //TODO Unnecessary operation?  Check later.
+				_engine->getTextRenderer()->drawTextWithWordWrapping(sub->_lines[sub->lineId].subStr, textSurface, _engine->isWidescreen());
+				_renderManager->blitSurfaceToText(textSurface, sub->r.left, sub->r.top, -1);
+				textSurface.free();
+				sub->redraw = false;
+			}
+		}
+		redraw = false;
 	}
 }
 
 void SubtitleManager::update(int32 count, uint16 subid) {
 	if (_subsList.contains(subid))
-    if( _subsList[subid]->update(count) ) {
-      //_subsFocus.set(subid);
-      redraw = true;
-    }
+		if (_subsList[subid]->update(count)) {
+			//_subsFocus.set(subid);
+			redraw = true;
+		}
 }
 
 uint16 SubtitleManager::create(const Common::Path &subname, bool vob) {
-  _subId++;
-  debug(2,"Creating scripted subtitle, subId=%d", _subId);
-  _subsList[_subId] = new Subtitle(_engine, subname, vob);
-  _subsFocus.set(_subId);
-  return _subId;
+	_subId++;
+	debug(2, "Creating scripted subtitle, subId=%d", _subId);
+	_subsList[_subId] = new Subtitle(_engine, subname, vob);
+	_subsFocus.set(_subId);
+	return _subId;
 }
 
 uint16 SubtitleManager::create(const Common::Path &subname, Audio::SoundHandle handle) {
-  _subId++;
-  debug(2,"Creating scripted subtitle, subId=%d", _subId);
-  _subsList[_subId] = new AutomaticSubtitle(_engine, subname, handle);
-  _subsFocus.set(_subId);
-  return _subId;
+	_subId++;
+	debug(2, "Creating scripted subtitle, subId=%d", _subId);
+	_subsList[_subId] = new AutomaticSubtitle(_engine, subname, handle);
+	_subsFocus.set(_subId);
+	return _subId;
 }
 
 uint16 SubtitleManager::create(const Common::String &str) {
-  _subId++;
-  debug(2,"Creating simple subtitle, subId=%d, message %s", _subId, str.c_str());
-  _subsList[_subId] = new Subtitle(_engine, str, _textArea);
-  _subsFocus.set(_subId);
-  return _subId;
+	_subId++;
+	debug(2, "Creating simple subtitle, subId=%d, message %s", _subId, str.c_str());
+	_subsList[_subId] = new Subtitle(_engine, str, _textArea);
+	_subsFocus.set(_subId);
+	return _subId;
 }
 
 void SubtitleManager::destroy(uint16 id) {
 	if (_subsList.contains(id)) {
-    debug(2,"Marking subtitle %d for immediate deletion", id);
+		debug(2, "Marking subtitle %d for immediate deletion", id);
 		_subsList[id]->todelete = true;
-		}
+	}
 }
 
 void SubtitleManager::destroy(uint16 id, int16 delay) {
 	if (_subsList.contains(id)) {
-    debug(2,"Marking subtitle %d for deletion in %dms", id, delay);	  
+		debug(2, "Marking subtitle %d for deletion in %dms", id, delay);
 		_subsList[id]->timer = delay;
-		}
+	}
 }
 
 void SubtitleManager::timedMessage(const Common::String &str, uint16 milsecs) {
 	uint16 msgid = create(str);
-  debug(1,"initiating timed message: %s to subtitle id %d, time %d", str.c_str(), msgid, milsecs);
-	update(0,msgid);
+	debug(1, "initiating timed message: %s to subtitle id %d, time %d", str.c_str(), msgid, milsecs);
+	update(0, msgid);
 	process(0);
 	destroy(msgid, milsecs);
 }
 
 bool SubtitleManager::askQuestion(const Common::String &str) {
 	uint16 msgid = create(str);
-  debug(1,"initiating user question: %s to subtitle id %d", str.c_str(), msgid);
-	update(0,msgid);
+	debug(1, "initiating user question: %s to subtitle id %d", str.c_str(), msgid);
+	update(0, msgid);
 	process(0);
 	_renderManager->renderSceneToScreen(true);
 	_engine->stopClock();
@@ -196,7 +195,7 @@ bool SubtitleManager::askQuestion(const Common::String &str) {
 				}
 			}
 		}
-	  _renderManager->renderSceneToScreen(true); 
+		_renderManager->renderSceneToScreen(true);
 		if (_doubleFPS)
 			_system->delayMillis(33);
 		else
@@ -209,8 +208,8 @@ bool SubtitleManager::askQuestion(const Common::String &str) {
 
 void SubtitleManager::delayedMessage(const Common::String &str, uint16 milsecs) {
 	uint16 msgid = create(str);
-  debug(1,"initiating delayed message: %s to subtitle id %d, delay %dms", str.c_str(), msgid, milsecs);
-	update(0,msgid);
+	debug(1, "initiating delayed message: %s to subtitle id %d, delay %dms", str.c_str(), msgid, milsecs);
+	update(0, msgid);
 	process(0);
 	_renderManager->renderSceneToScreen(true);
 	_engine->stopClock();
@@ -225,7 +224,7 @@ void SubtitleManager::delayedMessage(const Common::String &str, uint16 milsecs)
 			         evnt.kbd.keycode == Common::KEYCODE_ESCAPE))
 				break;
 		}
-	  _renderManager->renderSceneToScreen(true);
+		_renderManager->renderSceneToScreen(true);
 		if (_doubleFPS)
 			_system->delayMillis(17);
 		else
@@ -237,41 +236,39 @@ void SubtitleManager::delayedMessage(const Common::String &str, uint16 milsecs)
 
 void SubtitleManager::showDebugMsg(const Common::String &msg, int16 delay) {
 	uint16 msgid = create(msg);
-  debug(1,"initiating in-game debug message: %s to subtitle id %d, delay %dms", msg.c_str(), msgid, delay);
-	update(0,msgid);
+	debug(1, "initiating in-game debug message: %s to subtitle id %d, delay %dms", msg.c_str(), msgid, delay);
+	update(0, msgid);
 	process(0);
 	destroy(msgid, delay);
 }
 
 Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool vob) :
-  _engine(engine),
+	_engine(engine),
 	lineId(-1),
 	timer(-1),
 	todelete(false),
 	redraw(false) {
 	Common::File subFile;
-  Common::Point _textOffset = _engine->getSubtitleManager()->getTextOffset();
+	Common::Point _textOffset = _engine->getSubtitleManager()->getTextOffset();
 	if (_engine->getSearchManager()->openFile(subFile, subname)) {
-	  //Parse subtitle parameters from script
+		//Parse subtitle parameters from script
 		while (!subFile.eos()) {
 			Common::String str = subFile.readLine();
 			if (str.lastChar() == '~')
 				str.deleteLastChar();
 			if (str.matchString("*Initialization*", true)) {
 				// Not used
-			} 
-			else if (str.matchString("*Rectangle*", true)) {
+			} else if (str.matchString("*Rectangle*", true)) {
 				int32 x1, y1, x2, y2;
 				sscanf(str.c_str(), "%*[^:]:%d %d %d %d", &x1, &y1, &x2, &y2);
 				r = Common::Rect(x1, y1, x2, y2);
-				debug(1,"Original subtitle script rectangle coordinates: l%d, t%d, r%d, b%d", x1, y1, x2, y2);				
-	      //Original game subtitle scripts appear to define subtitle rectangles relative to origin of working area.
-	      //To allow arbitrary aspect ratios, we need to instead place these relative to origin of text area.
-	      //This will allow the managed text area to then be arbitrarily placed on the screen to suit different aspect ratios.
-	      r.translate(_textOffset.x, _textOffset.y);  //Convert working area coordinates to text area coordinates
-				debug(1,"Text area coordinates: l%d, t%d, r%d, b%d", r.left, r.top, r.right, r.bottom);	
-			} 
-			else if (str.matchString("*TextFile*", true)) {
+				debug(1, "Original subtitle script rectangle coordinates: l%d, t%d, r%d, b%d", x1, y1, x2, y2);
+				//Original game subtitle scripts appear to define subtitle rectangles relative to origin of working area.
+				//To allow arbitrary aspect ratios, we need to instead place these relative to origin of text area.
+				//This will allow the managed text area to then be arbitrarily placed on the screen to suit different aspect ratios.
+				r.translate(_textOffset.x, _textOffset.y);  //Convert working area coordinates to text area coordinates
+				debug(1, "Text area coordinates: l%d, t%d, r%d, b%d", r.left, r.top, r.right, r.bottom);
+			} else if (str.matchString("*TextFile*", true)) {
 				char filename[64];
 				sscanf(str.c_str(), "%*[^:]:%s", filename);
 				Common::File txtFile;
@@ -286,8 +283,7 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool vob) :
 					}
 					txtFile.close();
 				}
-			} 
-			else {
+			} else {
 				int32 st; //Line start time
 				int32 en; //Line end time
 				int32 sb; //Line number
@@ -306,22 +302,21 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool vob) :
 				}
 			}
 		}
-    subFile.close();
-  }
-  else {
-    //TODO - add error message here
-    todelete = true;
-  }
+		subFile.close();
+	} else {
+		//TODO - add error message here
+		todelete = true;
+	}
 }
 
 Subtitle::Subtitle(ZVision *engine, const Common::String &str, const Common::Rect &textArea) :
-  _engine(engine),
+	_engine(engine),
 	lineId(-1),
 	timer(-1),
 	todelete(false),
 	redraw(false) {
 	r = textArea;
-	debug(1,"Text area coordinates: l%d, t%d, r%d, b%d", r.left, r.top, r.right, r.bottom);	
+	debug(1, "Text area coordinates: l%d, t%d, r%d, b%d", r.left, r.top, r.right, r.bottom);
 	line curLine;
 	curLine.start = -1;
 	curLine.stop = 0;
@@ -343,50 +338,49 @@ bool Subtitle::process(int32 deltatime) {
 }
 
 bool Subtitle::update(int32 count) {
-  int16 j = -1;
-  //Search all lines to find first line that encompasses current time/framecount, set j to this
-  for (uint16 i = (lineId >= 0 ? lineId : 0); i < _lines.size(); i++)
-	  if (count >= _lines[i].start && count <= _lines[i].stop) {
-		  j = i;
-		  break;
-	  }
-  if (j == -1) {
-    //No line exists for current time/framecount
-    if(lineId != -1) {
-      //Line is set
-	    lineId = -1; //Unset line
-	    redraw = true;
-    }
-  }
-  else {
-    //Line exists for current time/framecount
-    if (j != lineId && _lines[j].subStr.size()) {
-      //Set line is not equal to current line & current line is not blank
-      lineId = j;  //Set line to current
-      redraw = true;
-    }
-  }
-  return redraw;
+	int16 j = -1;
+	//Search all lines to find first line that encompasses current time/framecount, set j to this
+	for (uint16 i = (lineId >= 0 ? lineId : 0); i < _lines.size(); i++)
+		if (count >= _lines[i].start && count <= _lines[i].stop) {
+			j = i;
+			break;
+		}
+	if (j == -1) {
+		//No line exists for current time/framecount
+		if (lineId != -1) {
+			//Line is set
+			lineId = -1; //Unset line
+			redraw = true;
+		}
+	} else {
+		//Line exists for current time/framecount
+		if (j != lineId && _lines[j].subStr.size()) {
+			//Set line is not equal to current line & current line is not blank
+			lineId = j;  //Set line to current
+			redraw = true;
+		}
+	}
+	return redraw;
 }
 
 AutomaticSubtitle::AutomaticSubtitle(ZVision *engine, const Common::Path &subname, Audio::SoundHandle handle) :
-  Subtitle(engine, subname, false),
-  _handle(handle) {
+	Subtitle(engine, subname, false),
+	_handle(handle) {
 }
 
 bool AutomaticSubtitle::selfUpdate() {
 	if (_engine->_mixer->isSoundHandleActive(_handle) && _engine->getScriptManager()->getStateValue(StateKey_Subtitles) == 1)
-    return update(_engine->_mixer->getSoundElapsedTime(_handle) / 100);
-  else {
-    todelete = true;
-    return false;
-  }
+		return update(_engine->_mixer->getSoundElapsedTime(_handle) / 100);
+	else {
+		todelete = true;
+		return false;
+	}
 }
 
 bool AutomaticSubtitle::process(int32 deltatime) {
-  Subtitle::process(deltatime);
-	if(!_engine->_mixer->isSoundHandleActive(_handle))
-	  todelete = true;
+	Subtitle::process(deltatime);
+	if (!_engine->_mixer->isSoundHandleActive(_handle))
+		todelete = true;
 	return todelete;
 }
 
diff --git a/engines/zvision/text/subtitle_manager.h b/engines/zvision/text/subtitle_manager.h
index 274119c5d6d..e1b3f1a753e 100644
--- a/engines/zvision/text/subtitle_manager.h
+++ b/engines/zvision/text/subtitle_manager.h
@@ -31,23 +31,25 @@ namespace ZVision {
 class ZVision;
 
 class Subtitle {
-friend class SubtitleManager;
+	friend class SubtitleManager;
 public:
-  Subtitle(ZVision *engine, const Common::Path &subname, bool vob=false);  //For scripted subtitles
-  Subtitle(ZVision *engine, const Common::String &str, const Common::Rect &textArea);  //For other text messages
-  virtual ~Subtitle();
-  bool update(int32 count); //Return true if necessary to redraw
-  virtual bool selfUpdate() {return false;};
+	Subtitle(ZVision *engine, const Common::Path &subname, bool vob = false); //For scripted subtitles
+	Subtitle(ZVision *engine, const Common::String &str, const Common::Rect &textArea);  //For other text messages
+	virtual ~Subtitle();
+	bool update(int32 count); //Return true if necessary to redraw
+	virtual bool selfUpdate() {
+		return false;
+	};
 
 protected:
-  virtual bool process(int32 deltatime);  //Return true if to be deleted
+	virtual bool process(int32 deltatime);  //Return true if to be deleted
 	ZVision *_engine;
 	Common::Rect r;
 	Common::String txt;
 	int16  timer; //Always in milliseconds; countdown to deletion
 	bool todelete;
 	bool redraw;
-	
+
 	int16 lineId;
 	struct line {
 		int start;
@@ -57,27 +59,27 @@ protected:
 	//NB: start & stop do not always use the same units between different instances of this struct!
 	//Sound effect & music subtitles use milliseconds
 	//Video subtitle timings are specified in video frames at 15fps, i.e. in multiples of 66.6' milliseconds!
-    //AVI videos run at 15fps and can have frames counted directly
-    //DVD videos in VOB format run at 29.97 fps and must be converted to work with the subtitle files, which were made for AVI.
-	
+	//AVI videos run at 15fps and can have frames counted directly
+	//DVD videos in VOB format run at 29.97 fps and must be converted to work with the subtitle files, which were made for AVI.
+
 	Common::Array<line> _lines;
 };
 
 class AutomaticSubtitle : public Subtitle {
 public:
-  AutomaticSubtitle(ZVision *engine, const Common::Path &subname, Audio::SoundHandle handle);  //For scripted audio subtitles
-  ~AutomaticSubtitle() {};
-  
+	AutomaticSubtitle(ZVision *engine, const Common::Path &subname, Audio::SoundHandle handle);  //For scripted audio subtitles
+	~AutomaticSubtitle() {};
+
 private:
-  bool process(int32 deltatime);  //Return true if to be deleted
-  bool selfUpdate(); //Return true if necessary to redraw
-  Audio::SoundHandle _handle;
+	bool process(int32 deltatime);  //Return true if to be deleted
+	bool selfUpdate(); //Return true if necessary to redraw
+	Audio::SoundHandle _handle;
 };
 
 class SubtitleManager {
 public:
-  SubtitleManager(ZVision *engine, const ScreenLayout layout, const Graphics::PixelFormat pixelFormat, bool doubleFPS);
-  ~SubtitleManager();  
+	SubtitleManager(ZVision *engine, const ScreenLayout layout, const Graphics::PixelFormat pixelFormat, bool doubleFPS);
+	~SubtitleManager();
 private:
 	ZVision *_engine;
 	OSystem *_system;
@@ -90,30 +92,32 @@ private:
 	// Internal subtitle ID counter
 	uint16 _subId;
 
-	typedef Common::HashMap<uint16, Subtitle*> SubtitleMap;
+	typedef Common::HashMap<uint16, Subtitle *> SubtitleMap;
 
 	// Subtitle list
 	SubtitleMap _subsList;
 	// Subtitle focus history
-  FocusList<uint16> _subsFocus;
-  
+	FocusList<uint16> _subsFocus;
+
 public:
-  //Update all subtitle objects' deletion timers, delete expired subtitles, & redraw most recent.  Does NOT update any subtitle's count value or displayed string!
-  void process(int32 deltatime);  //deltatime is always milliseconds
-  //Update counter value of referenced subtitle id & set current line to display, if any.
+	//Update all subtitle objects' deletion timers, delete expired subtitles, & redraw most recent.  Does NOT update any subtitle's count value or displayed string!
+	void process(int32 deltatime);  //deltatime is always milliseconds
+	//Update counter value of referenced subtitle id & set current line to display, if any.
 	void update(int32 count, uint16 subid);  //Count is milliseconds for sound & music; frames for video playback.
-	
-  Common::Point getTextOffset() {return _textOffset;}
-	
+
+	Common::Point getTextOffset() {
+		return _textOffset;
+	}
+
 	// Create subtitle object and return ID
 	uint16 create(const Common::Path &subname, bool vob = false);
-	uint16 create(const Common::Path &subname, Audio::SoundHandle handle);	//NB this creates an automatic subtitle
+	uint16 create(const Common::Path &subname, Audio::SoundHandle handle);  //NB this creates an automatic subtitle
 	uint16 create(const Common::String &str);
-	
+
 	// Delete subtitle object by ID
 	void destroy(uint16 id);
 	void destroy(uint16 id, int16 delay);
-	
+
 	bool askQuestion(const Common::String &str);
 	void delayedMessage(const Common::String &str, uint16 milsecs);
 	void timedMessage(const Common::String &str, uint16 milsecs);
diff --git a/engines/zvision/text/text.cpp b/engines/zvision/text/text.cpp
index de438fd530e..f515e37b70f 100644
--- a/engines/zvision/text/text.cpp
+++ b/engines/zvision/text/text.cpp
@@ -42,16 +42,16 @@ TextStyleState::TextStyleState() {
 	_green = 255;
 	_red = 255;
 	_bold = false;
-#if 0
+	#if 0
 	_newline = false;
 	_escapement = 0;
-#endif
+	#endif
 	_italic = false;
 	_justification = TEXT_JUSTIFY_LEFT;
 	_size = 12;
-#if 0
+	#if 0
 	_skipcolor = false;
-#endif
+	#endif
 	_strikeout = false;
 	_underline = false;
 	_statebox = 0;
@@ -117,12 +117,12 @@ TextChange TextStyleState::parseStyle(const Common::String &str, int16 len) {
 				}
 			}
 		} else if (token.matchString("newline", true)) {
-#if 0
+			#if 0
 			if ((retval & TXT_RET_NEWLN) == 0)
 				_newline = 0;
 
 			_newline++;
-#endif
+			#endif
 			retval |= TEXT_CHANGE_NEWLINE;
 		} else if (token.matchString("point", true)) {
 			if (!tokenizer.empty()) {
@@ -136,10 +136,10 @@ TextChange TextStyleState::parseStyle(const Common::String &str, int16 len) {
 		} else if (token.matchString("escapement", true)) {
 			if (!tokenizer.empty()) {
 				token = tokenizer.nextToken();
-#if 0
+				#if 0
 				int32 tmp = atoi(token.c_str());
 				_escapement = tmp;
-#endif
+				#endif
 			}
 		} else if (token.matchString("italic", true)) {
 			if (!tokenizer.empty()) {
@@ -204,13 +204,13 @@ TextChange TextStyleState::parseStyle(const Common::String &str, int16 len) {
 		} else if (token.matchString("skipcolor", true)) {
 			if (!tokenizer.empty()) {
 				token = tokenizer.nextToken();
-#if 0
+				#if 0
 				if (token.matchString("on", true)) {
 					_skipcolor = true;
 				} else if (token.matchString("off", true)) {
 					_skipcolor = false;
 				}
-#endif
+				#endif
 			}
 		} else if (token.matchString("image", true)) {
 			// Not used
@@ -273,16 +273,16 @@ void TextStyleState::updateFontWithTextState(StyledTTFont &font) {
 }
 
 void TextRenderer::drawTextWithJustification(const Common::String &text, StyledTTFont &font, uint32 color, Graphics::Surface &dest, int lineY, TextJustification justify) {
-  switch(justify) {
-  case TEXT_JUSTIFY_LEFT :
-	  font.drawString(&dest, text, 0, lineY, dest.w, color, Graphics::kTextAlignLeft);
-	  break;
-  case TEXT_JUSTIFY_CENTER :
-	  font.drawString(&dest, text, 0, lineY, dest.w, color, Graphics::kTextAlignCenter);
-	  break;
-  case TEXT_JUSTIFY_RIGHT :
-	  font.drawString(&dest, text, 0, lineY, dest.w, color, Graphics::kTextAlignRight);
-    break;
+	switch (justify) {
+	case TEXT_JUSTIFY_LEFT :
+		font.drawString(&dest, text, 0, lineY, dest.w, color, Graphics::kTextAlignLeft);
+		break;
+	case TEXT_JUSTIFY_CENTER :
+		font.drawString(&dest, text, 0, lineY, dest.w, color, Graphics::kTextAlignCenter);
+		break;
+	case TEXT_JUSTIFY_RIGHT :
+		font.drawString(&dest, text, 0, lineY, dest.w, color, Graphics::kTextAlignRight);
+		break;
 	}
 }
 
@@ -336,9 +336,9 @@ void TextRenderer::drawTextWithWordWrapping(const Common::String &text, Graphics
 	uint i = 0u;
 	uint stringlen = text.size();
 
-  //Parse entirety of supplied text
+	//Parse entirety of supplied text
 	while (i < stringlen) {
-	  //Style tag encountered?
+		//Style tag encountered?
 		if (text[i] == '<') {
 			// Flush the currentWord to the currentSentence
 			currentSentence += currentWord;
@@ -479,7 +479,7 @@ void TextRenderer::drawTextWithWordWrapping(const Common::String &text, Graphics
 	// Render out any remaining words/sentences
 	if (!currentWord.empty() || !currentSentence.empty()) {
 		currentSentence += currentWord;
-		sentenceWidth += wordWidth;		
+		sentenceWidth += wordWidth;
 		textSurfaces.push_back(TextSurface(font.renderSolidText(currentSentence, currentState.getTextColor(_engine)), sentencePixelOffset, currentLineNumber));
 	}
 	lineWidths.push_back(lineWidth + sentenceWidth);
@@ -487,20 +487,20 @@ void TextRenderer::drawTextWithWordWrapping(const Common::String &text, Graphics
 	for (Common::Array<TextSurface>::iterator iter = textSurfaces.begin(); iter != textSurfaces.end(); ++iter) {
 		Common::Rect empty;
 		int16 Xpos = iter->_surfaceOffset.x;
-    switch (lineJustifications[iter->_lineNumber]) {
-      case TEXT_JUSTIFY_LEFT :
-	      break;
-      case TEXT_JUSTIFY_CENTER :
-        Xpos += ((dest.w - lineWidths[iter->_lineNumber]) / 2);
-	      break;
-      case TEXT_JUSTIFY_RIGHT :
-        Xpos += dest.w - lineWidths[iter->_lineNumber];
-	      break;
-    }
-    if(blackFrame)
-      _engine->getRenderManager()->blitSurfaceToSurface(*iter->_surface, empty, dest, Xpos, iter->_surfaceOffset.y);
-    else
-      _engine->getRenderManager()->blitSurfaceToSurface(*iter->_surface, empty, dest, Xpos, iter->_surfaceOffset.y, 0);
+		switch (lineJustifications[iter->_lineNumber]) {
+		case TEXT_JUSTIFY_LEFT :
+			break;
+		case TEXT_JUSTIFY_CENTER :
+			Xpos += ((dest.w - lineWidths[iter->_lineNumber]) / 2);
+			break;
+		case TEXT_JUSTIFY_RIGHT :
+			Xpos += dest.w - lineWidths[iter->_lineNumber];
+			break;
+		}
+		if (blackFrame)
+			_engine->getRenderManager()->blitSurfaceToSurface(*iter->_surface, empty, dest, Xpos, iter->_surfaceOffset.y);
+		else
+			_engine->getRenderManager()->blitSurfaceToSurface(*iter->_surface, empty, dest, Xpos, iter->_surfaceOffset.y, 0);
 		// Release memory
 		iter->_surface->free();
 		delete iter->_surface;
diff --git a/engines/zvision/text/truetype_font.cpp b/engines/zvision/text/truetype_font.cpp
index 11dd7e9b02b..6de91b4d71c 100644
--- a/engines/zvision/text/truetype_font.cpp
+++ b/engines/zvision/text/truetype_font.cpp
@@ -38,15 +38,15 @@
 namespace ZVision {
 
 const FontStyle systemFonts[] = {
-	{ "*times new roman*",	  "times",   "LiberationSerif"  },
-	{ "*times*",		  "times",   "LiberationSerif"  },
+	{ "*times new roman*",    "times",   "LiberationSerif"  },
+	{ "*times*",          "times",   "LiberationSerif"  },
 	{ "*century schoolbook*", "censcbk", "LiberationSerif"  },
-	{ "*garamond*", 	  "gara",    "LiberationSerif"  },
-	{ "*courier new*",	  "cour",    "LiberationMono" },
-	{ "*courier*",		  "cour",    "LiberationMono" },
-	{ "*ZorkDeath*",	  "cour",    "LiberationMono" },
-	{ "*arial*",		  "arial",   "LiberationSans" },
-	{ "*ZorkNormal*",	  "arial",   "LiberationSans" }
+	{ "*garamond*",       "gara",    "LiberationSerif"  },
+	{ "*courier new*",    "cour",    "LiberationMono" },
+	{ "*courier*",        "cour",    "LiberationMono" },
+	{ "*ZorkDeath*",      "cour",    "LiberationMono" },
+	{ "*arial*",          "arial",   "LiberationSans" },
+	{ "*ZorkNormal*",     "arial",   "LiberationSans" }
 };
 
 const FontStyle getSystemFont(int fontIndex) {
@@ -112,7 +112,7 @@ bool StyledTTFont::loadFont(const Common::String &fontName, int32 point, uint st
 	Common::File *file = new Common::File();
 	Graphics::Font *newFont;
 	if (!file->open(Common::Path(newFontName)) && !_engine->getSearchManager()->openFile(*file, Common::Path(newFontName)) &&
-		!file->open(Common::Path(liberationFontName)) && !_engine->getSearchManager()->openFile(*file, Common::Path(liberationFontName))) {
+	        !file->open(Common::Path(liberationFontName)) && !_engine->getSearchManager()->openFile(*file, Common::Path(liberationFontName))) {
 		newFont = Graphics::loadTTFFontFromArchive(liberationFontName, point, Graphics::kTTFSizeModeCell, 0, 0, (sharp ? Graphics::kTTFRenderModeMonochrome : Graphics::kTTFRenderModeNormal));
 		delete file;
 	} else {
diff --git a/engines/zvision/video/rlf_decoder.cpp b/engines/zvision/video/rlf_decoder.cpp
index b18ddcb8d59..93cb67c93e9 100644
--- a/engines/zvision/video/rlf_decoder.cpp
+++ b/engines/zvision/video/rlf_decoder.cpp
@@ -233,11 +233,10 @@ void RLFDecoder::RLFVideoTrack::decodeMaskedRunLengthEncoding(int8 *source, int8
 			}
 			// If numberOfSamples is >= 0, move destOffset forward ((numberOfSamples * 2) + 2)
 			// This function assumes the dest buffer has been memset with 0's.
-		} 
-		else {
+		} else {
 			if (sourceOffset + 1 >= sourceSize)
 				return;
-      else if (destOffset + 1 >= destSize) {
+			else if (destOffset + 1 >= destSize) {
 				debug(3, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
 				return;
 			}
@@ -271,8 +270,7 @@ void RLFDecoder::RLFVideoTrack::decodeSimpleRunLengthEncoding(int8 *source, int8
 			}
 			// If numberOfSamples is >= 0, copy one sample from source to the
 			// next (numberOfSamples + 2) dest spots
-		} 
-		else {
+		} else {
 			if (sourceOffset + 1 >= sourceSize)
 				return;
 			uint16 sampleColor = READ_LE_UINT16(source + sourceOffset);
diff --git a/engines/zvision/video/rlf_decoder.h b/engines/zvision/video/rlf_decoder.h
index 27b117f3648..32f640676f7 100644
--- a/engines/zvision/video/rlf_decoder.h
+++ b/engines/zvision/video/rlf_decoder.h
@@ -42,17 +42,31 @@ private:
 		RLFVideoTrack(Common::SeekableReadStream *stream);
 		~RLFVideoTrack() override;
 
-		uint16 getWidth() const override { return _width; }
-		uint16 getHeight() const override { return _height; }
-		Graphics::PixelFormat getPixelFormat() const override { return Graphics::PixelFormat(2, 5, 5, 5, 0, 10, 5, 0, 0); /* RGB 555 */ }
-		int getCurFrame() const override { return _displayedFrame; }
-		int getFrameCount() const override { return _frameCount; }
+		uint16 getWidth() const override {
+			return _width;
+		}
+		uint16 getHeight() const override {
+			return _height;
+		}
+		Graphics::PixelFormat getPixelFormat() const override {
+			return Graphics::PixelFormat(2, 5, 5, 5, 0, 10, 5, 0, 0); /* RGB 555 */
+		}
+		int getCurFrame() const override {
+			return _displayedFrame;
+		}
+		int getFrameCount() const override {
+			return _frameCount;
+		}
 		const Graphics::Surface *decodeNextFrame() override;
-		bool isSeekable() const override { return true; }
+		bool isSeekable() const override {
+			return true;
+		}
 		bool seek(const Audio::Timestamp &time) override;
 
 	protected:
-		Common::Rational getFrameRate() const override { return Common::Rational(1000, _frameTime); }
+		Common::Rational getFrameRate() const override {
+			return Common::Rational(1000, _frameTime);
+		}
 
 	private:
 		enum EncodingType {
@@ -125,7 +139,7 @@ private:
 		uint32 _frameBufferByteSize;
 
 		Common::SeekableReadStream *_readStream;
-	};	// RLFVideoTrack
+	};  // RLFVideoTrack
 };
 
 } // End of namespace ZVision
diff --git a/engines/zvision/video/video.cpp b/engines/zvision/video/video.cpp
index 2e1ba691aef..38ba7b8dbb9 100644
--- a/engines/zvision/video/video.cpp
+++ b/engines/zvision/video/video.cpp
@@ -23,7 +23,7 @@
 #include "common/system.h"
 #include "video/video_decoder.h"
 #if defined(USE_MPEG2) && defined(USE_A52)
-#include "video/mpegps_decoder.h"
+	#include "video/mpegps_decoder.h"
 #endif
 #include "engines/util.h"
 #include "graphics/surface.h"
@@ -44,19 +44,19 @@ Video::VideoDecoder *ZVision::loadAnimation(const Common::Path &fileName) {
 	Common::String tmpFileName = fileName.baseName();
 	tmpFileName.toLowercase();
 	Video::VideoDecoder *animation = NULL;
-	
- debug(1, "Loading animation %s", fileName.toString().c_str());
+
+	debug(1, "Loading animation %s", fileName.toString().c_str());
 
 	if (tmpFileName.hasSuffix(".rlf"))
 		animation = new RLFDecoder();
 	else if (tmpFileName.hasSuffix(".avi"))
 		animation = new ZorkAVIDecoder();
-#if defined(USE_MPEG2) && defined(USE_A52)
+	#if defined(USE_MPEG2) && defined(USE_A52)
 	else if (tmpFileName.hasSuffix(".vob")) {
- 		double amplification = getVobAmplification(tmpFileName);
+		double amplification = getVobAmplification(tmpFileName);
 		animation = new Video::MPEGPSDecoder(amplification);
 	}
-#endif
+	#endif
 	else
 		error("Unknown suffix for animation %s", fileName.toString().c_str());
 	Common::File *_file = getSearchManager()->openFile(fileName);
@@ -68,52 +68,52 @@ Video::VideoDecoder *ZVision::loadAnimation(const Common::Path &fileName) {
 	return animation;
 }
 
-  /**
-   * Play video at specified location.
-   *
-   * Pauses clock & normal game loop for duration of video; will still update & render subtitles & cursor.
-   *
-   * @param vid       Source video
-   * @param dstRect   Rectangle to play video into, defined relative to working window origin; video will scale to rectangle automatically.
- 	 * @param skippable Allow video to be skipped
-   * @param sub       Subtitle associated with video
-   * @param srcRect   Rectangle within video frame, defined relative to frame origin, to blit to output.  Only used for removing baked-in letterboxing in ZGI DVD HD videos
-   */	
-	 
+/**
+ * Play video at specified location.
+ *
+ * Pauses clock & normal game loop for duration of video; will still update & render subtitles & cursor.
+ *
+ * @param vid       Source video
+ * @param dstRect   Rectangle to play video into, defined relative to working window origin; video will scale to rectangle automatically.
+ * @param skippable Allow video to be skipped
+ * @param sub       Subtitle associated with video
+ * @param srcRect   Rectangle within video frame, defined relative to frame origin, to blit to output.  Only used for removing baked-in letterboxing in ZGI DVD HD videos
+ */
+
 void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, bool skippable, uint16 sub, const Common::Rect &srcRect) {
 	Common::Rect _dstRect = dstRect;
 	Common::Rect _srcRect = srcRect;
 	Common::Rect _frameArea = Common::Rect(vid.getWidth(), vid.getHeight());
 	Common::Rect _workingArea = _renderManager->getWorkingArea();
 	// If dstRect is empty, no specific scaling was requested. However, we may choose to do scaling anyway
-	bool scaled=false;
-	_workingArea.moveTo(0,0); //Set local origin system in this scope to origin of working area
-	
-  debug(1, "Playing video, source %d,%d,%d,%d, at destination %d,%d,%d,%d", _srcRect.left, _srcRect.top, _srcRect.right, _srcRect.bottom, _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
-	
+	bool scaled = false;
+	_workingArea.moveTo(0, 0); //Set local origin system in this scope to origin of working area
+
+	debug(1, "Playing video, source %d,%d,%d,%d, at destination %d,%d,%d,%d", _srcRect.left, _srcRect.top, _srcRect.right, _srcRect.bottom, _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
+
 	if (_dstRect.isEmpty())
 		_dstRect = _frameArea;
 	_dstRect.clip(_workingArea);
-  
-  debug(2, "Clipped dstRect = %d,%d,%d,%d", _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
-	
+
+	debug(2, "Clipped dstRect = %d,%d,%d,%d", _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
+
 	if (_srcRect.isEmpty())
 		_srcRect = _frameArea;
 	else
-	  _srcRect.clip(_frameArea);
-	  
-  debug(2, "Clipped srcRect = %d,%d,%d,%d", _srcRect.left, _srcRect.top, _srcRect.right, _srcRect.bottom);
+		_srcRect.clip(_frameArea);
+
+	debug(2, "Clipped srcRect = %d,%d,%d,%d", _srcRect.left, _srcRect.top, _srcRect.right, _srcRect.bottom);
 
 	Graphics::ManagedSurface &outSurface = _renderManager->getVidSurface(_dstRect);
-	_dstRect.moveTo(0,0);
+	_dstRect.moveTo(0, 0);
 	_dstRect.clip(Common::Rect(outSurface.w, outSurface.h));
 
-  debug(2, "dstRect clipped with outSurface = %d,%d,%d,%d", _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
-	
-  debug(1, "Final size %d x %d, at working window coordinates %d, %d", _srcRect.width(), _srcRect.height(), _dstRect.left, _dstRect.top);
+	debug(2, "dstRect clipped with outSurface = %d,%d,%d,%d", _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
+
+	debug(1, "Final size %d x %d, at working window coordinates %d, %d", _srcRect.width(), _srcRect.height(), _dstRect.left, _dstRect.top);
 	if (_srcRect.width() != _dstRect.width() || _srcRect.height() != _dstRect.height()) {
-	  debug(1,"Video will be scaled from %dx%d to %dx%d", _srcRect.width(), _srcRect.height(), _dstRect.width(), _dstRect.height());
-	  scaled = true;
+		debug(1, "Video will be scaled from %dx%d to %dx%d", _srcRect.width(), _srcRect.height(), _dstRect.width(), _dstRect.height());
+		scaled = true;
 	}
 	bool showSubs = (_scriptManager->getStateValue(StateKey_Subtitles) == 1);
 	_clock.stop();
@@ -149,27 +149,26 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 			if (showSubs && sub > 0)
 				_subtitleManager->update(vid.getCurFrame(), sub);
 			if (frame) {
-		    _renderManager->renderSceneToScreen(true,true,true);  //Redraw text area to clean background of subtitles for videos that don't fill entire working area, e.g, Nemesis sarcophagi
+				_renderManager->renderSceneToScreen(true, true, true); //Redraw text area to clean background of subtitles for videos that don't fill entire working area, e.g, Nemesis sarcophagi
 				if (scaled) {
-				  debug(8,"Scaled blit from area %d x %d to video output surface at output surface position %d, %d", _srcRect.width(), _srcRect.height(), _dstRect.left, _dstRect.top);
+					debug(8, "Scaled blit from area %d x %d to video output surface at output surface position %d, %d", _srcRect.width(), _srcRect.height(), _dstRect.left, _dstRect.top);
 					outSurface.blitFrom(*frame, _srcRect, _dstRect);
-					}
-        else {
-				  debug(8,"Simple blit from area %d x %d to video output surface at output surface position %d, %d", _srcRect.width(), _srcRect.height(), _dstRect.left, _dstRect.top);
-				  outSurface.simpleBlitFrom(*frame, _srcRect, _dstRect.origin());
-			  }
+				} else {
+					debug(8, "Simple blit from area %d x %d to video output surface at output surface position %d, %d", _srcRect.width(), _srcRect.height(), _dstRect.left, _dstRect.top);
+					outSurface.simpleBlitFrom(*frame, _srcRect, _dstRect.origin());
+				}
 				_subtitleManager->process(0);
 			}
 		}
 		// Always update the screen so the mouse continues to render & video does not skip
-		_renderManager->renderSceneToScreen(true,true,false);
+		_renderManager->renderSceneToScreen(true, true, false);
 		_system->delayMillis(vid.getTimeToNextFrame() / 2); //Exponentially decaying delay
 	}
 	_cutscenesKeymap->setEnabled(false);
 	_gameKeymap->setEnabled(true);
 	_videoIsPlaying = false;
 	_clock.start();
-  debug(1, "Video playback complete");
+	debug(1, "Video playback complete");
 }
 
 double ZVision::getVobAmplification(Common::String fileName) const {
diff --git a/engines/zvision/video/zork_avi_decoder.cpp b/engines/zvision/video/zork_avi_decoder.cpp
index 7137ceabdfc..4545d5065d8 100644
--- a/engines/zvision/video/zork_avi_decoder.cpp
+++ b/engines/zvision/video/zork_avi_decoder.cpp
@@ -41,7 +41,7 @@ Video::AVIDecoder::AVIAudioTrack *ZorkAVIDecoder::createAudioTrack(Video::AVIDec
 }
 
 ZorkAVIDecoder::ZorkAVIAudioTrack::ZorkAVIAudioTrack(const AVIStreamHeader &streamHeader, const PCMWaveFormat &waveFormat, Audio::Mixer::SoundType soundType) :
-		Video::AVIDecoder::AVIAudioTrack(streamHeader, waveFormat, soundType), _queueStream(0), _decoder(waveFormat.channels == 2) {
+	Video::AVIDecoder::AVIAudioTrack(streamHeader, waveFormat, soundType), _queueStream(0), _decoder(waveFormat.channels == 2) {
 }
 
 void ZorkAVIDecoder::ZorkAVIAudioTrack::createAudioStream() {
@@ -57,10 +57,10 @@ void ZorkAVIDecoder::ZorkAVIAudioTrack::queueSound(Common::SeekableReadStream *s
 		byte flags = Audio::FLAG_16BITS;
 		if (_wvInfo.channels == 2)
 			flags |= Audio::FLAG_STEREO;
-#ifdef SCUMM_LITTLE_ENDIAN
+		#ifdef SCUMM_LITTLE_ENDIAN
 		// RawChunkStream produces native endianness int16
 		flags |= Audio::FLAG_LITTLE_ENDIAN;
-#endif
+		#endif
 		_queueStream->queueBuffer((byte *)chunk.data, chunk.size, DisposeAfterUse::YES, flags);
 	}
 
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index 2ecb6293d38..469351e1f07 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -62,24 +62,24 @@ namespace ZVision {
 struct zvisionIniSettings {
 	const char *name;
 	int16 slot;
-	int16 defaultValue;	// -1: use the bool value
+	int16 defaultValue; // -1: use the bool value
 	bool defaultBoolValue;
 	bool allowEditing;
 } settingsKeys[ZVISION_SETTINGS_KEYS_COUNT] = {
 	// Hardcoded settings
-	{"countrycode", StateKey_CountryCode, 0, false, false},	// always 0 = US, subtitles are shown for codes 0 - 4, unused
-	{"lineskipvideo", StateKey_VideoLineSkip, 0, false, false},	// video line skip, 0 = default, 1 = always, 2 = pixel double when possible, unused
-	{"installlevel", StateKey_InstallLevel, 0, false, false},	// 0 = full, checked by universe.scr
-	{"debugcheats", StateKey_DebugCheats, -1, true, false},	// always start with the GOxxxx cheat enabled
+	{"countrycode", StateKey_CountryCode, 0, false, false}, // always 0 = US, subtitles are shown for codes 0 - 4, unused
+	{"lineskipvideo", StateKey_VideoLineSkip, 0, false, false}, // video line skip, 0 = default, 1 = always, 2 = pixel double when possible, unused
+	{"installlevel", StateKey_InstallLevel, 0, false, false},   // 0 = full, checked by universe.scr
+	{"debugcheats", StateKey_DebugCheats, -1, true, false}, // always start with the GOxxxx cheat enabled
 	// Editable settings
-	{"qsoundenabled", StateKey_Qsound, -1, true, true},	// 1 = enable generic directional audio and non-linear volume scaling.  Genuine Qsound is copyright & unlikely to be implemented.
+	{"qsoundenabled", StateKey_Qsound, -1, true, true}, // 1 = enable generic directional audio and non-linear volume scaling.  Genuine Qsound is copyright & unlikely to be implemented.
 	{"keyboardturnspeed", StateKey_KbdRotateSpeed, 5, false, true},
-	{"panarotatespeed", StateKey_RotateSpeed, 540, false, true},	// checked by universe.scr
-	{"noanimwhileturning", StateKey_NoTurnAnim, -1, false, true},	// toggle playing animations during pana rotation
-	{"highquality", StateKey_HighQuality, -1, true, false},	// high panorama quality; enables bilinear filtering in RenderTable
+	{"panarotatespeed", StateKey_RotateSpeed, 540, false, true},    // checked by universe.scr
+	{"noanimwhileturning", StateKey_NoTurnAnim, -1, false, true},   // toggle playing animations during pana rotation
+	{"highquality", StateKey_HighQuality, -1, true, false}, // high panorama quality; enables bilinear filtering in RenderTable
 	{"venusenabled", StateKey_VenusEnable, -1, true, true},
 	{"subtitles", StateKey_Subtitles, -1, true, true},
-	{"mpegmovies", StateKey_MPEGMovies, -1, true, true}		// Zork: Grand Inquisitor DVD hi-res MPEG movies (0 = normal, 1 = hires, 2 = disable option)
+	{"mpegmovies", StateKey_MPEGMovies, -1, true, true}     // Zork: Grand Inquisitor DVD hi-res MPEG movies (0 = normal, 1 = hires, 2 = disable option)
 };
 
 const char *mainKeymapId = "zvision";
@@ -126,8 +126,8 @@ ZVision::~ZVision() {
 	delete _stringManager;
 	delete _saveManager;
 	delete _scriptManager;
-	delete _renderManager;	// should be deleted after the script manager
-	delete _subtitleManager;	
+	delete _renderManager;  // should be deleted after the script manager
+	delete _subtitleManager;
 	delete _rnd;
 	delete _midiManager;
 	delete _volumeManager;
@@ -175,33 +175,34 @@ void ZVision::saveSettings() {
 }
 
 void ZVision::initialize() {
-  //File Paths
+	//File Paths
 	const Common::FSNode gameDataDir(ConfMan.getPath("path"));
 	_searchManager = new SearchManager(ConfMan.getPath("path"), 6);
 	_searchManager->addDir("FONTS");
 	_searchManager->addDir("addon");
-	switch(getGameId()) {
-	  case GID_GRANDINQUISITOR:
-		  if (!_searchManager->loadZix("INQUIS.ZIX"))
-			  error("Unable to load file INQUIS.ZIX");	  
-	    break;
-    case GID_NEMESIS:
-		  if (!_searchManager->loadZix("NEMESIS.ZIX"))
-			  // The game might not be installed, try MEDIUM.ZIX instead
-			  if (!_searchManager->loadZix("ZNEMSCR/MEDIUM.ZIX"))
-				  error("Unable to load the file ZNEMSCR/MEDIUM.ZIX");
-      break;
-	  case GID_NONE:
-    default:   
-  		error("Unknown/unspecified GameId");
-	    break;
+	switch (getGameId()) {
+	case GID_GRANDINQUISITOR:
+		if (!_searchManager->loadZix("INQUIS.ZIX"))
+			error("Unable to load file INQUIS.ZIX");
+		break;
+	case GID_NEMESIS:
+		if (!_searchManager->loadZix("NEMESIS.ZIX"))
+			// The game might not be installed, try MEDIUM.ZIX instead
+			if (!_searchManager->loadZix("ZNEMSCR/MEDIUM.ZIX"))
+				error("Unable to load the file ZNEMSCR/MEDIUM.ZIX");
+		break;
+	case GID_NONE:
+	// fall through
+	default:
+		error("Unknown/unspecified GameId");
+		break;
 	}
-	
+
 	//Graphics
 	_widescreen = ConfMan.getBool("widescreen");
 	_doubleFPS = ConfMan.getBool("doublefps");
-	
-  //Keymaps
+
+	//Keymaps
 	Common::Keymapper *keymapper = _system->getEventManager()->getKeymapper();
 	_gameKeymap = keymapper->getKeymap(gameKeymapId);
 	_gameKeymap->setEnabled(true);
@@ -212,24 +213,25 @@ void ZVision::initialize() {
 	_rnd = new Common::RandomSource("zvision");
 
 	// Create managers
-  switch (getGameId()) {
-    case GID_NEMESIS:
-      _renderManager = new RenderManager(this, nemesisLayout, _resourcePixelFormat, _doubleFPS, _widescreen);
-	    _menu = new MenuNemesis(this, _renderManager->getMenuArea());
-      _subtitleManager = new SubtitleManager(this, nemesisLayout, _resourcePixelFormat, _doubleFPS);
-	    _volumeManager = new VolumeManager(this, kVolumePowerLaw);
-	    break;
-    case GID_GRANDINQUISITOR:
-      _renderManager = new RenderManager(this, zgiLayout, _resourcePixelFormat, _doubleFPS, _widescreen);
-		  _menu = new MenuZGI(this, _renderManager->getMenuArea());
-      _subtitleManager = new SubtitleManager(this, zgiLayout, _resourcePixelFormat, _doubleFPS);
-	    _volumeManager = new VolumeManager(this, kVolumeLogAmplitude);
-		  break;
-	  case GID_NONE:
-	  default:
-  		error("Unknown/unspecified GameId");
-	    break;
-  }
+	switch (getGameId()) {
+	case GID_NEMESIS:
+		_renderManager = new RenderManager(this, nemesisLayout, _resourcePixelFormat, _doubleFPS, _widescreen);
+		_menu = new MenuNemesis(this, _renderManager->getMenuArea());
+		_subtitleManager = new SubtitleManager(this, nemesisLayout, _resourcePixelFormat, _doubleFPS);
+		_volumeManager = new VolumeManager(this, kVolumePowerLaw);
+		break;
+	case GID_GRANDINQUISITOR:
+		_renderManager = new RenderManager(this, zgiLayout, _resourcePixelFormat, _doubleFPS, _widescreen);
+		_menu = new MenuZGI(this, _renderManager->getMenuArea());
+		_subtitleManager = new SubtitleManager(this, zgiLayout, _resourcePixelFormat, _doubleFPS);
+		_volumeManager = new VolumeManager(this, kVolumeLogAmplitude);
+		break;
+	case GID_NONE:
+	// fall through
+	default:
+		error("Unknown/unspecified GameId");
+		break;
+	}
 	_scriptManager = new ScriptManager(this);
 	_saveManager = new SaveManager(this);
 	_stringManager = new StringManager(this);
@@ -246,10 +248,10 @@ void ZVision::initialize() {
 	registerDefaultSettings();
 	loadSettings();
 
-#if !defined(USE_MPEG2) || !defined(USE_A52)
+	#if !defined(USE_MPEG2) || !defined(USE_A52)
 	// libmpeg2 or liba52 not loaded, disable the MPEG2 movies option
 	_scriptManager->setStateValue(StateKey_MPEGMovies, 2);
-#endif
+	#endif
 
 	// Create debugger console. It requires GFX to be initialized
 	setDebugger(new Console(this));
@@ -257,8 +259,8 @@ void ZVision::initialize() {
 	// Initialize FPS timer callback
 	getTimerManager()->installTimerProc(&fpsTimerCallback, 1000000, this, "zvisionFPS");
 
-  //Ensure a new game is launched with correct panorama quality setting
-  _scriptManager->setStateValue(StateKey_HighQuality, ConfMan.getBool("highquality"));
+	//Ensure a new game is launched with correct panorama quality setting
+	_scriptManager->setStateValue(StateKey_HighQuality, ConfMan.getBool("highquality"));
 }
 
 extern const FontStyle getSystemFont(int fontIndex);
@@ -297,8 +299,8 @@ Common::Error ZVision::run() {
 			liberationFontName += ".ttf";
 
 			if (!Common::File::exists(Common::Path(fontName)) && !_searchManager->hasFile(Common::Path(fontName)) &&
-				!Common::File::exists(Common::Path(liberationFontName)) && !_searchManager->hasFile(Common::Path(liberationFontName)) &&
-				!Common::File::exists("fonts.dat") && !_searchManager->hasFile("fonts.dat")) {
+			        !Common::File::exists(Common::Path(liberationFontName)) && !_searchManager->hasFile(Common::Path(liberationFontName)) &&
+			        !Common::File::exists("fonts.dat") && !_searchManager->hasFile("fonts.dat")) {
 				foundAllFonts = false;
 				break;
 			}
@@ -308,58 +310,58 @@ Common::Error ZVision::run() {
 	}
 	if (!foundAllFonts) {
 		GUI::MessageDialog dialog(_(
-				"Before playing this game, you'll need to copy the required "
-				"fonts into ScummVM's extras directory, or into the game directory. "
-				"On Windows, you'll need the following font files from the Windows "
-				"font directory: Times New Roman, Century Schoolbook, Garamond, "
-				"Courier New and Arial. Alternatively, you can download the "
-				"Liberation Fonts package. You'll need all the fonts from the "
-				"font package you choose, i.e., LiberationMono, LiberationSans "
-				"and LiberationSerif."
-		));
+		                              "Before playing this game, you'll need to copy the required "
+		                              "fonts into ScummVM's extras directory, or into the game directory. "
+		                              "On Windows, you'll need the following font files from the Windows "
+		                              "font directory: Times New Roman, Century Schoolbook, Garamond, "
+		                              "Courier New and Arial. Alternatively, you can download the "
+		                              "Liberation Fonts package. You'll need all the fonts from the "
+		                              "font package you choose, i.e., LiberationMono, LiberationSans "
+		                              "and LiberationSerif."
+		                          ));
 		dialog.runModal();
 		quitGame();
 		return Common::kUnknownError;
 	}
-	if(getGameId() == GID_NEMESIS && !_midiManager->isAvailable()) {
+	if (getGameId() == GID_NEMESIS && !_midiManager->isAvailable()) {
 		GUI::MessageDialog MIDIdialog(_(
-	      "MIDI playback is not available, or else improperly configured. "
-	      "Zork Nemesis contains several music puzzles which require "
-	      "MIDI audio in order to be solved.  These puzzles may alternatively "
-	      "be solved using subtitles, if supported. Continue launching game?" 
-      ),
-	    _("Yes"),
-	    _("No")
-    );
-	  if (MIDIdialog.runModal() != GUI::kMessageOK)
-		  quitGame();
-  }
+		                                  "MIDI playback is not available, or else improperly configured. "
+		                                  "Zork Nemesis contains several music puzzles which require "
+		                                  "MIDI audio in order to be solved.  These puzzles may alternatively "
+		                                  "be solved using subtitles, if supported. Continue launching game?"
+		                              ),
+		                              _("Yes"),
+		                              _("No")
+		                             );
+		if (MIDIdialog.runModal() != GUI::kMessageOK)
+			quitGame();
+	}
 
 	// Main loop
 	while (!shouldQuit()) {
-	  debug(5,"\nInitiating new game cycle");
-	  debug(5,"Timers");
-	  //Timers
+		debug(5, "\nInitiating new game cycle");
+		debug(5, "Timers");
+		//Timers
 		_clock.update();
-		uint32 deltaTime = _clock.getDeltaTime();		
-	  debug(5,"Logic");
-    //Process game logic & update backbuffers as necessary   
-    debug(5,"Cursor");
-		_cursorManager->setItemID(_scriptManager->getStateValue(StateKey_InventoryItem));	
-    debug(5,"Events");
-		processEvents();  //NB rotateTo or playVideo event will pause clock & call renderSceneToScreen() directly.		
-    debug(5,"Rotation");
-		_renderManager->updateRotation();	
-    debug(5,"Scripts");
+		uint32 deltaTime = _clock.getDeltaTime();
+		debug(5, "Logic");
+		//Process game logic & update backbuffers as necessary
+		debug(5, "Cursor");
+		_cursorManager->setItemID(_scriptManager->getStateValue(StateKey_InventoryItem));
+		debug(5, "Events");
+		processEvents();  //NB rotateTo or playVideo event will pause clock & call renderSceneToScreen() directly.
+		debug(5, "Rotation");
+		_renderManager->updateRotation();
+		debug(5, "Scripts");
 		_scriptManager->update(deltaTime);
-    debug(5,"Menu");
+		debug(5, "Menu");
 		_menu->process(deltaTime);
-    debug(5,"Subtitles");
+		debug(5, "Subtitles");
 		_subtitleManager->process(deltaTime);
-	  debug(5,"Render");
+		debug(5, "Render");
 		// Render the backBuffer to the screen
-  	_renderManager->prepareBackground();
-		if(_renderManager->renderSceneToScreen())
+		_renderManager->prepareBackground();
+		if (_renderManager->renderSceneToScreen())
 			_renderedFrameCount++;
 		else
 			_frameRenderDelay--;
@@ -371,12 +373,12 @@ void ZVision::pauseEngineIntern(bool pause) {
 	_mixer->pauseAll(pause);
 	if (pause)
 		_clock.stop();
-  else
+	else
 		_clock.start();
 }
 
 void ZVision::setRenderDelay(uint delay) {
-  debug(2,"Setting framerenderdelay to %d", delay);
+	debug(2, "Setting framerenderdelay to %d", delay);
 	_frameRenderDelay = delay;
 }
 
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index 649aa7cb391..a34a515074c 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -71,10 +71,10 @@ class MidiManager;
 class VolumeManager;
 
 struct ScreenLayout {
-  Common::Rect screenArea;  //Original screen resolution
-  Common::Rect menuArea;  //Menu display area, relative to original screen
-  Common::Rect workingArea;   //Playfield & video playback area, relative to original screen
-  Common::Rect textArea;  //Subtitle & message area, relative to original screen
+	Common::Rect screenArea;  //Original screen resolution
+	Common::Rect menuArea;  //Menu display area, relative to original screen
+	Common::Rect workingArea;   //Playfield & video playback area, relative to original screen
+	Common::Rect textArea;  //Subtitle & message area, relative to original screen
 };
 
 //NB Footage of original DOS Nemesis engine indicates playfield was centrally placed on screen.
@@ -100,17 +100,17 @@ static const ScreenLayout zgiLayout {
 //*/
 //Central values
 static const ScreenLayout nemesisLayout {
-  Common::Rect(640,480),  //Screen
-  Common::Rect(Common::Point(64,0), 512, 32), //Menu
-  Common::Rect(Common::Point(64,80), 512, 320), //Working; aspect ratio 1.6
-  Common::Rect(Common::Point(64,420), 512, 60) //Text
+	Common::Rect(640, 480), //Screen
+	Common::Rect(Common::Point(64, 0), 512, 32), //Menu
+	Common::Rect(Common::Point(64, 80), 512, 320), //Working; aspect ratio 1.6
+	Common::Rect(Common::Point(64, 420), 512, 60) //Text
 };
 
 static const ScreenLayout zgiLayout {
-  Common::Rect(640,480),  //Screen
-  Common::Rect(Common::Point(0,0), 640, 32), //Menu
-  Common::Rect(Common::Point(0,68), 640, 344), //Working; aspect ratio 1.86
-  Common::Rect(Common::Point(0,412), 640, 68) //Text
+	Common::Rect(640, 480), //Screen
+	Common::Rect(Common::Point(0, 0), 640, 32), //Menu
+	Common::Rect(Common::Point(0, 68), 640, 344), //Working; aspect ratio 1.86
+	Common::Rect(Common::Point(0, 412), 640, 68) //Text
 };
 //*/
 enum {
@@ -151,7 +151,7 @@ public:
 	 */
 //	Common::Rect _workingArea;
 	/**
-	 * A Rectangle in which the menu will be rendered.  
+	 * A Rectangle in which the menu will be rendered.
 	 * In the original game, this is always separate from the working window,
 	 * and thus may be rendered completely independently.
 	 * In the widescreen mod, this window may intersect the working window,
@@ -164,7 +164,7 @@ public:
 
 private:
 	const ZVisionGameDescription *_gameDescription;
-	
+
 	// We need random numbers
 	Common::RandomSource *_rnd;
 
@@ -178,8 +178,8 @@ private:
 	MidiManager *_midiManager;
 	SaveManager *_saveManager;
 	MenuManager *_menu;
-  SubtitleManager *_subtitleManager;
-  VolumeManager *_volumeManager;
+	SubtitleManager *_subtitleManager;
+	VolumeManager *_volumeManager;
 
 	// Clock
 	Clock _clock;
@@ -267,7 +267,7 @@ public:
 		_clock.stop();
 	}
 
-	void initScreen(bool hiRes=false);
+	void initScreen(bool hiRes = false);
 
 	/**
 	 * Play a video until it is finished. This is a blocking call. It will call
@@ -289,9 +289,9 @@ public:
 	int getFPS() const {
 		return _fps;
 	}
-	
+
 	bool isWidescreen() {
-	  return _widescreen;
+		return _widescreen;
 	}
 
 	void syncSoundSettings() override;


Commit: 8c47b04e542878ce7bf8e91a5070d66faac1a681
    https://github.com/scummvm/scummvm/commit/8c47b04e542878ce7bf8e91a5070d66faac1a681
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:59+02:00

Commit Message:
GRAPHICS: Code formatting compliance.
Apply astyle with standard ScummVM parameters to framelimiter.cpp, framelimiter.h, screen.cpp

Changed paths:
    graphics/framelimiter.cpp
    graphics/framelimiter.h
    graphics/screen.cpp


diff --git a/graphics/framelimiter.cpp b/graphics/framelimiter.cpp
index cc1df8e603d..f0b702b321f 100644
--- a/graphics/framelimiter.cpp
+++ b/graphics/framelimiter.cpp
@@ -25,46 +25,46 @@
 namespace Graphics {
 
 FrameLimiter::FrameLimiter(OSystem *system, const uint framerate, const bool deferToVsync) :
-		_system(system),
-		_deferToVsync(deferToVsync),
-		_frameStart(0),
-		_frameLimit(0),
-		_frameDuration(0),
-		_drawStart(0),
-		_drawDuration(0),
-		_loopDuration(0),
-		_delay(0) {
-  initialize(framerate);
+	_system(system),
+	_deferToVsync(deferToVsync),
+	_frameStart(0),
+	_frameLimit(0),
+	_frameDuration(0),
+	_drawStart(0),
+	_drawDuration(0),
+	_loopDuration(0),
+	_delay(0) {
+	initialize(framerate);
 }
 
 void FrameLimiter::initialize() {
-	_enabled =  (_frameLimit != 0) && !(_deferToVsync && _system->getFeatureState(OSystem::kFeatureVSync));
+	_enabled = (_frameLimit != 0) && !(_deferToVsync && _system->getFeatureState(OSystem::kFeatureVSync));
 	_frameDuration = _frameLimit;
-};
+}
 
 void FrameLimiter::initialize(const uint framerate) {
 	_frameLimit = (framerate > 0) ? 1000.0f / CLIP<uint>(framerate, 1, 100) : 0;
-  initialize();
-};
+	initialize();
+}
 
 uint FrameLimiter::startFrame() {
 	_now = _system->getMillis();
 	if (_frameStart != 0) {
-	  _frameDuration = _now - _frameStart;
-    _drawDuration = _now - _drawStart;
-  }
+		_frameDuration = _now - _frameStart;
+		_drawDuration = _now - _drawStart;
+	}
 	_frameStart = _now;
 	return _frameDuration;
 }
 
 bool FrameLimiter::delayBeforeSwap() {
-  _now = _system->getMillis();
-  _loopDuration = _now - _frameStart;
-	if(_enabled) {
-	  //delay = frameLimit - loopDuration;  //Original functionality, will tend to undershoot target framerate slightly due to finite screen.update() time.
-  	_delay = _frameLimit - (_now - _drawStart); //Ensure EXACTLY the specified frame duration has elapsed since last screen.update() was called.
-    if(_delay > 0)
-  	  _system->delayMillis(_delay);
+	_now = _system->getMillis();
+	_loopDuration = _now - _frameStart;
+	if (_enabled) {
+		//delay = frameLimit - loopDuration;  //Original functionality, will tend to undershoot target framerate slightly due to finite screen.update() time.
+		_delay = _frameLimit - (_now - _drawStart); //Ensure EXACTLY the specified frame duration has elapsed since last screen.update() was called.
+		if (_delay > 0)
+			_system->delayMillis(_delay);
 	}
 	_drawStart = _system->getMillis();
 	return (_delay < 0); //Check if frame is late
diff --git a/graphics/framelimiter.h b/graphics/framelimiter.h
index fa7fb595570..a5e1d9f474d 100644
--- a/graphics/framelimiter.h
+++ b/graphics/framelimiter.h
@@ -40,61 +40,69 @@ namespace Graphics {
 class FrameLimiter {
 public:
 	FrameLimiter(OSystem *system, const uint framerate, const bool deferToVsync = true);
-/**
- * Always call this after instantiating Screen & calling initGraphics(), to ensure Vsync status is detected correctly!
- */
-  void initialize();
+	/**
+	 * Always call this after instantiating Screen & calling initGraphics(), to ensure Vsync status is detected correctly!
+	 */
+	void initialize();
 	void initialize(const uint framerate);
 
-/**
- * Call immediately before starting game logic cycle, and immediately after previous screen->update(), if any.
- * Returns last frame duration.
- */
+	/**
+	 * Call immediately before starting game logic cycle, and immediately after previous screen->update(), if any.
+	 * Returns last frame duration.
+	 */
 	uint startFrame();
-	
-/**
- * Call immediately after game logic cycle is completed, and immediately before screen->update().
- * If Vsync is inactive, will wait and return at the appropriate moment to call screen->update() in order to maintain the specified FPS.
- * If Vsync is active, will return immediately as screen->update() should automatically wait for the right moment.
- * Returns true if next frame is expected to be late.
- */
+
+	/**
+	 * Call immediately after game logic cycle is completed, and immediately before screen->update().
+	 * If Vsync is inactive, will wait and return at the appropriate moment to call screen->update() in order to maintain the specified FPS.
+	 * If Vsync is active, will return immediately as screen->update() should automatically wait for the right moment.
+	 * Returns true if next frame is expected to be late.
+	 */
 	bool delayBeforeSwap();
 	void pause(bool pause);
-/**
- * Return duration of last whole frame, including game logic, frame limiter or Vsync delay (if any), and screen redraw time.
- * Specifically, this is the time between the last two successive startFrame() calls.
- */
-	uint getLastFrameDuration() const {return _frameDuration;};
-/**
- * Return duration of last screen update
- * If Vsync is inactive, this value will just be the duration of the redraw process itself;
- * If Vsync is active, this value will encompass both the redraw time AND the delay between presenting the frame to redraw and the screen redraw actually starting.
- */
- 	uint getLastDrawDuration() const {return _drawDuration;}; 
-/**
- * Return duration of last game logic loop
- * Specifically, this is the time from when startFrame() was last called to when delayBeforeSwap() was last called
- */
-	uint getLastLoopDuration() const {return _loopDuration;};
-/**
- * If true, framelimiter is active and applying _system->delayMillis(delay) to maintain the specified FPS, if valid.
- * If false, framelimiter is inactive, either because supplied FPS was invalid or because Vsync is active.
- * delayBeforeSwap() should still be called even if inactive, in order to ensure timers are updated correctly.
- */
-	bool isEnabled() const {return _enabled;};
-	
+	/**
+	 * Return duration of last whole frame, including game logic, frame limiter or Vsync delay (if any), and screen redraw time.
+	 * Specifically, this is the time between the last two successive startFrame() calls.
+	 */
+	uint getLastFrameDuration() const {
+		return _frameDuration;
+	};
+	/**
+	 * Return duration of last screen update
+	 * If Vsync is inactive, this value will just be the duration of the redraw process itself;
+	 * If Vsync is active, this value will encompass both the redraw time AND the delay between presenting the frame to redraw and the screen redraw actually starting.
+	 */
+	uint getLastDrawDuration() const {
+		return _drawDuration;
+	};
+	/**
+	 * Return duration of last game logic loop
+	 * Specifically, this is the time from when startFrame() was last called to when delayBeforeSwap() was last called
+	 */
+	uint getLastLoopDuration() const {
+		return _loopDuration;
+	};
+	/**
+	 * If true, framelimiter is active and applying _system->delayMillis(delay) to maintain the specified FPS, if valid.
+	 * If false, framelimiter is inactive, either because supplied FPS was invalid or because Vsync is active.
+	 * delayBeforeSwap() should still be called even if inactive, in order to ensure timers are updated correctly.
+	 */
+	bool isEnabled() const {
+		return _enabled;
+	};
+
 private:
 	OSystem *_system;
 	bool _enabled;
 	bool _deferToVsync;
 	uint _frameStart;  //Time at which screen update completed and startFrame() was called; start of next cycle of game logic
-  uint _frameLimit;  //Target frame duration to achieve specified FPS
-  uint _frameDuration; //Duration of previous frame between successive startFrame() calls; total game logic, delay (if any) and screen update time
-  uint _drawStart;  //Time at which delayBeforeSwap() returns
-  uint _drawDuration;  //Measured screen update time
-  uint _loopDuration;  //Duration of last game logic cycle, from when startFrame() was called to when delayBeforeSwap() was called
-  int _delay; //Time to delay before returning from delayBeforeSwap()
-  uint _now; //Current time
+	uint _frameLimit;  //Target frame duration to achieve specified FPS
+	uint _frameDuration; //Duration of previous frame between successive startFrame() calls; total game logic, delay (if any) and screen update time
+	uint _drawStart;  //Time at which delayBeforeSwap() returns
+	uint _drawDuration;  //Measured screen update time
+	uint _loopDuration;  //Duration of last game logic cycle, from when startFrame() was called to when delayBeforeSwap() was called
+	int _delay; //Time to delay before returning from delayBeforeSwap()
+	uint _now; //Current time
 };
 
 } // End of namespace Graphics
diff --git a/graphics/screen.cpp b/graphics/screen.cpp
index b3e5cb68e71..653373eed9e 100644
--- a/graphics/screen.cpp
+++ b/graphics/screen.cpp
@@ -45,27 +45,26 @@ void Screen::update() {
 	// Loop through copying dirty areas to the physical screen
 	PixelFormat outputFormat = g_system->getScreenFormat();
 	Common::List<Common::Rect>::iterator i;
-	if(outputFormat == format) {
-	  for (i = _dirtyRects.begin(); i != _dirtyRects.end(); ++i) {
-		  const Common::Rect &r = *i;
-		  const byte *srcP = (const byte *)getBasePtr(r.left, r.top);
-		  g_system->copyRectToScreen(srcP, pitch, r.left, r.top,
-			  r.width(), r.height());
-	  }
-  }
-  else {
-  	Graphics::Surface outSurface;
-    for (i = _dirtyRects.begin(); i != _dirtyRects.end(); ++i) {
-	    const Common::Rect &r = *i;
-		  const byte *srcP = (const byte *)getBasePtr(r.left, r.top);
-      outSurface.create(r.width(), r.height(), format);
-      outSurface.copyRectToSurface(srcP, pitch, 0, 0, r.width(), r.height());
-      outSurface.convertToInPlace(outputFormat);
-	    g_system->copyRectToScreen(outSurface.getBasePtr(0,0), outSurface.pitch, r.left, r.top,
-		    r.width(), r.height());
-    }
-    outSurface.free();
-  }
+	if (outputFormat == format) {
+		for (i = _dirtyRects.begin(); i != _dirtyRects.end(); ++i) {
+			const Common::Rect &r = *i;
+			const byte *srcP = (const byte *)getBasePtr(r.left, r.top);
+			g_system->copyRectToScreen(srcP, pitch, r.left, r.top,
+			                           r.width(), r.height());
+		}
+	} else {
+		Graphics::Surface outSurface;
+		for (i = _dirtyRects.begin(); i != _dirtyRects.end(); ++i) {
+			const Common::Rect &r = *i;
+			const byte *srcP = (const byte *)getBasePtr(r.left, r.top);
+			outSurface.create(r.width(), r.height(), format);
+			outSurface.copyRectToSurface(srcP, pitch, 0, 0, r.width(), r.height());
+			outSurface.convertToInPlace(outputFormat);
+			g_system->copyRectToScreen(outSurface.getBasePtr(0, 0), outSurface.pitch, r.left, r.top,
+			                           r.width(), r.height());
+		}
+		outSurface.free();
+	}
 
 	// Signal the physical screen to update
 	updateScreen();


Commit: f784996e93f6a3b7aedf8765d14d924e352f97fa
    https://github.com/scummvm/scummvm/commit/f784996e93f6a3b7aedf8765d14d924e352f97fa
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:59+02:00

Commit Message:
COMMON: Code formatting compliance.
Apply astyle with standard ScummVM parameters to rect.h

Changed paths:
    common/rect.h


diff --git a/common/rect.h b/common/rect.h
index 9f7bd9db56e..6a3c895e9f1 100644
--- a/common/rect.h
+++ b/common/rect.h
@@ -43,8 +43,8 @@ namespace Common {
  * Simple class for handling both 2D position and size.
  */
 struct Point {
-	int16 x;	/*!< The horizontal position of the point. */
-	int16 y;	/*!< The vertical position of the point. */
+	int16 x;    /*!< The horizontal position of the point. */
+	int16 y;    /*!< The vertical position of the point. */
 
 	constexpr Point() : x(0), y(0) {}
 
@@ -55,35 +55,51 @@ struct Point {
 	/**
 	 * Determine whether the position of two points is the same.
 	 */
-	bool  operator==(const Point &p)    const { return x == p.x && y == p.y; }
+	bool  operator==(const Point &p)    const {
+		return x == p.x && y == p.y;
+	}
 	/**
 	 * Determine whether the position of two points is not the same.
 	 */
-	bool  operator!=(const Point &p)    const { return x != p.x || y != p.y; }
+	bool  operator!=(const Point &p)    const {
+		return x != p.x || y != p.y;
+	}
 	/**
 	 * Create a point by adding the @p delta value to a point.
 	 */
-	Point operator+(const Point &delta) const { return Point(x + delta.x, y + delta.y); }
+	Point operator+(const Point &delta) const {
+		return Point(x + delta.x, y + delta.y);
+	}
 	/**
 	 * Create a point by subtracting the @p delta value from a point.
 	 */
-	Point operator-(const Point &delta) const { return Point(x - delta.x, y - delta.y); }
+	Point operator-(const Point &delta) const {
+		return Point(x - delta.x, y - delta.y);
+	}
 	/**
 	 * Create a point by dividing a point by the (int) @p divisor value.
 	 */
-	Point operator/(int divisor) const { return Point(x / divisor, y / divisor); }
+	Point operator/(int divisor) const {
+		return Point(x / divisor, y / divisor);
+	}
 	/**
 	 * Create a point by multiplying a point by the (int) @p multiplier value.
 	 */
-	Point operator*(int multiplier) const { return Point(x * multiplier, y * multiplier); }
+	Point operator*(int multiplier) const {
+		return Point(x * multiplier, y * multiplier);
+	}
 	/**
 	 * Create a point by dividing a point by the (double) @p divisor value.
 	 */
-	Point operator/(double divisor) const { return Point((int16)(x / divisor), (int16)(y / divisor)); }
+	Point operator/(double divisor) const {
+		return Point((int16)(x / divisor), (int16)(y / divisor));
+	}
 	/**
 	 * Create a point by multiplying a point by the (double) @p multiplier value.
 	 */
-	Point operator*(double multiplier) const { return Point((int16)(x * multiplier), (int16)(y * multiplier)); }
+	Point operator*(double multiplier) const {
+		return Point((int16)(x * multiplier), (int16)(y * multiplier));
+	}
 
 	/**
 	 * Change a point's position by adding @p delta to its x and y coordinates.
@@ -104,7 +120,7 @@ struct Point {
 	/**
 	 * Return the square of the distance between this point and the point @p p.
 	 *
-	 * @param p		The other point.
+	 * @param p     The other point.
 	 * @return      The distance between this and @p p.
 	 */
 	uint sqrDist(const Point &p) const {
@@ -120,8 +136,12 @@ struct Point {
 	}
 };
 
-static inline Point operator*(int multiplier, const Point &p) { return Point(p.x * multiplier, p.y * multiplier); }
-static inline Point operator*(double multiplier, const Point &p) { return Point((int16)(p.x * multiplier), (int16)(p.y * multiplier)); }
+static inline Point operator*(int multiplier, const Point &p) {
+	return Point(p.x * multiplier, p.y * multiplier);
+}
+static inline Point operator*(double multiplier, const Point &p) {
+	return Point((int16)(p.x * multiplier), (int16)(p.y * multiplier));
+}
 
 /**
  * Simple class for handling a rectangular zone.
@@ -142,8 +162,8 @@ static inline Point operator*(double multiplier, const Point &p) { return Point(
  * When writing code using our Rect class, always keep this principle in mind!
 */
 struct Rect {
-	int16 top, left;		/*!< The point at the top left of the rectangle (part of the Rect). */
-	int16 bottom, right;	/*!< The point at the bottom right of the rectangle (not part of the Rect). */
+	int16 top, left;        /*!< The point at the top left of the rectangle (part of the Rect). */
+	int16 bottom, right;    /*!< The point at the bottom right of the rectangle (not part of the Rect). */
 
 	constexpr Rect() : top(0), left(0), bottom(0), right(0) {}
 	/**
@@ -180,17 +200,27 @@ struct Rect {
 	 *
 	 * @return True if the rectangles are identical, false otherwise.
 	 */
-	bool operator==(const Rect &rhs) const { return equals(rhs); }
+	bool operator==(const Rect &rhs) const {
+		return equals(rhs);
+	}
 	/**
 	 * Check if two rectangles are different.
 	 *
 	 * @return True if the rectangles are different, false otherwise.
 	 */
-	bool operator!=(const Rect &rhs) const { return !equals(rhs); }
+	bool operator!=(const Rect &rhs) const {
+		return !equals(rhs);
+	}
 
-	Common::Point origin() const { return Common::Point(left, top); } /*!< Return the origin of a rectangle. */
-	int16 width() const { return right - left; }                      /*!< Return the width of a rectangle. */
-	int16 height() const { return bottom - top; }                     /*!< Return the height of a rectangle. */
+	Common::Point origin() const {
+		return Common::Point(left, top);    /*!< Return the origin of a rectangle. */
+	}
+	int16 width() const {
+		return right - left;    /*!< Return the width of a rectangle. */
+	}
+	int16 height() const {
+		return bottom - top;    /*!< Return the height of a rectangle. */
+	}
 
 	void setWidth(int16 aWidth) {   /*!< Set the width to @p aWidth value. */
 		right = left + aWidth;
@@ -315,14 +345,14 @@ struct Rect {
 		else if (right < r.left) right = r.left;
 	}
 
-   	/**
+	/**
 	 * Reduce the dimensions of this rectangle by setting max width and max height.
 	 */
 	void clip(int16 maxw, int16 maxh) {
 		clip(Rect(0, 0, maxw, maxh));
 	}
 
-   	/**
+	/**
 	 * Check if the rectangle is empty (its width or length is 0) or invalid (its width or length are negative).
 	 *
 	 * @retval true  The rectangle is empty or invalid.
@@ -353,8 +383,10 @@ struct Rect {
 	 * Move the rectangle by the given delta x and y values.
 	 */
 	void translate(int16 dx, int16 dy) {
-		left += dx; right += dx;
-		top += dy; bottom += dy;
+		left += dx;
+		right += dx;
+		top += dy;
+		bottom += dy;
 	}
 
 	/**
@@ -364,36 +396,36 @@ struct Rect {
 		moveTo(p.x, p.y);
 	}
 
-	 /**
-	 * Print debug messages related to this class.
-	 */
+	/**
+	* Print debug messages related to this class.
+	*/
 	void debugPrint(int debuglevel = 0, const char *caption = "Rect:") const {
 		debug(debuglevel, "%s %d, %d, %d, %d", caption, left, top, right, bottom);
 	}
 
-	 /**
-	 * Print debug messages related to this class.
-	 */
+	/**
+	* Print debug messages related to this class.
+	*/
 	void debugPrintC(int debuglevel, uint32 debugChannel, const char *caption = "Rect:") const {
 		debugC(debuglevel, debugChannel, "%s %d, %d, %d, %d", caption, left, top, right, bottom);
 	}
 
-  /**
-  * Create a rectangle around the given center.
-  * @note The center point is rounded up and left when given an odd width and height.
-  */
+	/**
+	* Create a rectangle around the given center.
+	* @note The center point is rounded up and left when given an odd width and height.
+	*/
 	static Rect center(int16 cx, int16 cy, int16 w, int16 h) {
 		int x = cx - w / 2, y = cy - h / 2;
 		return Rect(x, y, x + w, y + h);
 	}
 
-  /**
-  * Return a Point indicating the centroid of the rectangle
-  * @note The center point is rounded up and left when width and/or height are odd
-  */
-  Point center() const {
-    return Point((left+right)/2, (bottom+top)/2);
-  }	
+	/**
+	* Return a Point indicating the centroid of the rectangle
+	* @note The center point is rounded up and left when width and/or height are odd
+	*/
+	Point center() const {
+		return Point((left + right) / 2, (bottom + top) / 2);
+	}
 
 	/**
 	 * Given target surface with size clip, this function ensures that


Commit: 430e4f9e22acecd6daa823238507ae2ca04e7e44
    https://github.com/scummvm/scummvm/commit/430e4f9e22acecd6daa823238507ae2ca04e7e44
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:59+02:00

Commit Message:
ZVISION: Code formatting & convention compliance.
Ensure all member variables are prefixed with an underscore.
Ensure all type names start with upper case.

Changed paths:
    engines/zvision/common/focus_list.h
    engines/zvision/common/scroller.cpp
    engines/zvision/common/scroller.h
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/effects/music_effect.h
    engines/zvision/scripting/menu.cpp
    engines/zvision/scripting/menu.h
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/scripting/script_manager.h
    engines/zvision/sound/midi.cpp
    engines/zvision/sound/midi.h
    engines/zvision/sound/volume_manager.cpp
    engines/zvision/sound/volume_manager.h
    engines/zvision/text/subtitle_manager.cpp
    engines/zvision/text/subtitle_manager.h
    engines/zvision/zvision.cpp


diff --git a/engines/zvision/common/focus_list.h b/engines/zvision/common/focus_list.h
index 99ff4961891..3ea6955103b 100644
--- a/engines/zvision/common/focus_list.h
+++ b/engines/zvision/common/focus_list.h
@@ -27,60 +27,60 @@
 template<typename T>
 class FocusList {
 private:
-	Common::Array<T> focus;
-	typedef uint _size_type;  //TODO - find a way to make this typedef inherit from the definition in Common::Array
+	Common::Array<T> _focus;
+	typedef uint SizeType;  //TODO - find a way to make this typedef inherit from the definition in Common::Array
 public:
 	void set(T currentFocus) {
-		if (!focus.size())
-			focus.push_back(currentFocus);
+		if (!_focus.size())
+			_focus.push_back(currentFocus);
 		else {
-			if (focus.front() != currentFocus) {
+			if (_focus.front() != currentFocus) {
 				Common::Array<T> buffer;
-				while (focus.size() > 0) {
-					if (focus.back() != currentFocus)
-						buffer.push_back(focus.back());
-					focus.pop_back();
+				while (_focus.size() > 0) {
+					if (_focus.back() != currentFocus)
+						buffer.push_back(_focus.back());
+					_focus.pop_back();
 				}
-				focus.push_back(currentFocus);
+				_focus.push_back(currentFocus);
 				while (buffer.size() > 0) {
-					focus.push_back(buffer.back());
+					_focus.push_back(buffer.back());
 					buffer.pop_back();
 				}
 			}
 		}
 	}
 
-	T get(_size_type idx = 0) {
-		return focus[idx];
+	T get(SizeType idx = 0) {
+		return _focus[idx];
 	}
 
 	T front() {
-		return focus.front();
+		return _focus.front();
 	}
 
-	T &operator[](_size_type idx) {
-		assert(idx < focus.size());
-		return focus[idx];
+	T &operator[](SizeType idx) {
+		assert(idx < _focus.size());
+		return _focus[idx];
 	}
 
-	_size_type size() {
-		return focus.size();
+	SizeType size() {
+		return _focus.size();
 	}
 
 	void clear() {
-		focus.clear();
+		_focus.clear();
 	}
 
 	void remove(T value) {
-		if (focus.size()) {
+		if (_focus.size()) {
 			Common::Array<T> buffer;
-			while (focus.size() > 0) {
-				if (focus.back() != value)
-					buffer.push_back(focus.back());
-				focus.pop_back();
+			while (_focus.size() > 0) {
+				if (_focus.back() != value)
+					buffer.push_back(_focus.back());
+				_focus.pop_back();
 			}
 			while (buffer.size() > 0) {
-				focus.push_back(buffer.back());
+				_focus.push_back(buffer.back());
 				buffer.pop_back();
 			}
 		}
diff --git a/engines/zvision/common/scroller.cpp b/engines/zvision/common/scroller.cpp
index bfd1c6491fd..c5a1b106050 100644
--- a/engines/zvision/common/scroller.cpp
+++ b/engines/zvision/common/scroller.cpp
@@ -24,11 +24,11 @@
 namespace ZVision {
 
 LinearScroller::LinearScroller(const int16 activePos, const int16 idlePos, const int16 period) :
-	Pos(idlePos),
-	prevPos(idlePos),
+	_pos(idlePos),
+	_prevPos(idlePos),
 	_activePos(activePos),
 	_idlePos(idlePos),
-	deltaPos((int16)(activePos - idlePos)),
+	_deltaPos((int16)(activePos - idlePos)),
 	_period(period) {
 }
 
@@ -36,7 +36,7 @@ LinearScroller::~LinearScroller() {
 }
 
 bool LinearScroller::update(uint32 deltatime) {
-	prevPos = Pos;
+	_prevPos = _pos;
 	if (_period != 0) {
 		int16 targetPos;
 		float dPos = 0;
@@ -44,10 +44,10 @@ bool LinearScroller::update(uint32 deltatime) {
 			targetPos = _activePos;
 		else
 			targetPos = _idlePos;
-		if (Pos != targetPos) {
-			dPos = (float)((int32)deltatime * (int32)deltaPos) / _period;
+		if (_pos != targetPos) {
+			dPos = (float)((int32)deltatime * (int32)_deltaPos) / _period;
 			if ((int16)dPos == 0) {
-				if (deltaPos > 0)
+				if (_deltaPos > 0)
 					dPos = 1;
 				else
 					dPos = -1;
@@ -55,23 +55,23 @@ bool LinearScroller::update(uint32 deltatime) {
 		}
 		if (!_active)
 			dPos = -dPos;
-		Pos += (int16)dPos;
-		if ((dPos == 0) || ((dPos > 0) && (Pos > targetPos)) || ((dPos < 0) && (Pos < targetPos)))
-			Pos = targetPos;
-		moving = (Pos != targetPos);
+		_pos += (int16)dPos;
+		if ((dPos == 0) || ((dPos > 0) && (_pos > targetPos)) || ((dPos < 0) && (_pos < targetPos)))
+			_pos = targetPos;
+		_moving = (_pos != targetPos);
 	} else {
 		if (_active)
-			Pos = _activePos;
+			_pos = _activePos;
 		else
-			Pos = _idlePos;
-		moving = false;
+			_pos = _idlePos;
+		_moving = false;
 	}
-	return (Pos != prevPos);  //True if redraw necessary
+	return (_pos != _prevPos);  //True if redraw necessary
 }
 
 void LinearScroller::reset() {
 	setActive(false);
-	Pos = _idlePos;
+	_pos = _idlePos;
 }
 
 void LinearScroller::setActive(bool active) {
@@ -79,43 +79,43 @@ void LinearScroller::setActive(bool active) {
 }
 
 bool LinearScroller::isMoving() {
-	return moving;
+	return _moving;
 }
 
 
 Scroller::Scroller(const Common::Point &activePos, const Common::Point &idlePos, int16 period) :
-	Xscroller(activePos.x, idlePos.x, period),
-	Yscroller(activePos.y, idlePos.y, period) {
-	Pos.x = Xscroller.Pos;
-	Pos.y = Yscroller.Pos;
+	_xScroller(activePos.x, idlePos.x, period),
+	_yScroller(activePos.y, idlePos.y, period) {
+	_pos.x = _xScroller._pos;
+	_pos.y = _yScroller._pos;
 }
 
 Scroller::~Scroller() {
 }
 
 void Scroller::reset() {
-	Xscroller.reset();
-	Yscroller.reset();
+	_xScroller.reset();
+	_yScroller.reset();
 };
 
 
 void Scroller::setActive(bool active) {
-	Xscroller.setActive(active);
-	Yscroller.setActive(active);
+	_xScroller.setActive(active);
+	_yScroller.setActive(active);
 }
 
 bool Scroller::isMoving() {
-	return Xscroller.isMoving() | Yscroller.isMoving();
+	return _xScroller.isMoving() | _yScroller.isMoving();
 }
 
 bool Scroller::update(uint32 deltatime) {
 	bool redraw = false;
-	if (Xscroller.update(deltatime))
+	if (_xScroller.update(deltatime))
 		redraw = true;
-	if (Yscroller.update(deltatime))
+	if (_yScroller.update(deltatime))
 		redraw = true;
-	Pos.x = Xscroller.Pos;
-	Pos.y = Yscroller.Pos;
+	_pos.x = _xScroller._pos;
+	_pos.y = _yScroller._pos;
 	return (redraw);
 }
 
diff --git a/engines/zvision/common/scroller.h b/engines/zvision/common/scroller.h
index c2883056d1a..f645692e0d2 100644
--- a/engines/zvision/common/scroller.h
+++ b/engines/zvision/common/scroller.h
@@ -37,15 +37,15 @@ public:
 	bool isMoving();
 	int16 getPos();
 
-	int16 Pos;
-	int16 prevPos;
+	int16 _pos;
+	int16 _prevPos;
 
 private:
 	bool _active = false;
-	bool moving = false;
+	bool _moving = false;
 	const int16 _activePos;
 	const int16 _idlePos;
-	const int16 deltaPos;
+	const int16 _deltaPos;
 	const int16 _period;
 };
 
@@ -57,10 +57,11 @@ public:
 	bool update(uint32 deltatime);  //Calculate updated position of scrolled graphics; return true if redraw is necessary.
 	void setActive(bool active);
 	bool isMoving();
-	Common::Point Pos;
+	
+	Common::Point _pos;
 
 private:
-	LinearScroller Xscroller, Yscroller;
+	LinearScroller _xScroller, _yScroller;
 };
 
 } // End of namespace ZVision
diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index a17607f74eb..1a53e5fcb97 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -46,19 +46,19 @@ RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const G
 	: _engine(engine),
 	  _system(engine->_system),
 	  _layout(layout),
-	  _screenArea(_layout.screenArea),
-	  _workingArea(_layout.workingArea),
+	  _screenArea(layout.screenArea),
+	  _workingArea(layout.workingArea),
 	  _workingAreaCenter(Common::Point(_workingArea.width() / 2, _workingArea.height() / 2)),
-	  _textArea(_layout.textArea),
-	  _menuArea(_layout.menuArea),
+	  _textArea(layout.textArea),
+	  _menuArea(layout.menuArea),
 	  _pixelFormat(pixelFormat),
 	  _backgroundWidth(0),
 	  _backgroundHeight(0),
 	  _backgroundOffset(0),
-	  _renderTable(engine, _layout.workingArea.width(), _layout.workingArea.height(), pixelFormat),
+	  _renderTable(engine, layout.workingArea.width(), layout.workingArea.height(), pixelFormat),
 	  _doubleFPS(doubleFPS),
 	  _widescreen(widescreen),
-	  frameLimiter(engine->_system, doubleFPS ? 60 : 30) {
+	  _frameLimiter(engine->_system, doubleFPS ? 60 : 30) {
 	debug(1, "creating render manager");
 	//Define graphics modes & screen subarea geometry
 	Graphics::ModeList modes;
@@ -163,7 +163,7 @@ void RenderManager::initialize(bool hiRes) {
 	//Set hardware/window resolution
 	debug(1, "_screen.w = %d, _screen.h = %d", _screen.w, _screen.h);
 	initGraphics(_screen.w, _screen.h, &_engine->_screenPixelFormat);
-	frameLimiter.initialize();
+	_frameLimiter.initialize();
 	debug(1, "Render manager initialized");
 }
 
@@ -214,23 +214,23 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
 			debug(5, "Rendering panorama");
 			if (!_backgroundSurfaceDirtyRect.isEmpty()) {
 				_renderTable.mutateImage(&_warpedSceneSurface, inputSurface, _engine->getScriptManager()->getStateValue(StateKey_HighQuality));
-				outputSurface = &_warpedSceneSurface;
+				_outputSurface = &_warpedSceneSurface;
 				outWndDirtyRect = Common::Rect(_workingArea.width(), _workingArea.height());
 			}
 			break;
 		default:
-			outputSurface = inputSurface;
+			_outputSurface = inputSurface;
 			outWndDirtyRect = _backgroundSurfaceDirtyRect;
 			break;
 			debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
 		}
 		debug(5, "Rendering working area");
-		_workingManagedSurface.simpleBlitFrom(*outputSurface); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
+		_workingManagedSurface.simpleBlitFrom(*_outputSurface); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
 		debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
 	}
 	if (preStream) {
 		debug(5, "Pre-rendering text area for video stream");
-		_workingManagedSurface.simpleBlitFrom(*outputSurface, _textOverlay, _textOverlay.origin()); //Prevents subtitle visual corruption when streaming videos that don't fully overlap them, e.g. Nemesis sarcophagi
+		_workingManagedSurface.simpleBlitFrom(*_outputSurface, _textOverlay, _textOverlay.origin()); //Prevents subtitle visual corruption when streaming videos that don't fully overlap them, e.g. Nemesis sarcophagi
 		return false;
 	} else {
 		debug(5, "Rendering menu");
@@ -240,15 +240,15 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
 		_textManagedSurface.transBlitFrom(_textSurface, -1);
 		debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
 		if (immediate) {
-			frameLimiter.startFrame();
+			_frameLimiter.startFrame();
 			debug(5, "Updating screen, immediate");
 			_screen.update();
 			debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
 			debug(10, "~renderSceneToScreen, immediate");
 			return true;
 		} else if (_engine->canRender()) {
-			frameLimiter.delayBeforeSwap();
-			frameLimiter.startFrame();
+			_frameLimiter.delayBeforeSwap();
+			_frameLimiter.startFrame();
 			debug(5, "Updating screen, frame limited");
 			_screen.update();
 			debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
@@ -996,7 +996,7 @@ void RenderManager::bkgFill(uint8 r, uint8 g, uint8 b) {
 void RenderManager::updateRotation() {
 	int16 _velocity = _engine->getMouseVelocity() + _engine->getKeyboardVelocity();
 	ScriptManager *scriptManager = _engine->getScriptManager();
-	if (_doubleFPS | !frameLimiter.isEnabled()) //Assuming 60fps when in Vsync mode.
+	if (_doubleFPS | !_frameLimiter.isEnabled()) //Assuming 60fps when in Vsync mode.
 		_velocity /= 2;
 	if (_velocity) {
 		switch (_renderTable.getRenderState()) {
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index b02a1413ab0..79144a7ba57 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -62,7 +62,7 @@ private:
 	const Graphics::PixelFormat _pixelFormat;
 	const ScreenLayout _layout;
 	bool _hiRes = false;
-	Graphics::FrameLimiter frameLimiter;
+	Graphics::FrameLimiter _frameLimiter;
 
 	/**
 	 * A Rectangle representing the screen/window resolution.
@@ -155,7 +155,7 @@ private:
 	EffectsList _effects;
 
 	//Pointer to currently active backbuffer output surface
-	Graphics::Surface *outputSurface;
+	Graphics::Surface *_outputSurface;
 
 	bool _doubleFPS;
 	bool _widescreen;
diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index 8460a4bc4e8..038f8719c7d 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -41,10 +41,10 @@ RenderTable::RenderTable(ZVision *engine, uint numColumns, uint numRows, const G
 	_internalBuffer = new FilterPixel[numRows * numColumns];
 	memset(&_panoramaOptions, 0, sizeof(_panoramaOptions));
 	memset(&_tiltOptions, 0, sizeof(_tiltOptions));
-	halfRows = floor((_numRows - 1) / 2);
-	halfColumns = floor((_numColumns - 1) / 2);
-	halfWidth = (float)_numColumns / 2.0f - 0.5f;
-	halfHeight = (float)_numRows / 2.0f - 0.5f;
+	_halfRows = floor((_numRows - 1) / 2);
+	_halfColumns = floor((_numColumns - 1) / 2);
+	_halfWidth = (float)_numColumns / 2.0f - 0.5f;
+	_halfHeight = (float)_numRows / 2.0f - 0.5f;
 }
 
 RenderTable::~RenderTable() {
@@ -80,10 +80,10 @@ const Common::Point RenderTable::convertWarpedCoordToFlatCoord(const Common::Poi
 		int16 y = CLIP<int16>(point.y, 0, (int16)_numRows);
 		return Common::Point(x, y);
 	}
-	index = point.y * _numColumns + point.x;
+	_index = point.y * _numColumns + point.x;
 	Common::Point newPoint(point);
-	newPoint.x += (_internalBuffer[index].xDir ? _internalBuffer[index].Src.right : _internalBuffer[index].Src.left);
-	newPoint.y += (_internalBuffer[index].yDir ? _internalBuffer[index].Src.bottom : _internalBuffer[index].Src.top);
+	newPoint.x += (_internalBuffer[_index]._xDir ? _internalBuffer[_index]._Src.right : _internalBuffer[_index]._Src.left);
+	newPoint.y += (_internalBuffer[_index]._yDir ? _internalBuffer[_index]._Src.bottom : _internalBuffer[_index]._Src.top);
 	return newPoint;
 }
 
@@ -100,8 +100,8 @@ void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 d
               uint32 normalizedX = x - subRect.left;
               uint32 index = sourceOffset + x;
               // RenderTable only stores offsets from the original coordinates
-              sourceYIndex = y + _internalBuffer[index].Src.top;
-              sourceXIndex = x + _internalBuffer[index].Src.left;
+              sourceYIndex = y + _internalBuffer[index]._Src.top;
+              sourceXIndex = x + _internalBuffer[index]._Src.left;
               destBuffer[destOffset + normalizedX] = sourceBuffer[sourceYIndex * _numColumns + sourceXIndex];
           }
           destOffset += destWidth;
@@ -114,8 +114,8 @@ void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 d
               uint32 normalizedX = x - subRect.left;
               uint32 index = sourceOffset + x;
               // RenderTable only stores offsets from the original coordinates
-              sourceYIndex = y + _internalBuffer[index].Src.top;
-              sourceXIndex = x + _internalBuffer[index].Src.left;
+              sourceYIndex = y + _internalBuffer[index]._Src.top;
+              sourceXIndex = x + _internalBuffer[index]._Src.left;
               destBuffer[destOffset + normalizedX] = sourceBuffer[sourceYIndex * _numColumns + sourceXIndex];
           }
           destOffset += destWidth;
@@ -125,7 +125,7 @@ void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 d
 //*/
 
 void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf, bool highQuality) {
-	destOffset = 0;
+	_destOffset = 0;
 	uint16 *sourceBuffer = (uint16 *)srcBuf->getPixels();
 	uint16 *destBuffer = (uint16 *)dstBuf->getPixels();
 	if (highQuality != _highQuality) {
@@ -137,27 +137,27 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 		//Apply bilinear interpolation
 		FilterPixel _curP;
 		for (int16 y = 0; y < srcBuf->h; ++y) {
-			sourceOffset = y * _numColumns;
+			_sourceOffset = y * _numColumns;
 			for (int16 x = 0; x < srcBuf->w; ++x) {
-				_curP = _internalBuffer[sourceOffset + x];
-				srcIndexYT = y + _curP.Src.top;
-				srcIndexYB = y + _curP.Src.bottom;
-				srcIndexXL = x + _curP.Src.left;
-				srcIndexXR = x + _curP.Src.right;
-				splitColor(sourceBuffer[srcIndexYT * _numColumns + srcIndexXL], rTL, gTL, bTL);
-				splitColor(sourceBuffer[srcIndexYT * _numColumns + srcIndexXR], rTR, gTR, bTR);
-				splitColor(sourceBuffer[srcIndexYB * _numColumns + srcIndexXL], rBL, gBL, bBL);
-				splitColor(sourceBuffer[srcIndexYB * _numColumns + srcIndexXR], rBR, gBR, bBR);
-				rF = _curP.fTL * rTL + _curP.fTR * rTR + _curP.fBL * rBL + _curP.fBR * rBR;
-				gF = _curP.fTL * gTL + _curP.fTR * gTR + _curP.fBL * gBL + _curP.fBR * gBR;
-				bF = _curP.fTL * bTL + _curP.fTR * bTR + _curP.fBL * bBL + _curP.fBR * bBR;
-				destBuffer[destOffset] = mergeColor(rF, gF, bF);
-				destOffset++;
+				_curP = _internalBuffer[_sourceOffset + x];
+				_srcIndexYT = y + _curP._Src.top;
+				_srcIndexYB = y + _curP._Src.bottom;
+				_srcIndexXL = x + _curP._Src.left;
+				_srcIndexXR = x + _curP._Src.right;
+				splitColor(sourceBuffer[_srcIndexYT * _numColumns + _srcIndexXL], _rTL, _gTL, _bTL);
+				splitColor(sourceBuffer[_srcIndexYT * _numColumns + _srcIndexXR], _rTR, _gTR, _bTR);
+				splitColor(sourceBuffer[_srcIndexYB * _numColumns + _srcIndexXL], _rBL, _gBL, _bBL);
+				splitColor(sourceBuffer[_srcIndexYB * _numColumns + _srcIndexXR], _rBR, _gBR, _bBR);
+				_rF = _curP._fTL * _rTL + _curP._fTR * _rTR + _curP._fBL * _rBL + _curP._fBR * _rBR;
+				_gF = _curP._fTL * _gTL + _curP._fTR * _gTR + _curP._fBL * _gBL + _curP._fBR * _gBR;
+				_bF = _curP._fTL * _bTL + _curP._fTR * _bTR + _curP._fBL * _bBL + _curP._fBR * _bBR;
+				destBuffer[_destOffset] = mergeColor(_rF, _gF, _bF);
+				_destOffset++;
 				/*/
 				if(Common::Point(x,y)==testPixel) {
 				debug(2,"\tMutated test pixel %d, %d", x, y);
-				debug(2,"\tfX: %f, fY: %f", _curP.fX, _curP.fY);
-				debug(2,"\tYT: %d, YB: %d, XL: %d XR: %d", srcIndexYT, srcIndexYB, srcIndexXL, srcIndexXR);
+				debug(2,"\t_fX: %f, _fY: %f", _curP._fX, _curP._fY);
+				debug(2,"\tYT: %d, YB: %d, XL: %d XR: %d", _srcIndexYT, _srcIndexYB, _srcIndexXL, _srcIndexXR);
 				}
 				//*/
 			}
@@ -165,14 +165,14 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 	} else {
 		//Apply nearest-neighbour interpolation
 		for (int16 y = 0; y < srcBuf->h; ++y) {
-			sourceOffset = y * _numColumns;
+			_sourceOffset = y * _numColumns;
 			for (int16 x = 0; x < srcBuf->w; ++x) {
-				index = sourceOffset + x;
+				_index = _sourceOffset + x;
 				// RenderTable only stores offsets from the original coordinates
-				srcIndexXL = x + (_internalBuffer[index].xDir ? _internalBuffer[index].Src.right : _internalBuffer[index].Src.left);
-				srcIndexYT = y + (_internalBuffer[index].yDir ? _internalBuffer[index].Src.bottom : _internalBuffer[index].Src.top);
-				destBuffer[destOffset] = sourceBuffer[srcIndexYT * _numColumns + srcIndexXL];
-				destOffset++;
+				_srcIndexXL = x + (_internalBuffer[_index]._xDir ? _internalBuffer[_index]._Src.right : _internalBuffer[_index]._Src.left);
+				_srcIndexYT = y + (_internalBuffer[_index]._yDir ? _internalBuffer[_index]._Src.bottom : _internalBuffer[_index]._Src.top);
+				destBuffer[_destOffset] = sourceBuffer[_srcIndexYT * _numColumns + _srcIndexXL];
+				_destOffset++;
 			}
 		}
 	}
@@ -199,8 +199,8 @@ void RenderTable::generateRenderTable() {
 
 void RenderTable::generateLookupTable(bool tilt) {
 	debug(1, "Generating %s lookup table.", tilt ? "tilt" : "panorama");
-	debug(5, "halfWidth %f, halfHeight %f", halfWidth, halfHeight);
-	debug(5, "halfRows %d, halfColumns %d", halfRows, halfColumns);
+	debug(5, "_halfWidth %f, _halfHeight %f", _halfWidth, _halfHeight);
+	debug(5, "_halfRows %d, _halfColumns %d", _halfRows, _halfColumns);
 	uint32 generationTime = _system->getMillis();
 	float alpha, cosAlpha, polarCoordInCylinderCoords, linearCoordInCylinderCoords, cylinderRadius, xOffset, yOffset;
 	uint32 indexTL, indexBL, indexTR, indexBR;
@@ -243,37 +243,37 @@ void RenderTable::generateLookupTable(bool tilt) {
 	};
 	if (tilt) {
 		uint32 columnIndexTL, columnIndexBL, columnIndexTR, columnIndexBR;
-		cylinderRadius = (halfWidth + 0.5f) / tan(_tiltOptions.verticalFOV);
-		_tiltOptions.gap = cylinderRadius * atan2((float)(halfHeight / cylinderRadius), 1.0f) * _tiltOptions.linearScale;
-		for (y = 0; y <= halfRows; ++y) {
-			outerLoop(y, halfHeight, _tiltOptions.linearScale);
+		cylinderRadius = (_halfWidth + 0.5f) / tan(_tiltOptions.verticalFOV);
+		_tiltOptions.gap = cylinderRadius * atan2((float)(_halfHeight / cylinderRadius), 1.0f) * _tiltOptions.linearScale;
+		for (y = 0; y <= _halfRows; ++y) {
+			outerLoop(y, _halfHeight, _tiltOptions.linearScale);
 			columnIndexTL = y * _numColumns;
 			columnIndexBL = (_numRows - (y + 1)) * _numColumns;
 			columnIndexTR = columnIndexTL + (_numColumns - 1);
 			columnIndexBR = columnIndexBL + (_numColumns - 1);
-			for (x = 0; x <= halfColumns; ++x) {
+			for (x = 0; x <= _halfColumns; ++x) {
 				indexTL = columnIndexTL + x;
 				indexBL = columnIndexBL + x;
 				indexTR = columnIndexTR - x;
 				indexBR = columnIndexBR - x;
-				innerLoop(y, x, halfWidth, yOffset, xOffset);
+				innerLoop(y, x, _halfWidth, yOffset, xOffset);
 			}
 		}
 	} else {
 		uint32 rowIndexT, rowIndexB, columnIndexL, columnIndexR;
-		cylinderRadius = (halfHeight + 0.5f) / tan(_panoramaOptions.verticalFOV);
-		for (x = 0; x <= halfColumns; ++x) {
+		cylinderRadius = (_halfHeight + 0.5f) / tan(_panoramaOptions.verticalFOV);
+		for (x = 0; x <= _halfColumns; ++x) {
 			columnIndexL = x;
 			columnIndexR = (_numColumns - 1) - x;
 			rowIndexT = 0;
 			rowIndexB = _numColumns * (_numRows - 1);
-			outerLoop(x, halfWidth, _panoramaOptions.linearScale);
-			for (y = 0; y <= halfRows; ++y) {
+			outerLoop(x, _halfWidth, _panoramaOptions.linearScale);
+			for (y = 0; y <= _halfRows; ++y) {
 				indexTL = rowIndexT + columnIndexL;
 				indexBL = rowIndexB + columnIndexL;
 				indexTR = rowIndexT + columnIndexR;
 				indexBR = rowIndexB + columnIndexR;
-				innerLoop(x, y, halfHeight, xOffset, yOffset);
+				innerLoop(x, y, _halfHeight, xOffset, yOffset);
 				rowIndexT += _numColumns;
 				rowIndexB -= _numColumns;
 			}
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index 8ec49d46a81..99b339674cb 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -32,55 +32,55 @@ namespace ZVision {
 class FilterPixel {
 public:
 	//Bitfields representing sequential direction of contraction
-	bool xDir = 0; //0 left, 1 right
-	bool yDir = 0; //0 up, 1 down
-	Common::Rect Src = Common::Rect(0, 0); //Coordinates of four panorama image pixels around actual working window pixel
+	bool _xDir = 0; //0 left, 1 right
+	bool _yDir = 0; //0 up, 1 down
+	Common::Rect _Src = Common::Rect(0, 0); //Coordinates of four panorama image pixels around actual working window pixel
 
-	float fX, fY, fTL, fTR, fBL, fBR;
+	float _fX, _fY, _fTL, _fTR, _fBL, _fBR;
 
 //  bool _printDebug = false;
 
 	FilterPixel() {};
 //  FilterPixel(float x, float y, bool highQuality=false, bool printDebug=false) {
 	FilterPixel(float x, float y, bool highQuality = false) {
-		Src.left = int16(floor(x));
-		Src.right = int16(ceil(x));
-		Src.top = int16(floor(y));
-		Src.bottom = int16(ceil(y));
+		_Src.left = int16(floor(x));
+		_Src.right = int16(ceil(x));
+		_Src.top = int16(floor(y));
+		_Src.bottom = int16(ceil(y));
 		/*
 		      _printDebug = printDebug;
 		    if(_printDebug)
 		      debug(5,"\tTarget pixel offset: %f, %f", x, y);
 		*/
 		if (highQuality) {
-			fX = x - (float)Src.left;
-			fY = y - (float)Src.top;
-			fTL = (1 - fX) * (1 - fY);
-			fTR = fX * (1 - fY);
-			fBL = (1 - fX) * fY;
-			fBR = fX * fY;
+			_fX = x - (float)_Src.left;
+			_fY = y - (float)_Src.top;
+			_fTL = (1 - _fX) * (1 - _fY);
+			_fTR = _fX * (1 - _fY);
+			_fBL = (1 - _fX) * _fY;
+			_fBR = _fX * _fY;
 			/*
 			      if(_printDebug)
-			        debug(5,"fX: %f, fY: %f, fTL:%f, fTR:%f, fBL:%f, fBR:%f", fX, fY, fTL, fTR, fBL, fBR);
+			        debug(5,"_fX: %f, _fY: %f, _fTL:%f, _fTR:%f, _fBL:%f, _fBR:%f", _fX, _fY, _fTL, _fTR, _fBL, _fBR);
 			*/
 		} else {
 			//Nearest neighbour
-			xDir = (x - Src.left) > 0.5f;
-			yDir = (y - Src.top) > 0.5f;
+			_xDir = (x - _Src.left) > 0.5f;
+			_yDir = (y - _Src.top) > 0.5f;
 			/*
 			      if(_printDebug)
-			        debug(5,"\tNearest neighbour, xDir: 0x%X, yDir: 0x%X", xDir, yDir);
+			        debug(5,"\tNearest neighbour, _xDir: 0x%X, _yDir: 0x%X", _xDir, _yDir);
 			*/
 		}
 	};
 	~FilterPixel() {};
 	inline void flipH() {
-		Src.left = -Src.left;
-		Src.right = -Src.right;
+		_Src.left = -_Src.left;
+		_Src.right = -_Src.right;
 	};
 	inline void flipV() {
-		Src.top = -Src.top;
-		Src.bottom = -Src.bottom;
+		_Src.top = -_Src.top;
+		_Src.bottom = -_Src.bottom;
 	};
 };
 
@@ -101,19 +101,19 @@ public:
 private:
 	ZVision *_engine;
 	OSystem *_system;
-	uint _numRows, _numColumns, halfRows, halfColumns; //Working area width, height; half width, half height, in whole pixels
-	float halfWidth, halfHeight;  //Centre axis to midpoint of outermost pixel
+	uint _numRows, _numColumns, _halfRows, _halfColumns; //Working area width, height; half width, half height, in whole pixels
+	float _halfWidth, _halfHeight;  //Centre axis to midpoint of outermost pixel
 	FilterPixel *_internalBuffer;
 	RenderState _renderState;
 	bool _highQuality = false;
 	const Graphics::PixelFormat _pixelFormat;
 
-	uint32 index;
-	uint32 sourceOffset, destOffset;
-	uint32 srcIndexXL, srcIndexXR, srcIndexYT, srcIndexYB;
-	uint32 rTL, rTR, rBL, rBR, rF;
-	uint32 gTL, gTR, gBL, gBR, gF;
-	uint32 bTL, bTR, bBL, bBR, bF;
+	uint32 _index;
+	uint32 _sourceOffset, _destOffset;
+	uint32 _srcIndexXL, _srcIndexXR, _srcIndexYT, _srcIndexYB;
+	uint32 _rTL, _rTR, _rBL, _rBR, _rF;
+	uint32 _gTL, _gTR, _gBL, _gBR, _gF;
+	uint32 _bTL, _bTR, _bBL, _bBR, _bF;
 
 	inline void splitColor(uint16 &color, uint32 &r, uint32 &g, uint32 &b) {
 		//NB Left & right shifting unnecessary for interpolating & recombining, so not bothering in order to save cycles
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 7e1e30f26e9..877b1e7b5cb 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -59,10 +59,10 @@ void MusicNodeBASE::setBalance(int8 balance) {
 
 void MusicNodeBASE::updateMixer() {
 	if (_engine->getScriptManager()->getStateValue(StateKey_Qsound) >= 1)
-		volumeOut = _engine->getVolumeManager()->convert(_volume, _azimuth, _directionality);  //Apply game-specific volume profile and then attenuate according to azimuth
+		_volumeOut = _engine->getVolumeManager()->convert(_volume, _azimuth, _directionality);  //Apply game-specific volume profile and then attenuate according to azimuth
 	else
-//    volumeOut = _engine->getVolumeManager()->convert(_volume, kVolumeLinear);  //Apply linear volume profile and ignore azimuth
-		volumeOut = _engine->getVolumeManager()->convert(_volume);  //Apply game-specific volume profile and ignore azimuth
+//    _volumeOut = _engine->getVolumeManager()->convert(_volume, kVolumeLinear);  //Apply linear volume profile and ignore azimuth
+		_volumeOut = _engine->getVolumeManager()->convert(_volume);  //Apply game-specific volume profile and ignore azimuth
 	outputMixer();
 }
 
@@ -72,10 +72,10 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 	_volume = volume;
 	_balance = 0;
 	_fade = false;
-	fadeStartVol = volume;
-	fadeEndVol = 0;
-	fadeTime = 0;
-	fadeElapsed = 0;
+	_fadeStartVol = volume;
+	_fadeEndVol = 0;
+	_fadeTime = 0;
+	_fadeElapsed = 0;
 	_sub = 0;
 	_stereo = false;
 	_loaded = false;
@@ -128,14 +128,14 @@ MusicNode::~MusicNode() {
 
 void MusicNode::outputMixer() {
 	_engine->_mixer->setChannelBalance(_handle, _balance);
-	_engine->_mixer->setChannelVolume(_handle, volumeOut);
+	_engine->_mixer->setChannelVolume(_handle, _volumeOut);
 }
 
 void MusicNode::setFade(int32 time, uint8 target) {
-	fadeStartVol = _volume;
-	fadeEndVol = target;
-	fadeElapsed = 0;
-	fadeTime = time <= 0 ? 0 : (uint32)time;
+	_fadeStartVol = _volume;
+	_fadeEndVol = target;
+	_fadeElapsed = 0;
+	_fadeTime = time <= 0 ? 0 : (uint32)time;
 	_fade = true;
 }
 
@@ -144,17 +144,17 @@ bool MusicNode::process(uint32 deltaTimeInMillis) {
 		return stop();
 	else {
 		if (_fade) {
-			debug(3, "Fading music, endVol %d, startVol %d, current %d, fade time %d, elapsed time %dms", fadeEndVol, fadeStartVol, _volume, fadeTime, fadeElapsed);
+			debug(3, "Fading music, endVol %d, startVol %d, current %d, fade time %d, elapsed time %dms", _fadeEndVol, _fadeStartVol, _volume, _fadeTime, _fadeElapsed);
 			uint8 _newvol = 0;
-			fadeElapsed += deltaTimeInMillis;
-			if ((fadeTime <= 0) | (fadeElapsed >= fadeTime)) {
-				_newvol = fadeEndVol;
+			_fadeElapsed += deltaTimeInMillis;
+			if ((_fadeTime <= 0) | (_fadeElapsed >= _fadeTime)) {
+				_newvol = _fadeEndVol;
 				_fade = false;
 			} else {
-				if (fadeEndVol > fadeStartVol)
-					_newvol = fadeStartVol + (fadeElapsed * (fadeEndVol - fadeStartVol)) / fadeTime;
+				if (_fadeEndVol > _fadeStartVol)
+					_newvol = _fadeStartVol + (_fadeElapsed * (_fadeEndVol - _fadeStartVol)) / _fadeTime;
 				else
-					_newvol = fadeStartVol - (fadeElapsed * (fadeStartVol - fadeEndVol)) / fadeTime;
+					_newvol = _fadeStartVol - (_fadeElapsed * (_fadeStartVol - _fadeEndVol)) / _fadeTime;
 			}
 			if (_volume != _newvol)
 				setVolume(_newvol);
@@ -178,8 +178,8 @@ void MusicNode::setVolume(uint8 newVolume) {
 PanTrackNode::PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos, uint8 mag, bool resetMixerOnDelete, bool staticScreen)
 	: ScriptingEffect(engine, key, SCRIPTING_EFFECT_PANTRACK),
 	  _slot(slot),
-	  sourcePos(0),
-	  viewPos(0),
+	  _sourcePos(0),
+	  _viewPos(0),
 	  _mag(mag),
 	  _width(0),
 	  _pos(pos),
@@ -214,12 +214,12 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 				debug(3, "PanTrackNode in panorama mode");
 				_width = _engine->getRenderManager()->getBkgSize().x;
 				if (_width) {
-					sourcePos.setDegrees(360 * _pos / _width);
-					viewPos.setDegrees(360 * scriptManager->getStateValue(StateKey_ViewPos) / _width);
+					_sourcePos.setDegrees(360 * _pos / _width);
+					_viewPos.setDegrees(360 * scriptManager->getStateValue(StateKey_ViewPos) / _width);
 				} else {
 					warning("Encountered zero background width whilst processing PanTrackNode in panoramic mode!");
-					//sourcePos.setDegrees(0);
-					//viewPos.setDegrees(0);
+					//_sourcePos.setDegrees(0);
+					//_viewPos.setDegrees(0);
 				}
 				break;
 			case RenderTable::FLAT :
@@ -228,17 +228,17 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 			// fall through
 			default :
 				debug(3, "PanTrackNode in FLAT/TILT mode");
-				sourcePos.setDegrees(0);
-				viewPos.setDegrees(0);
+				_sourcePos.setDegrees(0);
+				_viewPos.setDegrees(0);
 				break;
 			} else {
 			//Used for auxiliary scripts only
-			sourcePos.setDegrees(_pos);
-			viewPos.setDegrees(0);
+			_sourcePos.setDegrees(_pos);
+			_viewPos.setDegrees(0);
 		}
 		Math::Angle azimuth;
-		azimuth = sourcePos - viewPos;
-		debug(3, "soundPos: %f, viewPos: %f, azimuth: %f, width %d", sourcePos.getDegrees(), viewPos.getDegrees(), azimuth.getDegrees(), _width);
+		azimuth = _sourcePos - _viewPos;
+		debug(3, "soundPos: %f, _viewPos: %f, azimuth: %f, width %d", _sourcePos.getDegrees(), _viewPos.getDegrees(), azimuth.getDegrees(), _width);
 		//azimuth is sound source position relative to player, clockwise from centre of camera axis to front when viewed top-down
 		mus->setDirection(azimuth, _mag);
 	}
@@ -285,7 +285,7 @@ void MusicMidiNode::setVolume(uint8 newVolume) {
 void MusicMidiNode::outputMixer() {
 	_engine->getMidiManager()->setBalance(_chan, _balance);
 	_engine->getMidiManager()->setPan(_chan, _pan);
-	_engine->getMidiManager()->setVolume(_chan, volumeOut);
+	_engine->getMidiManager()->setVolume(_chan, _volumeOut);
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/effects/music_effect.h b/engines/zvision/scripting/effects/music_effect.h
index 8fbcedaeab8..fa13bd60a78 100644
--- a/engines/zvision/scripting/effects/music_effect.h
+++ b/engines/zvision/scripting/effects/music_effect.h
@@ -63,7 +63,7 @@ protected:
 	int8 _balance = 0;
 	Math::Angle _azimuth;
 	uint8 _directionality;  //0 = fully ambient, 255 = fully directional
-	uint8 volumeOut = 0;
+	uint8 _volumeOut = 0;
 };
 
 class MusicNode : public MusicNodeBASE {
@@ -86,10 +86,10 @@ private:
 	void outputMixer() override;
 	bool _loop;
 	bool _fade;
-	uint8 fadeStartVol;
-	uint8 fadeEndVol;
-	uint32 fadeTime;
-	uint32 fadeElapsed; //Cumulative time since fade start
+	uint8 _fadeStartVol;
+	uint8 _fadeEndVol;
+	uint32 _fadeTime;
+	uint32 _fadeElapsed; //Cumulative time since fade start
 	bool _stereo;
 	Audio::SoundHandle _handle;
 	uint16 _sub;
@@ -130,7 +130,7 @@ public:
 private:
 	uint32 _slot;
 	int16 _width, _pos;
-	Math::Angle sourcePos, viewPos;
+	Math::Angle _sourcePos, _viewPos;
 	uint8 _mag;
 	bool _resetMixerOnDelete;
 	bool _staticScreen;
diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index 8c79de6a109..d0c5a2f2c89 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -37,66 +37,66 @@ enum {
 MenuManager::MenuManager(ZVision *engine, const Common::Rect menuArea, const MenuParams params) :
 	_engine(engine),
 	_params(params),
-	menuBarFlag(0xFFFF),
+	_menuBarFlag(0xFFFF),
 	_menuArea(menuArea),
-	menuOrigin(menuArea.origin()),
-	menuTriggerArea(menuOrigin, _menuArea.width(), _params.triggerHeight),
-	mainScroller(params.activePos, params.idlePos, params.period) {
+	_menuOrigin(menuArea.origin()),
+	_menuTriggerArea(_menuOrigin, _menuArea.width(), _params.triggerHeight),
+	_mainScroller(params.activePos, params.idlePos, params.period) {
 
-	enableFlags.set_size(6);
+	_enableFlags.set_size(6);
 	for (int8 i = 0; i < 4; i++) {
 		//Generate button hotspot areas
-		menuHotspots[i] = Common::Rect(_params.wxButs[i][1], _menuArea.top, _params.wxButs[i][1] + _params.wxButs[i][0], _menuArea.bottom);
+		_menuHotspots[i] = Common::Rect(_params.wxButs[i][1], _menuArea.top, _params.wxButs[i][1] + _params.wxButs[i][0], _menuArea.bottom);
 		//Initialise button animation frames
-		mainFrames[i] = _params.idleFrame;
+		_mainFrames[i] = _params.idleFrame;
 	}
 	for (int i = 0; i < 4; i++)
-		buttonAnim[i] = new LinearScroller(_params.activeFrame, _params.idleFrame, _params.buttonPeriod);
+		_buttonAnim[i] = new LinearScroller(_params.activeFrame, _params.idleFrame, _params.buttonPeriod);
 	setFocus(kFocusNone); //Ensure focus list is initialised
-	mainArea = Common::Rect(_params.wMain, hMainMenu);
-	mainArea.moveTo(menuOrigin + mainScroller.Pos);
+	_mainArea = Common::Rect(_params.wMain, _hMainMenu);
+	_mainArea.moveTo(_menuOrigin + _mainScroller._pos);
 }
 
 MenuManager::~MenuManager() {
 	for (int i = 0; i < 4; i++)
-		delete buttonAnim[i];
-	mainBack.free();
+		delete _buttonAnim[i];
+	_mainBack.free();
 }
 
 void MenuManager::setEnable(uint16 flags) {
 	static const uint16 flagMasks[6] = {0x8, 0x4, 0x2, 0x1, 0x100, 0x200}; //Enum order: save,restore,prefs,quit,items,magic
-	menuBarFlag = flags;
+	_menuBarFlag = flags;
 	for (uint i = 0; i <= 5; i++) {
-		if (menuBarFlag & flagMasks[i])
-			enableFlags.set(i);
+		if (_menuBarFlag & flagMasks[i])
+			_enableFlags.set(i);
 		else
-			enableFlags.unset(i);
+			_enableFlags.unset(i);
 	}
 }
 
 void MenuManager::onMouseUp(const Common::Point &Pos) {
-	if (menuFocus.front() == kFocusMain) {
-		mouseOnItem = mouseOverMain(Pos);
-		if (mouseOnItem == mainClicked)
+	if (_menuFocus.front() == kFocusMain) {
+		_mouseOnItem = mouseOverMain(Pos);
+		if (_mouseOnItem == _mainClicked)
 			//Activate clicked action from main menu
-			switch (mouseOnItem) {
+			switch (_mouseOnItem) {
 			case kMainMenuSave:
 				_engine->getScriptManager()->changeLocation('g', 'j', 's', 'e', 0);
 				setFocus(kFocusNone);
-				mainScroller.reset();
-				redraw = true;
+				_mainScroller.reset();
+				_redraw = true;
 				break;
 			case kMainMenuLoad:
 				_engine->getScriptManager()->changeLocation('g', 'j', 'r', 'e', 0);
 				setFocus(kFocusNone);
-				mainScroller.reset();
-				redraw = true;
+				_mainScroller.reset();
+				_redraw = true;
 				break;
 			case kMainMenuPrefs:
 				_engine->getScriptManager()->changeLocation('g', 'j', 'p', 'e', 0);
 				setFocus(kFocusNone);
-				mainScroller.reset();
-				redraw = true;
+				_mainScroller.reset();
+				_redraw = true;
 				break;
 			case kMainMenuExit:
 				_engine->ifQuit();
@@ -105,17 +105,17 @@ void MenuManager::onMouseUp(const Common::Point &Pos) {
 				break;
 			}
 	}
-	mainClicked = -1;
+	_mainClicked = -1;
 }
 
 void MenuManager::onMouseDown(const Common::Point &Pos) {
-	if (menuFocus.front() == kFocusMain) {
-		mouseOnItem = mouseOverMain(Pos);
+	if (_menuFocus.front() == kFocusMain) {
+		_mouseOnItem = mouseOverMain(Pos);
 		//Show clicked graphic
-		if ((mouseOnItem >= 0) && (mouseOnItem < 4))
-			if (enableFlags.get(mouseOnItem)) {
-				mainClicked = mouseOnItem;
-				redraw = true;
+		if ((_mouseOnItem >= 0) && (_mouseOnItem < 4))
+			if (_enableFlags.get(_mouseOnItem)) {
+				_mainClicked = _mouseOnItem;
+				_redraw = true;
 			}
 	}
 	debug(1, "mouse position %d %d", Pos.x, Pos.y);
@@ -124,64 +124,64 @@ void MenuManager::onMouseDown(const Common::Point &Pos) {
 
 void MenuManager::onMouseMove(const Common::Point &Pos) {
 	bool nowInMenu = inMenu(Pos);
-	if (nowInMenu != prevInMenu)
-		redraw = true;
-	prevInMenu = nowInMenu;
+	if (nowInMenu != _prevInMenu)
+		_redraw = true;
+	_prevInMenu = nowInMenu;
 
-	int lastItem = mouseOnItem;
+	int lastItem = _mouseOnItem;
 
-	switch (menuFocus.front()) {
+	switch (_menuFocus.front()) {
 	case kFocusMain:
 		//Inform game scripting engine that mouse is in main menu
 		if (_engine->getScriptManager()->getStateValue(StateKey_MenuState) != 2)
 			_engine->getScriptManager()->setStateValue(StateKey_MenuState, 2);
-		mouseOnItem = mouseOverMain(Pos);
+		_mouseOnItem = mouseOverMain(Pos);
 		break;
 	case kFocusNone:
 		//Inform game scripting engine that mouse is not in any menu
 		if (_engine->getScriptManager()->getStateValue(StateKey_MenuState) != 0)
 			_engine->getScriptManager()->setStateValue(StateKey_MenuState, 0);
-		mouseOnItem = -1;
+		_mouseOnItem = -1;
 		break;
 	}
-	mainScroller.setActive(menuFocus.front() == kFocusMain);
+	_mainScroller.setActive(_menuFocus.front() == kFocusMain);
 	//Update button animation status
 	for (int i = 0; i < 4; i++)
-		if (menuFocus[0] == kFocusMain && mouseOnItem == i)
-			buttonAnim[i]->setActive(true);
+		if (_menuFocus[0] == kFocusMain && _mouseOnItem == i)
+			_buttonAnim[i]->setActive(true);
 		else
-			buttonAnim[i]->setActive(false);
-	if (lastItem != mouseOnItem)
-		redraw = true;
+			_buttonAnim[i]->setActive(false);
+	if (lastItem != _mouseOnItem)
+		_redraw = true;
 }
 
 int MenuManager::mouseOverMain(const Common::Point &Pos) {
-	//Common::Rect mainHotspot(28,hSideMenu);
-	//mainHotspot.moveTo(mainOrigin + mainScroller.Pos);
+	//Common::Rect mainHotspot(28,_hSideMenu);
+	//mainHotspot.moveTo(mainOrigin + _mainScroller._pos);
 	for (int8 i = 0; i < 4; i++) {
-		if (enableFlags.get(i) && menuHotspots[i].contains(Pos))
+		if (_enableFlags.get(i) && _menuHotspots[i].contains(Pos))
 			return i;
 	}
 	return -1;
 }
 
 void MenuManager::process(uint32 deltatime) {
-	if (mainScroller.update(deltatime)) {
-		mainArea.moveTo(menuOrigin + mainScroller.Pos);
+	if (_mainScroller.update(deltatime)) {
+		_mainArea.moveTo(_menuOrigin + _mainScroller._pos);
 		for (int i = 0; i < 4; i++)
-			menuHotspots[i].moveTo(menuOrigin + Common::Point(_params.wxButs[i][1], mainScroller.Pos.y));
-		redraw = true;
+			_menuHotspots[i].moveTo(_menuOrigin + Common::Point(_params.wxButs[i][1], _mainScroller._pos.y));
+		_redraw = true;
 	}
 	//Update button highlight animation frame
 	for (int i = 0; i < 4; i++)
-		if (buttonAnim[i]->update(deltatime)) {
-			mainFrames[i] = buttonAnim[i]->Pos;
-			redraw = true;
+		if (_buttonAnim[i]->update(deltatime)) {
+			_mainFrames[i] = _buttonAnim[i]->_pos;
+			_redraw = true;
 		}
-	if (redraw) {
+	if (_redraw) {
 		_engine->getRenderManager()->clearMenuSurface();
 		redrawAll();
-		redraw = false;
+		_redraw = false;
 	}
 }
 
@@ -191,60 +191,60 @@ void MenuNemesis::redrawAll() {
 
 void MenuManager::redrawMain() {
 	//Draw menu background
-	_engine->getRenderManager()->blitSurfaceToMenu(mainBack, mainScroller.Pos.x, mainScroller.Pos.y, 0);
+	_engine->getRenderManager()->blitSurfaceToMenu(_mainBack, _mainScroller._pos.x, _mainScroller._pos.y, 0);
 	//Draw buttons
-	if (menuFocus.front() == kFocusMain)
+	if (_menuFocus.front() == kFocusMain)
 		for (int8 i = 0; i < 4; i++) {
-			if (enableFlags.get(i) && (mainFrames[i] >= 0)) {
-				if (mainClicked == i)
-					_engine->getRenderManager()->blitSurfaceToMenu(mainButtons[i][_params.clickedFrame], _params.wxButs[i][1], mainScroller.Pos.y, 0);
+			if (_enableFlags.get(i) && (_mainFrames[i] >= 0)) {
+				if (_mainClicked == i)
+					_engine->getRenderManager()->blitSurfaceToMenu(_mainButtons[i][_params.clickedFrame], _params.wxButs[i][1], _mainScroller._pos.y, 0);
 				else
-					_engine->getRenderManager()->blitSurfaceToMenu(mainButtons[i][mainFrames[i]], _params.wxButs[i][1], mainScroller.Pos.y, 0);
+					_engine->getRenderManager()->blitSurfaceToMenu(_mainButtons[i][_mainFrames[i]], _params.wxButs[i][1], _mainScroller._pos.y, 0);
 			}
 		}
-	clean = false;
+	_clean = false;
 }
 
 void MenuManager::setFocus(int8 currentFocus) {
-	menuFocus.set(currentFocus);
-	assert(menuFocus.size() <= 4);
+	_menuFocus.set(currentFocus);
+	assert(_menuFocus.size() <= 4);
 }
 
 MenuZGI::MenuZGI(ZVision *engine, const Common::Rect menuArea) :
 	MenuManager(engine, menuArea, zgiParams),
-	itemsScroller(Common::Point(0, 0), Common::Point(wSideMenuTab - wSideMenu, 0), sideMenuPeriod),
-	magicScroller(Common::Point(-wSideMenu, 0), Common::Point(-wSideMenuTab, 0), sideMenuPeriod),
-	itemsOrigin(menuArea.left, menuArea.top),
-	magicOrigin(menuArea.right, menuArea.top) {
+	_itemsScroller(Common::Point(0, 0), Common::Point(_wSideMenuTab - _wSideMenu, 0), _sideMenuPeriod),
+	_magicScroller(Common::Point(-_wSideMenu, 0), Common::Point(-_wSideMenuTab, 0), _sideMenuPeriod),
+	_itemsOrigin(menuArea.left, menuArea.top),
+	_magicOrigin(menuArea.right, menuArea.top) {
 
-	magicArea = Common::Rect(magicOrigin + magicScroller.Pos, wSideMenu, hSideMenu);
-	itemsArea = Common::Rect(itemsOrigin + itemsScroller.Pos, wSideMenu, hSideMenu);
+	_magicArea = Common::Rect(_magicOrigin + _magicScroller._pos, _wSideMenu, _hSideMenu);
+	_itemsArea = Common::Rect(_itemsOrigin + _itemsScroller._pos, _wSideMenu, _hSideMenu);
 
 	//Buffer main menu background
-	_engine->getRenderManager()->readImageToSurface("gmzau031.tga", mainBack, false);
+	_engine->getRenderManager()->readImageToSurface("gmzau031.tga", _mainBack, false);
 
 	char buf[24];
 	for (int i = 0; i < 4; i++) {
 		//Buffer menu buttons
 		Common::sprintf_s(buf, "gmzmu%2.2x1.tga", i);
-		_engine->getRenderManager()->readImageToSurface(buf, mainButtons[i][0], false);
+		_engine->getRenderManager()->readImageToSurface(buf, _mainButtons[i][0], false);
 		Common::sprintf_s(buf, "gmznu%2.2x1.tga", i);
-		_engine->getRenderManager()->readImageToSurface(buf, mainButtons[i][1], false);
+		_engine->getRenderManager()->readImageToSurface(buf, _mainButtons[i][1], false);
 	}
 	for (int i = 1; i < 4; i++) {
 		//Buffer full menu backgrounds
 		Common::sprintf_s(buf, "gmzau%2.2x1.tga", i);
-		_engine->getRenderManager()->readImageToSurface(buf, menuBack[i - 1], false);
+		_engine->getRenderManager()->readImageToSurface(buf, _menuBack[i - 1], false);
 	}
 	for (int i = 0; i < 50; i++) {
-		items[i][0] = NULL;
-		items[i][1] = NULL;
-		itemId[i] = 0;
+		_items[i][0] = NULL;
+		_items[i][1] = NULL;
+		_itemId[i] = 0;
 	}
 	for (int i = 0; i < 12; i++) {
-		magic[i][0] = NULL;
-		magic[i][1] = NULL;
-		magicId[i] = 0;
+		_magic[i][0] = NULL;
+		_magic[i][1] = NULL;
+		_magicId[i] = 0;
 	}
 	//Initialise focus sequence
 	setFocus(kFocusMain);
@@ -255,44 +255,44 @@ MenuZGI::MenuZGI(ZVision *engine, const Common::Rect menuArea) :
 
 MenuZGI::~MenuZGI() {
 	for (int i = 0; i < 3; i++)
-		menuBack[i].free();
+		_menuBack[i].free();
 
 	for (int i = 0; i < 4; i++)
 		for (int j = 0; j < 2; j++)
-			mainButtons[i][j].free();
+			_mainButtons[i][j].free();
 
 	for (int i = 0; i < 50; i++) {
-		if (items[i][0]) {
-			items[i][0]->free();
-			delete items[i][0];
+		if (_items[i][0]) {
+			_items[i][0]->free();
+			delete _items[i][0];
 		}
-		if (items[i][1]) {
-			items[i][1]->free();
-			delete items[i][1];
+		if (_items[i][1]) {
+			_items[i][1]->free();
+			delete _items[i][1];
 		}
 	}
 	for (int i = 0; i < 12; i++) {
-		if (magic[i][0]) {
-			magic[i][0]->free();
-			delete magic[i][0];
+		if (_magic[i][0]) {
+			_magic[i][0]->free();
+			delete _magic[i][0];
 		}
-		if (magic[i][1]) {
-			magic[i][1]->free();
-			delete magic[i][1];
+		if (_magic[i][1]) {
+			_magic[i][1]->free();
+			delete _magic[i][1];
 		}
 	}
 }
 
 bool MenuZGI::inMenu(const Common::Point &Pos) {
-	return menuTriggerArea.contains(Pos) || (menuFocus.front() != kFocusNone);
+	return _menuTriggerArea.contains(Pos) || (_menuFocus.front() != kFocusNone);
 }
 
 void MenuZGI::onMouseUp(const Common::Point &Pos) {
 	if (inMenu(Pos))
-		//redraw = true;
-		switch (menuFocus.front()) {
+		//_redraw = true;
+		switch (_menuFocus.front()) {
 		case kFocusItems:
-			if (enableFlags.get(kItemsMenu)) {
+			if (_enableFlags.get(kItemsMenu)) {
 				int itemCount = _engine->getScriptManager()->getStateValue(StateKey_Inv_TotalSlots);
 				if (itemCount == 0)
 					itemCount = 20;
@@ -303,13 +303,13 @@ void MenuZGI::onMouseUp(const Common::Point &Pos) {
 						_engine->getScriptManager()->inventoryDrop(mouseItem);
 						_engine->getScriptManager()->inventoryAdd(_engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + i));
 						_engine->getScriptManager()->setStateValue(StateKey_Inv_StartSlot + i, mouseItem);
-						redraw = true;
+						_redraw = true;
 					}
 				}
 			}
 			break;
 		case kFocusMagic:
-			if (enableFlags.get(kMagicMenu)) {
+			if (_enableFlags.get(kMagicMenu)) {
 				int i = mouseOverMagic(Pos);
 				if (i != -1) {
 					uint itemnum = _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + i);
@@ -335,30 +335,30 @@ void MenuZGI::onMouseUp(const Common::Point &Pos) {
 
 void MenuZGI::onMouseMove(const Common::Point &Pos) {
 	if (!inMenu(Pos)) {
-		mainScroller.reset();
-		magicScroller.reset();
-		itemsScroller.reset();
+		_mainScroller.reset();
+		_magicScroller.reset();
+		_itemsScroller.reset();
 	}
 
 	//Set focus to topmost layer of menus that mouse is currently over
-	for (uint8 i = 0; i < menuFocus.size(); i++) {
-		switch (menuFocus[i]) {
+	for (uint8 i = 0; i < _menuFocus.size(); i++) {
+		switch (_menuFocus[i]) {
 		case kFocusItems:
-			if (itemsArea.contains(Pos)) {
+			if (_itemsArea.contains(Pos)) {
 				setFocus(kFocusItems);
-				i = menuFocus.size() + 1;
+				i = _menuFocus.size() + 1;
 			}
 			break;
 		case kFocusMagic:
-			if (magicArea.contains(Pos)) {
+			if (_magicArea.contains(Pos)) {
 				setFocus(kFocusMagic);
-				i = menuFocus.size() + 1;
+				i = _menuFocus.size() + 1;
 			}
 			break;
 		case kFocusMain:
-			if (mainArea.contains(Pos)) {
+			if (_mainArea.contains(Pos)) {
 				setFocus(kFocusMain);
-				i = menuFocus.size() + 1;
+				i = _menuFocus.size() + 1;
 			}
 			break;
 		default:
@@ -366,31 +366,31 @@ void MenuZGI::onMouseMove(const Common::Point &Pos) {
 			break;
 		}
 	}
-	itemsScroller.setActive(menuFocus.front() == kFocusItems);
-	magicScroller.setActive(menuFocus.front() == kFocusMagic);
-	if (menuFocus.front() != kFocusNone) {
-		switch (menuFocus.front()) {
+	_itemsScroller.setActive(_menuFocus.front() == kFocusItems);
+	_magicScroller.setActive(_menuFocus.front() == kFocusMagic);
+	if (_menuFocus.front() != kFocusNone) {
+		switch (_menuFocus.front()) {
 		case kFocusItems:
-			if (enableFlags.get(kItemsMenu)) {
+			if (_enableFlags.get(kItemsMenu)) {
 				int itemCount = _engine->getScriptManager()->getStateValue(StateKey_Inv_TotalSlots);
 				if (itemCount == 0)
 					itemCount = 20;
 				else if (itemCount > 50)
 					itemCount = 50;
-				int lastItem = mouseOnItem;
-				mouseOnItem = mouseOverItem(Pos, itemCount);
-				if (lastItem != mouseOnItem)
-					if (_engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + mouseOnItem) || _engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + lastItem))
-						redraw = true;
+				int lastItem = _mouseOnItem;
+				_mouseOnItem = mouseOverItem(Pos, itemCount);
+				if (lastItem != _mouseOnItem)
+					if (_engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + _mouseOnItem) || _engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + lastItem))
+						_redraw = true;
 			}
 			break;
 		case kFocusMagic:
-			if (enableFlags.get(kMagicMenu)) {
-				int lastItem = mouseOnItem;
-				mouseOnItem = mouseOverMagic(Pos);
-				if (lastItem != mouseOnItem)
-					if (_engine->getScriptManager()->getStateValue(StateKey_Spell_1 + mouseOnItem) || _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + lastItem))
-						redraw = true;
+			if (_enableFlags.get(kMagicMenu)) {
+				int lastItem = _mouseOnItem;
+				_mouseOnItem = mouseOverMagic(Pos);
+				if (lastItem != _mouseOnItem)
+					if (_engine->getScriptManager()->getStateValue(StateKey_Spell_1 + _mouseOnItem) || _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + lastItem))
+						_redraw = true;
 			}
 			break;
 		case kFocusMain:
@@ -401,9 +401,9 @@ void MenuZGI::onMouseMove(const Common::Point &Pos) {
 }
 
 int MenuZGI::mouseOverItem(const Common::Point &Pos, int itemCount) {
-	int itemWidth = (wSideMenu - 28) / itemCount;
-	Common::Rect itemHotspot = Common::Rect(28, hSideMenu);
-	itemHotspot.moveTo(itemsOrigin + itemsScroller.Pos);
+	int itemWidth = (_wSideMenu - 28) / itemCount;
+	Common::Rect itemHotspot = Common::Rect(28, _hSideMenu);
+	itemHotspot.moveTo(_itemsOrigin + _itemsScroller._pos);
 	for (int i = 0; i < itemCount; i++) {
 		if (itemHotspot.contains(Pos))
 			return i;
@@ -413,40 +413,40 @@ int MenuZGI::mouseOverItem(const Common::Point &Pos, int itemCount) {
 }
 
 int MenuZGI::mouseOverMagic(const Common::Point &Pos) {
-	Common::Rect magicHotspot(28, hSideMenu);
-	magicHotspot.moveTo(magicOrigin + magicScroller.Pos);
+	Common::Rect magicHotspot(28, _hSideMenu);
+	magicHotspot.moveTo(_magicOrigin + _magicScroller._pos);
 	magicHotspot.translate(28, 0); //Offset from end of menu
 	for (int i = 0; i < 12; i++) {
 		if (magicHotspot.contains(Pos))
 			return i;
-		magicHotspot.translate(magicWidth, 0);
+		magicHotspot.translate(_magicWidth, 0);
 	}
 	return -1;
 }
 
 void MenuZGI::process(uint32 deltatime) {
-	if (itemsScroller.update(deltatime)) {
-		itemsArea.moveTo(itemsOrigin + itemsScroller.Pos);
-		redraw = true;
+	if (_itemsScroller.update(deltatime)) {
+		_itemsArea.moveTo(_itemsOrigin + _itemsScroller._pos);
+		_redraw = true;
 	}
-	if (magicScroller.update(deltatime)) {
-		magicArea.moveTo(magicOrigin + magicScroller.Pos);
-		redraw = true;
+	if (_magicScroller.update(deltatime)) {
+		_magicArea.moveTo(_magicOrigin + _magicScroller._pos);
+		_redraw = true;
 	}
 	MenuManager::process(deltatime);
 }
 
 void MenuZGI::redrawAll() {
 	if (MenuManager::inMenu())
-		for (int8 i = menuFocus.size() - 1; i >= 0; i--)
-			switch (menuFocus[i]) {
+		for (int8 i = _menuFocus.size() - 1; i >= 0; i--)
+			switch (_menuFocus[i]) {
 			case kFocusItems:
-				if (enableFlags.get(kItemsMenu)) {
+				if (_enableFlags.get(kItemsMenu)) {
 					redrawItems();
 				}
 				break;
 			case kFocusMagic:
-				if (enableFlags.get(kMagicMenu)) {
+				if (_enableFlags.get(kMagicMenu)) {
 					redrawMagic();
 				}
 				break;
@@ -460,10 +460,10 @@ void MenuZGI::redrawAll() {
 
 void MenuZGI::redrawMagic() {
 	const int16 yOrigin = _menuArea.width();
-	_engine->getRenderManager()->blitSurfaceToMenu(menuBack[kFocusMagic], yOrigin + magicScroller.Pos.x, 0, 0);
+	_engine->getRenderManager()->blitSurfaceToMenu(_menuBack[kFocusMagic], yOrigin + _magicScroller._pos.x, 0, 0);
 	for (int i = 0; i < 12; i++) {
 		bool inrect = false;
-		if (mouseOnItem == i)
+		if (_mouseOnItem == i)
 			inrect = true;
 		uint curItemId = _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + i);
 		if (curItemId) {
@@ -473,92 +473,92 @@ void MenuZGI::redrawMagic() {
 				curItemId = 0xE0 + i;
 		}
 		if (curItemId != 0) {
-			if (itemId[i] != curItemId) {
+			if (_itemId[i] != curItemId) {
 				char buf[16];
 				Common::sprintf_s(buf, "gmzwu%2.2x1.tga", curItemId);
-				magic[i][0] = _engine->getRenderManager()->loadImage(buf, false);
+				_magic[i][0] = _engine->getRenderManager()->loadImage(buf, false);
 				Common::sprintf_s(buf, "gmzxu%2.2x1.tga", curItemId);
-				magic[i][1] = _engine->getRenderManager()->loadImage(buf, false);
-				magicId[i] = curItemId;
+				_magic[i][1] = _engine->getRenderManager()->loadImage(buf, false);
+				_magicId[i] = curItemId;
 			}
 			if (inrect)
-				_engine->getRenderManager()->blitSurfaceToMenu(*magic[i][1], yOrigin + magicScroller.Pos.x + 28 + magicWidth * i, 0, 0);
+				_engine->getRenderManager()->blitSurfaceToMenu(*_magic[i][1], yOrigin + _magicScroller._pos.x + 28 + _magicWidth * i, 0, 0);
 			else
-				_engine->getRenderManager()->blitSurfaceToMenu(*magic[i][0], yOrigin + magicScroller.Pos.x + 28 + magicWidth * i, 0, 0);
+				_engine->getRenderManager()->blitSurfaceToMenu(*_magic[i][0], yOrigin + _magicScroller._pos.x + 28 + _magicWidth * i, 0, 0);
 		} else {
-			if (magic[i][0]) {
-				magic[i][0]->free();
-				delete magic[i][0];
-				magic[i][0] = NULL;
+			if (_magic[i][0]) {
+				_magic[i][0]->free();
+				delete _magic[i][0];
+				_magic[i][0] = NULL;
 			}
-			if (magic[i][1]) {
-				magic[i][1]->free();
-				delete magic[i][1];
-				magic[i][1] = NULL;
+			if (_magic[i][1]) {
+				_magic[i][1]->free();
+				delete _magic[i][1];
+				_magic[i][1] = NULL;
 			}
-			magicId[i] = 0;
+			_magicId[i] = 0;
 		}
 	}
-	clean = false;
+	_clean = false;
 }
 
 void MenuZGI::redrawItems() {
-	_engine->getRenderManager()->blitSurfaceToMenu(menuBack[kFocusItems], itemsScroller.Pos.x, 0, 0);
+	_engine->getRenderManager()->blitSurfaceToMenu(_menuBack[kFocusItems], _itemsScroller._pos.x, 0, 0);
 	int itemCount = _engine->getScriptManager()->getStateValue(StateKey_Inv_TotalSlots);
 	if (itemCount == 0)
 		itemCount = 20;
 	else if (itemCount > 50)
 		itemCount = 50;
-	int itemWidth = (wSideMenu - 28) / itemCount;
+	int itemWidth = (_wSideMenu - 28) / itemCount;
 
 	for (int i = 0; i < itemCount; i++) {
 		bool inrect = false;
-		if (mouseOnItem == i)
+		if (_mouseOnItem == i)
 			inrect = true;
 		uint curItemId = _engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + i);
 
 		if (curItemId != 0) {
-			if (itemId[i] != curItemId) {
+			if (_itemId[i] != curItemId) {
 				char buf[16];
 				Common::sprintf_s(buf, "gmzwu%2.2x1.tga", curItemId);
-				items[i][0] = _engine->getRenderManager()->loadImage(buf, false);
+				_items[i][0] = _engine->getRenderManager()->loadImage(buf, false);
 				Common::sprintf_s(buf, "gmzxu%2.2x1.tga", curItemId);
-				items[i][1] = _engine->getRenderManager()->loadImage(buf, false);
-				itemId[i] = curItemId;
+				_items[i][1] = _engine->getRenderManager()->loadImage(buf, false);
+				_itemId[i] = curItemId;
 			}
 			if (inrect)
-				_engine->getRenderManager()->blitSurfaceToMenu(*items[i][1], itemsScroller.Pos.x + itemWidth * i, 0, 0);
+				_engine->getRenderManager()->blitSurfaceToMenu(*_items[i][1], _itemsScroller._pos.x + itemWidth * i, 0, 0);
 			else
-				_engine->getRenderManager()->blitSurfaceToMenu(*items[i][0], itemsScroller.Pos.x + itemWidth * i, 0, 0);
+				_engine->getRenderManager()->blitSurfaceToMenu(*_items[i][0], _itemsScroller._pos.x + itemWidth * i, 0, 0);
 		} else {
-			if (items[i][0]) {
-				items[i][0]->free();
-				delete items[i][0];
-				items[i][0] = NULL;
+			if (_items[i][0]) {
+				_items[i][0]->free();
+				delete _items[i][0];
+				_items[i][0] = NULL;
 			}
-			if (items[i][1]) {
-				items[i][1]->free();
-				delete items[i][1];
-				items[i][1] = NULL;
+			if (_items[i][1]) {
+				_items[i][1]->free();
+				delete _items[i][1];
+				_items[i][1] = NULL;
 			}
-			itemId[i] = 0;
+			_itemId[i] = 0;
 		}
 	}
-	clean = false;
+	_clean = false;
 }
 
 MenuNemesis::MenuNemesis(ZVision *engine, const Common::Rect menuArea) :
 	MenuManager(engine, menuArea, nemesisParams) {
 
 	//Buffer menu background image
-	_engine->getRenderManager()->readImageToSurface("bar.tga", mainBack, false);
+	_engine->getRenderManager()->readImageToSurface("bar.tga", _mainBack, false);
 
 	char buf[24];
 	for (int i = 0; i < 4; i++) {
 		//Buffer menu buttons
 		for (int j = 0; j < 6; j++) {
 			Common::sprintf_s(buf, "butfrm%d%d.tga", i + 1, j);
-			_engine->getRenderManager()->readImageToSurface(buf, mainButtons[i][j], false);
+			_engine->getRenderManager()->readImageToSurface(buf, _mainButtons[i][j], false);
 		}
 	}
 }
@@ -566,18 +566,18 @@ MenuNemesis::MenuNemesis(ZVision *engine, const Common::Rect menuArea) :
 MenuNemesis::~MenuNemesis() {
 	for (int i = 0; i < 4; i++) {
 		for (int j = 0; j < 6; j++)
-			mainButtons[i][j].free();
+			_mainButtons[i][j].free();
 	};
 }
 
 bool MenuNemesis::inMenu(const Common::Point &Pos) {
-	return menuTriggerArea.contains(Pos) || (menuFocus.front() != kFocusNone);
+	return _menuTriggerArea.contains(Pos) || (_menuFocus.front() != kFocusNone);
 }
 
 void MenuNemesis::onMouseMove(const Common::Point &Pos) {
 	//Trigger main menu scrolldown to get mouse over main trigger area
 	//Set focus to topmost layer of menus that mouse is currently over
-	if (mainArea.contains(Pos) || menuTriggerArea.contains(Pos))
+	if (_mainArea.contains(Pos) || _menuTriggerArea.contains(Pos))
 		setFocus(kFocusMain);
 	else
 		setFocus(kFocusNone);
diff --git a/engines/zvision/scripting/menu.h b/engines/zvision/scripting/menu.h
index 56d86eb19e1..6ab6c120efe 100644
--- a/engines/zvision/scripting/menu.h
+++ b/engines/zvision/scripting/menu.h
@@ -93,7 +93,7 @@ public:
 	virtual void onMouseUp(const Common::Point &Pos);
 	virtual void process(uint32 deltaTimeInMillis);
 	bool inMenu() {
-		return prevInMenu;
+		return _prevInMenu;
 	};
 	virtual bool inMenu(const Common::Point &Pos) {
 		return false;
@@ -104,10 +104,10 @@ public:
 
 	void setEnable(uint16 flags);
 	uint16 getEnable() {
-		return menuBarFlag;
+		return _menuBarFlag;
 	}
 	bool getEnable(uint8 flag) {
-		return enableFlags.get(flag);
+		return _enableFlags.get(flag);
 	}
 
 protected:
@@ -116,29 +116,28 @@ protected:
 	int mouseOverMain(const Common::Point &Pos);
 	void setFocus(int8 currentFocus);
 
-//	bool inMenu = false;  //True if menus are currently visible
-	bool prevInMenu = false;
-	bool redraw = true;
-	int mouseOnItem = -1;
-	static const uint8 hMainMenu = 32;
-	int8 mainClicked = -1;
+	bool _prevInMenu = false;
+	bool _redraw = true;
+	int _mouseOnItem = -1;
+	static const uint8 _hMainMenu = 32;
+	int8 _mainClicked = -1;
 
 	ZVision *_engine;
 	const MenuParams _params;
-	uint16 menuBarFlag;
+	uint16 _menuBarFlag;
 	const Common::Rect _menuArea;
-	const Common::Point menuOrigin;
-	const Common::Rect menuTriggerArea;
-	Graphics::Surface mainBack;
-	Graphics::Surface mainButtons[4][6];
-	Common::BitArray enableFlags;
-	Common::Rect mainArea;
-	Common::Rect menuHotspots[4];
-	int8 mainFrames[4]; //Frame to display of each main menu button; first row is currently displayed, 2nd row is backbuffer for idle animations
-	Scroller mainScroller;
-	FocusList<int8> menuFocus;  //Order in which menus have most recently had focus; determines current mouse focus & order in which to redraw them.
-	bool clean = false; //Whether or not to blank
-	LinearScroller *buttonAnim[4];
+	const Common::Point _menuOrigin;
+	const Common::Rect _menuTriggerArea;
+	Graphics::Surface _mainBack;
+	Graphics::Surface _mainButtons[4][6];
+	Common::BitArray _enableFlags;
+	Common::Rect _mainArea;
+	Common::Rect _menuHotspots[4];
+	int8 _mainFrames[4]; //Frame to display of each main menu button; first row is currently displayed, 2nd row is backbuffer for idle animations
+	Scroller _mainScroller;
+	FocusList<int8> _menuFocus;  //Order in which menus have most recently had focus; determines current mouse focus & order in which to redraw them.
+	bool _clean = false; //Whether or not to blank
+	LinearScroller *_buttonAnim[4];
 };
 
 class MenuZGI: public MenuManager {
@@ -151,32 +150,32 @@ public:
 	bool inMenu(const Common::Point &Pos) override;
 private:
 	void redrawAll() override;
-	Graphics::Surface menuBack[3];
-	Graphics::Surface *items[50][2];
-	uint itemId[50];
+	Graphics::Surface _menuBack[3];
+	Graphics::Surface *_items[50][2];
+	uint _itemId[50];
 
-	Graphics::Surface *magic[12][2];
-	uint magicId[12];
+	Graphics::Surface *_magic[12][2];
+	uint _magicId[12];
 //  void redrawMain(bool hasFocus) override;
 	void redrawItems();
 	void redrawMagic();
 	int mouseOverItem(const Common::Point &Pos, int itemCount);
 	int mouseOverMagic(const Common::Point &Pos);
 
-	static const uint16 hSideMenu = 32;
-	static const uint16 wSideMenu = 600;
-	static const uint16 wSideMenuTab = 20;
-	static const int16 magicWidth = 47;
+	static const uint16 _hSideMenu = 32;
+	static const uint16 _wSideMenu = 600;
+	static const uint16 _wSideMenuTab = 20;
+	static const int16 _magicWidth = 47;
 
-	const int16 sideMenuPeriod = 300;
+	const int16 _sideMenuPeriod = 300;
 
-	Scroller itemsScroller, magicScroller;
+	Scroller _itemsScroller, _magicScroller;
 
-	const Common::Point magicOrigin;
-	const Common::Point itemsOrigin;
+	const Common::Point _magicOrigin;
+	const Common::Point _itemsOrigin;
 
-	Common::Rect magicArea;
-	Common::Rect itemsArea;
+	Common::Rect _magicArea;
+	Common::Rect _itemsArea;
 };
 
 class MenuNemesis: public MenuManager {
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index 23368283e5f..c40d67efb53 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -46,10 +46,10 @@ ScriptManager::ScriptManager(ZVision *engine)
 }
 
 ScriptManager::~ScriptManager() {
-	cleanScriptScope(universe);
-	cleanScriptScope(world);
-	cleanScriptScope(room);
-	cleanScriptScope(nodeview);
+	cleanScriptScope(_universe);
+	cleanScriptScope(_world);
+	cleanScriptScope(_room);
+	cleanScriptScope(_nodeview);
 	_controlEvents.clear();
 }
 
@@ -58,10 +58,10 @@ void ScriptManager::initialize(bool restarted) {
 		_globalState.clear();
 		_globalStateFlags.clear();
 	}
-	cleanScriptScope(universe);
-	cleanScriptScope(world);
-	cleanScriptScope(room);
-	cleanScriptScope(nodeview);
+	cleanScriptScope(_universe);
+	cleanScriptScope(_world);
+	cleanScriptScope(_room);
+	cleanScriptScope(_nodeview);
 	_currentLocation.node = 0;
 	_currentLocation.world = 0;
 	_currentLocation.room = 0;
@@ -88,7 +88,7 @@ void ScriptManager::initialize(bool restarted) {
 			break;
 		}
 	}
-	parseScrFile("universe.scr", universe);
+	parseScrFile("universe.scr", _universe);
 	changeLocation('g', 'a', 'r', 'y', 0);
 	_controlEvents.clear();
 	if (restarted)
@@ -111,13 +111,13 @@ void ScriptManager::update(uint deltaTimeMillis) {
 	}
 	updateNodes(deltaTimeMillis);
 	debug(5, "Script nodes updated");
-	if (!execScope(nodeview))
+	if (!execScope(_nodeview))
 		return;
-	if (!execScope(room))
+	if (!execScope(_room))
 		return;
-	if (!execScope(world))
+	if (!execScope(_world))
 		return;
-	if (!execScope(universe))
+	if (!execScope(_universe))
 		return;
 	updateControls(deltaTimeMillis);
 }
@@ -500,12 +500,12 @@ void ScriptManager::changeLocation(const Location &_newLocation) {
 	changeLocation(_newLocation.world, _newLocation.room, _newLocation.node, _newLocation.view, _newLocation.offset);
 }
 
-void ScriptManager::changeLocation(char _world, char _room, char _node, char _view, uint32 offset) {
+void ScriptManager::changeLocation(char world, char room, char node, char view, uint32 offset) {
 	_changeLocationDelayCycles = 1;
-	_nextLocation.world = _world;
-	_nextLocation.room = _room;
-	_nextLocation.node = _node;
-	_nextLocation.view = _view;
+	_nextLocation.world = world;
+	_nextLocation.room = room;
+	_nextLocation.node = node;
+	_nextLocation.view = view;
 	_nextLocation.offset = offset;
 	// If next location is 0000, return to the previous location.
 	if (_nextLocation == "0000") {
@@ -583,43 +583,43 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 	setStateValue(StateKey_ViewPos, _nextLocation.offset);
 
 	_referenceTable.clear();
-	addPuzzlesToReferenceTable(universe);
+	addPuzzlesToReferenceTable(_universe);
 
 	_engine->getMenuManager()->setEnable(0xFFFF);
 
 	if (_nextLocation.world != _currentLocation.world) {
-		cleanScriptScope(nodeview);
-		cleanScriptScope(room);
-		cleanScriptScope(world);
+		cleanScriptScope(_nodeview);
+		cleanScriptScope(_room);
+		cleanScriptScope(_world);
 		Common::Path fileName(Common::String::format("%c%c%c%c.scr", _nextLocation.world, _nextLocation.room, _nextLocation.node, _nextLocation.view));
-		parseScrFile(fileName, nodeview);
-		addPuzzlesToReferenceTable(nodeview);
+		parseScrFile(fileName, _nodeview);
+		addPuzzlesToReferenceTable(_nodeview);
 		fileName = Common::Path(Common::String::format("%c%c.scr", _nextLocation.world, _nextLocation.room));
-		parseScrFile(fileName, room);
-		addPuzzlesToReferenceTable(room);
+		parseScrFile(fileName, _room);
+		addPuzzlesToReferenceTable(_room);
 		fileName = Common::Path(Common::String::format("%c.scr", _nextLocation.world));
-		parseScrFile(fileName, world);
-		addPuzzlesToReferenceTable(world);
+		parseScrFile(fileName, _world);
+		addPuzzlesToReferenceTable(_world);
 	} else if (_nextLocation.room != _currentLocation.room) {
-		cleanScriptScope(nodeview);
-		cleanScriptScope(room);
-		addPuzzlesToReferenceTable(world);
+		cleanScriptScope(_nodeview);
+		cleanScriptScope(_room);
+		addPuzzlesToReferenceTable(_world);
 		Common::Path fileName(Common::String::format("%c%c%c%c.scr", _nextLocation.world, _nextLocation.room, _nextLocation.node, _nextLocation.view));
-		parseScrFile(fileName, nodeview);
-		addPuzzlesToReferenceTable(nodeview);
+		parseScrFile(fileName, _nodeview);
+		addPuzzlesToReferenceTable(_nodeview);
 		fileName = Common::Path(Common::String::format("%c%c.scr", _nextLocation.world, _nextLocation.room));
-		parseScrFile(fileName, room);
-		addPuzzlesToReferenceTable(room);
+		parseScrFile(fileName, _room);
+		addPuzzlesToReferenceTable(_room);
 	} else if (_nextLocation.node != _currentLocation.node || _nextLocation.view != _currentLocation.view) {
-		cleanScriptScope(nodeview);
-		addPuzzlesToReferenceTable(room);
-		addPuzzlesToReferenceTable(world);
+		cleanScriptScope(_nodeview);
+		addPuzzlesToReferenceTable(_room);
+		addPuzzlesToReferenceTable(_world);
 		Common::Path fileName(Common::String::format("%c%c%c%c.scr", _nextLocation.world, _nextLocation.room, _nextLocation.node, _nextLocation.view));
-		parseScrFile(fileName, nodeview);
-		addPuzzlesToReferenceTable(nodeview);
+		parseScrFile(fileName, _nodeview);
+		addPuzzlesToReferenceTable(_nodeview);
 	}
 
-	_activeControls = &nodeview.controls;
+	_activeControls = &_nodeview.controls;
 
 	// Revert to the idle cursor
 	_engine->getCursorManager()->changeCursor(CursorIndex_Idle);
@@ -629,20 +629,20 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 
 	if (_currentLocation == "0000") {
 		_currentLocation = _nextLocation;
-		execScope(world);
-		execScope(room);
-		execScope(nodeview);
+		execScope(_world);
+		execScope(_room);
+		execScope(_nodeview);
 	} else if (_nextLocation.world != _currentLocation.world) {
 		_currentLocation = _nextLocation;
-		execScope(room);
-		execScope(nodeview);
+		execScope(_room);
+		execScope(_nodeview);
 	} else if (_nextLocation.room != _currentLocation.room) {
 		_currentLocation = _nextLocation;
-		execScope(room);
-		execScope(nodeview);
+		execScope(_room);
+		execScope(_nodeview);
 	} else if (_nextLocation.node != _currentLocation.node || _nextLocation.view != _currentLocation.view) {
 		_currentLocation = _nextLocation;
-		execScope(nodeview);
+		execScope(_nodeview);
 	}
 
 	_engine->getRenderManager()->checkBorders();
@@ -678,9 +678,9 @@ void ScriptManager::deserialize(Common::SeekableReadStream *stream) {
 	// Clear out the current table values
 	_globalState.clear();
 	_globalStateFlags.clear();
-	cleanScriptScope(nodeview);
-	cleanScriptScope(room);
-	cleanScriptScope(world);
+	cleanScriptScope(_nodeview);
+	cleanScriptScope(_room);
+	cleanScriptScope(_world);
 	_currentLocation.node = 0;
 	_currentLocation.world = 0;
 	_currentLocation.room = 0;
@@ -788,25 +788,25 @@ void ScriptManager::trimCommentsAndWhiteSpace(Common::String *string) const {
 
 ValueSlot::ValueSlot(ScriptManager *scriptManager, const char *slotValue):
 	_scriptManager(scriptManager) {
-	value = 0;
-	slot = false;
+	_value = 0;
+	_slot = false;
 	const char *isSlot = strstr(slotValue, "[");
 	if (isSlot) {
-		slot = true;
-		value = atoi(isSlot + 1);
+		_slot = true;
+		_value = atoi(isSlot + 1);
 	} else {
-		slot = false;
-		value = atoi(slotValue);
+		_slot = false;
+		_value = atoi(slotValue);
 	}
 }
 int16 ValueSlot::getValue() {
-	if (slot) {
-		if (value >= 0)
-			return _scriptManager->getStateValue(value);
+	if (_slot) {
+		if (_value >= 0)
+			return _scriptManager->getStateValue(_value);
 		else
 			return 0;
 	} else
-		return value;
+		return _value;
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/script_manager.h b/engines/zvision/scripting/script_manager.h
index 15b8bb22dc7..cd4341f7698 100644
--- a/engines/zvision/scripting/script_manager.h
+++ b/engines/zvision/scripting/script_manager.h
@@ -182,10 +182,10 @@ private:
 
 	EventList _controlEvents;
 
-	ScriptScope universe;
-	ScriptScope world;
-	ScriptScope room;
-	ScriptScope nodeview;
+	ScriptScope _universe;
+	ScriptScope _world;
+	ScriptScope _room;
+	ScriptScope _nodeview;
 
 	/** Holds the currently active timers, musics, other */
 	SideFXList _activeSideFx;
@@ -381,8 +381,8 @@ public:
 	ValueSlot(ScriptManager *scriptManager, const char *slotValue);
 	int16 getValue();
 private:
-	int16 value;
-	bool slot;
+	int16 _value;
+	bool _slot;
 	ScriptManager *_scriptManager;
 };
 
diff --git a/engines/zvision/sound/midi.cpp b/engines/zvision/sound/midi.cpp
index b91f95c28f8..c9fc97294e9 100644
--- a/engines/zvision/sound/midi.cpp
+++ b/engines/zvision/sound/midi.cpp
@@ -29,20 +29,18 @@
 namespace ZVision {
 
 MidiManager::MidiManager() {
-	MidiDriver::DeviceHandle dev = MidiDriver::detectDevice(MDT_MIDI | MDT_ADLIB);  //NB Bug current in MT-32 emulation: MIDI channel 0 does not play anything!
+	MidiDriver::DeviceHandle dev = MidiDriver::detectDevice(MDT_MIDI | MDT_ADLIB);
 	_driver = MidiDriver::createMidi(dev);
 	if (_driver->open()) {
 		warning("Can't open MIDI, no MIDI output!");
-		available = false;
+		_available = false;
 	} else {
 		Common::String driverName = MidiDriver::getDeviceString(dev, MidiDriver::DeviceStringType::kDriverName);
 		Common::String deviceName = MidiDriver::getDeviceString(dev, MidiDriver::DeviceStringType::kDeviceName);
-		mt32workaround = driverName.contains("MT-32");
+		_mt32 = driverName.contains("MT-32");
 		debug(1, "MIDI opened, driver type: %s, device name: %s", driverName.c_str(), deviceName.c_str());
-		if (mt32workaround)
-			debug(1, "Blocking use of MIDI channel 0 to work around bug in MT-32 emulation.");
-		available = true;
-		maxChannels = _driver->MIDI_CHANNEL_COUNT;
+		_available = true;
+		_maxChannels = _driver->MIDI_CHANNEL_COUNT;
 	}
 }
 
@@ -66,24 +64,24 @@ void MidiManager::stop() {
 
 void MidiManager::noteOn(uint8 channel, uint8 note, uint8 velocity) {
 	assert(channel <= 15);
-	activeChannels[channel].playing = true;
-	activeChannels[channel].note = note;
+	_activeChannels[channel].playing = true;
+	_activeChannels[channel].note = note;
 	send(0x90 | channel, note, velocity);
 	debug(1, "MIDI note on, channel %d, note %d, velocity %d", channel, note, velocity);
 }
 
 void MidiManager::noteOff(uint8 channel) {
 	assert(channel <= 15);
-	if (activeChannels[channel].playing) {
-		activeChannels[channel].playing = false;
-		send(0x80 | channel, activeChannels[channel].note);
+	if (_activeChannels[channel].playing) {
+		_activeChannels[channel].playing = false;
+		send(0x80 | channel, _activeChannels[channel].note);
 	}
 }
 
 int8 MidiManager::getFreeChannel() {
-	uint8 start = mt32workaround ? 1 : 0; //MT-32 emulator driver currently fails to play anything when sent notes on channel 0.  Quick & dirty fix, since we only need a few notes for Nemesis music puzzles.  Inform maintainer of MT-32 emulator code of bug for proper fix in the future & then remove this nasty hack once that's sorted out.
+	uint8 start = _mt32 ? 1 : 0; //MT-32 can be used for MIDI, but does not play anything on MIDI channel 0
 	for (uint8 i = start; i < 16; i++)
-		if (!activeChannels[i].playing)
+		if (!_activeChannels[i].playing)
 			return i;
 	return -1;
 }
diff --git a/engines/zvision/sound/midi.h b/engines/zvision/sound/midi.h
index 43aa8362b17..7a1267ba124 100644
--- a/engines/zvision/sound/midi.h
+++ b/engines/zvision/sound/midi.h
@@ -41,22 +41,22 @@ public:
 
 	int8 getFreeChannel();  //Negative if none available
 	bool isAvailable() {
-		return available;
+		return _available;
 	};
 
 protected:
-	bool available = false;
-	bool mt32workaround = false;
+	bool _available = false;
+	bool _mt32 = false;
 	struct chan {
 		bool playing;
 		uint8 note;
 		chan() : playing(false), note(0) {};
 	};
 	void send(uint8 status, uint8 data1 = 0x00, uint8 data2 = 0x00);
-	uint8 startChannel = 0;
-	uint8 maxChannels = 16;
+	uint8 _startChannel = 0;
+	uint8 _maxChannels = 16;
 	MidiDriver *_driver;
-	chan activeChannels[16];
+	chan _activeChannels[16];
 };
 
 }
diff --git a/engines/zvision/sound/volume_manager.cpp b/engines/zvision/sound/volume_manager.cpp
index 7766dbc3a31..2d636671dc3 100644
--- a/engines/zvision/sound/volume_manager.cpp
+++ b/engines/zvision/sound/volume_manager.cpp
@@ -157,7 +157,7 @@ uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode, Math::Angle a
 
 uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode) {
 	uint16 scaledInput = inputValue * 255;
-	scaledInput /= scriptScale;
+	scaledInput /= _scriptScale;
 	uint8 output = 0;
 	switch (mode) {
 	case kVolumeLogPower:
diff --git a/engines/zvision/sound/volume_manager.h b/engines/zvision/sound/volume_manager.h
index 6624a565552..eacbd2067c3 100644
--- a/engines/zvision/sound/volume_manager.h
+++ b/engines/zvision/sound/volume_manager.h
@@ -54,7 +54,7 @@ public:
 	uint8 convert(uint8 inputValue, volumeScaling mode, Math::Angle azimuth, uint8 directionality = 255);
 private:
 	ZVision *_engine;
-	uint scriptScale = 100; //Z-Vision scripts internally use a volume scale of 0-100; ScummVM uses a scale of 0-255.
+	uint _scriptScale = 100; //Z-Vision scripts internally use a volume scale of 0-100; ScummVM uses a scale of 0-255.
 	volumeScaling _mode = kVolumeLinear;
 };
 
diff --git a/engines/zvision/text/subtitle_manager.cpp b/engines/zvision/text/subtitle_manager.cpp
index d48f196d717..88ced580c95 100644
--- a/engines/zvision/text/subtitle_manager.cpp
+++ b/engines/zvision/text/subtitle_manager.cpp
@@ -35,7 +35,7 @@ SubtitleManager::SubtitleManager(ZVision *engine, const ScreenLayout layout, con
 	_pixelFormat(pixelFormat),
 	_textOffset(layout.workingArea.origin() - layout.textArea.origin()),
 	_textArea(layout.textArea.width(), layout.textArea.height()),
-	redraw(false),
+	_redraw(false),
 	_doubleFPS(doubleFPS),
 	_subId(0) {
 }
@@ -53,14 +53,14 @@ void SubtitleManager::process(int32 deltatime) {
 	for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
 		//Update all automatic subtitles
 		if (it->_value->selfUpdate())
-			redraw = true;
+			_redraw = true;
 		//Update all subtitles' respective deletion timers
 		if (it->_value->process(deltatime)) {
 			debug(4, "Deleting subtitle, subId=%d", it->_key);
 			_subsFocus.remove(it->_key);
 			delete it->_value;
 			_subsList.erase(it);
-			redraw = true;
+			_redraw = true;
 		}
 	}
 	if (_subsList.size() == 0)
@@ -69,7 +69,7 @@ void SubtitleManager::process(int32 deltatime) {
 			_subId = 0;
 			_subsFocus.clear();
 		}
-	if (redraw) {
+	if (_redraw) {
 		debug(4, "Redrawing subtitles");
 		//Blank subtitle buffer
 		_renderManager->clearTextSurface();
@@ -78,17 +78,17 @@ void SubtitleManager::process(int32 deltatime) {
 			uint16 curSub = _subsFocus.get();
 			debug(4, "Rendering subtitle %d", curSub);
 			Subtitle *sub = _subsList[curSub];
-			if (sub->lineId >= 0) {
+			if (sub->_lineId >= 0) {
 				Graphics::Surface textSurface;
-				textSurface.create(sub->r.width(), sub->r.height(), _engine->_resourcePixelFormat);
-				textSurface.fillRect(Common::Rect(sub->r.width(), sub->r.height()), -1); //TODO Unnecessary operation?  Check later.
-				_engine->getTextRenderer()->drawTextWithWordWrapping(sub->_lines[sub->lineId].subStr, textSurface, _engine->isWidescreen());
-				_renderManager->blitSurfaceToText(textSurface, sub->r.left, sub->r.top, -1);
+				textSurface.create(sub->_textArea.width(), sub->_textArea.height(), _engine->_resourcePixelFormat);
+				textSurface.fillRect(Common::Rect(sub->_textArea.width(), sub->_textArea.height()), -1); //TODO Unnecessary operation?  Check later.
+				_engine->getTextRenderer()->drawTextWithWordWrapping(sub->_lines[sub->_lineId].subStr, textSurface, _engine->isWidescreen());
+				_renderManager->blitSurfaceToText(textSurface, sub->_textArea.left, sub->_textArea.top, -1);
 				textSurface.free();
-				sub->redraw = false;
+				sub->_redraw = false;
 			}
 		}
-		redraw = false;
+		_redraw = false;
 	}
 }
 
@@ -96,7 +96,7 @@ void SubtitleManager::update(int32 count, uint16 subid) {
 	if (_subsList.contains(subid))
 		if (_subsList[subid]->update(count)) {
 			//_subsFocus.set(subid);
-			redraw = true;
+			_redraw = true;
 		}
 }
 
@@ -127,14 +127,14 @@ uint16 SubtitleManager::create(const Common::String &str) {
 void SubtitleManager::destroy(uint16 id) {
 	if (_subsList.contains(id)) {
 		debug(2, "Marking subtitle %d for immediate deletion", id);
-		_subsList[id]->todelete = true;
+		_subsList[id]->_toDelete = true;
 	}
 }
 
 void SubtitleManager::destroy(uint16 id, int16 delay) {
 	if (_subsList.contains(id)) {
 		debug(2, "Marking subtitle %d for deletion in %dms", id, delay);
-		_subsList[id]->timer = delay;
+		_subsList[id]->_timer = delay;
 	}
 }
 
@@ -244,10 +244,10 @@ void SubtitleManager::showDebugMsg(const Common::String &msg, int16 delay) {
 
 Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool vob) :
 	_engine(engine),
-	lineId(-1),
-	timer(-1),
-	todelete(false),
-	redraw(false) {
+	_lineId(-1),
+	_timer(-1),
+	_toDelete(false),
+	_redraw(false) {
 	Common::File subFile;
 	Common::Point _textOffset = _engine->getSubtitleManager()->getTextOffset();
 	if (_engine->getSearchManager()->openFile(subFile, subname)) {
@@ -261,13 +261,13 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool vob) :
 			} else if (str.matchString("*Rectangle*", true)) {
 				int32 x1, y1, x2, y2;
 				sscanf(str.c_str(), "%*[^:]:%d %d %d %d", &x1, &y1, &x2, &y2);
-				r = Common::Rect(x1, y1, x2, y2);
+				_textArea = Common::Rect(x1, y1, x2, y2);
 				debug(1, "Original subtitle script rectangle coordinates: l%d, t%d, r%d, b%d", x1, y1, x2, y2);
 				//Original game subtitle scripts appear to define subtitle rectangles relative to origin of working area.
 				//To allow arbitrary aspect ratios, we need to instead place these relative to origin of text area.
 				//This will allow the managed text area to then be arbitrarily placed on the screen to suit different aspect ratios.
-				r.translate(_textOffset.x, _textOffset.y);  //Convert working area coordinates to text area coordinates
-				debug(1, "Text area coordinates: l%d, t%d, r%d, b%d", r.left, r.top, r.right, r.bottom);
+				_textArea.translate(_textOffset.x, _textOffset.y);  //Convert working area coordinates to text area coordinates
+				debug(1, "Text area coordinates: l%d, t%d, r%d, b%d", _textArea.left, _textArea.top, _textArea.right, _textArea.bottom);
 			} else if (str.matchString("*TextFile*", true)) {
 				char filename[64];
 				sscanf(str.c_str(), "%*[^:]:%s", filename);
@@ -275,7 +275,7 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool vob) :
 				if (_engine->getSearchManager()->openFile(txtFile, Common::Path(filename))) {
 					while (!txtFile.eos()) {
 						Common::String txtline = readWideLine(txtFile).encode();
-						line curLine;
+						Line curLine;
 						curLine.start = -1;
 						curLine.stop = -1;
 						curLine.subStr = txtline;
@@ -305,19 +305,19 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool vob) :
 		subFile.close();
 	} else {
 		//TODO - add error message here
-		todelete = true;
+		_toDelete = true;
 	}
 }
 
 Subtitle::Subtitle(ZVision *engine, const Common::String &str, const Common::Rect &textArea) :
 	_engine(engine),
-	lineId(-1),
-	timer(-1),
-	todelete(false),
-	redraw(false) {
-	r = textArea;
-	debug(1, "Text area coordinates: l%d, t%d, r%d, b%d", r.left, r.top, r.right, r.bottom);
-	line curLine;
+	_lineId(-1),
+	_timer(-1),
+	_toDelete(false),
+	_redraw(false) {
+	_textArea = textArea;
+	debug(1, "Text area coordinates: l%d, t%d, r%d, b%d", _textArea.left, _textArea.top, _textArea.right, _textArea.bottom);
+	Line curLine;
 	curLine.start = -1;
 	curLine.stop = 0;
 	curLine.subStr = str;
@@ -329,38 +329,38 @@ Subtitle::~Subtitle() {
 }
 
 bool Subtitle::process(int32 deltatime) {
-	if (timer != -1) {
-		timer -= deltatime;
-		if (timer <= 0)
-			todelete = true;
+	if (_timer != -1) {
+		_timer -= deltatime;
+		if (_timer <= 0)
+			_toDelete = true;
 	}
-	return todelete;
+	return _toDelete;
 }
 
 bool Subtitle::update(int32 count) {
 	int16 j = -1;
 	//Search all lines to find first line that encompasses current time/framecount, set j to this
-	for (uint16 i = (lineId >= 0 ? lineId : 0); i < _lines.size(); i++)
+	for (uint16 i = (_lineId >= 0 ? _lineId : 0); i < _lines.size(); i++)
 		if (count >= _lines[i].start && count <= _lines[i].stop) {
 			j = i;
 			break;
 		}
 	if (j == -1) {
 		//No line exists for current time/framecount
-		if (lineId != -1) {
+		if (_lineId != -1) {
 			//Line is set
-			lineId = -1; //Unset line
-			redraw = true;
+			_lineId = -1; //Unset line
+			_redraw = true;
 		}
 	} else {
 		//Line exists for current time/framecount
-		if (j != lineId && _lines[j].subStr.size()) {
+		if (j != _lineId && _lines[j].subStr.size()) {
 			//Set line is not equal to current line & current line is not blank
-			lineId = j;  //Set line to current
-			redraw = true;
+			_lineId = j;  //Set line to current
+			_redraw = true;
 		}
 	}
-	return redraw;
+	return _redraw;
 }
 
 AutomaticSubtitle::AutomaticSubtitle(ZVision *engine, const Common::Path &subname, Audio::SoundHandle handle) :
@@ -372,7 +372,7 @@ bool AutomaticSubtitle::selfUpdate() {
 	if (_engine->_mixer->isSoundHandleActive(_handle) && _engine->getScriptManager()->getStateValue(StateKey_Subtitles) == 1)
 		return update(_engine->_mixer->getSoundElapsedTime(_handle) / 100);
 	else {
-		todelete = true;
+		_toDelete = true;
 		return false;
 	}
 }
@@ -380,8 +380,8 @@ bool AutomaticSubtitle::selfUpdate() {
 bool AutomaticSubtitle::process(int32 deltatime) {
 	Subtitle::process(deltatime);
 	if (!_engine->_mixer->isSoundHandleActive(_handle))
-		todelete = true;
-	return todelete;
+		_toDelete = true;
+	return _toDelete;
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/text/subtitle_manager.h b/engines/zvision/text/subtitle_manager.h
index e1b3f1a753e..aa6a48b199c 100644
--- a/engines/zvision/text/subtitle_manager.h
+++ b/engines/zvision/text/subtitle_manager.h
@@ -44,14 +44,14 @@ public:
 protected:
 	virtual bool process(int32 deltatime);  //Return true if to be deleted
 	ZVision *_engine;
-	Common::Rect r;
-	Common::String txt;
-	int16  timer; //Always in milliseconds; countdown to deletion
-	bool todelete;
-	bool redraw;
-
-	int16 lineId;
-	struct line {
+	Common::Rect _textArea;
+	//Common::String _txt;
+	int16 _timer; //Always in milliseconds; countdown to deletion
+	bool _toDelete;
+	bool _redraw;
+
+	int16 _lineId;
+	struct Line {
 		int start;
 		int stop;
 		Common::String subStr;
@@ -62,7 +62,7 @@ protected:
 	//AVI videos run at 15fps and can have frames counted directly
 	//DVD videos in VOB format run at 29.97 fps and must be converted to work with the subtitle files, which were made for AVI.
 
-	Common::Array<line> _lines;
+	Common::Array<Line> _lines;
 };
 
 class AutomaticSubtitle : public Subtitle {
@@ -87,7 +87,7 @@ private:
 	const Graphics::PixelFormat _pixelFormat;
 	const Common::Point _textOffset;  //Position vector of text area origin relative to working window origin
 	const Common::Rect _textArea;
-	bool redraw;
+	bool _redraw;
 	bool _doubleFPS;
 	// Internal subtitle ID counter
 	uint16 _subId;
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index 469351e1f07..ce745f6ccc3 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -59,7 +59,7 @@ namespace ZVision {
 
 #define ZVISION_SETTINGS_KEYS_COUNT 12
 
-struct zvisionIniSettings {
+struct ZvisionIniSettings {
 	const char *name;
 	int16 slot;
 	int16 defaultValue; // -1: use the bool value


Commit: f35303bd193852679d7355cb39d2c3904b905b80
    https://github.com/scummvm/scummvm/commit/f35303bd193852679d7355cb39d2c3904b905b80
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:59+02:00

Commit Message:
COMMON: Code formatting & convention adjustment to minimise diff bloat.
Unnecessary whitespace & bracket layout changes removed.

Changed paths:
    common/rect.h


diff --git a/common/rect.h b/common/rect.h
index 6a3c895e9f1..10a59f40c7b 100644
--- a/common/rect.h
+++ b/common/rect.h
@@ -43,8 +43,8 @@ namespace Common {
  * Simple class for handling both 2D position and size.
  */
 struct Point {
-	int16 x;    /*!< The horizontal position of the point. */
-	int16 y;    /*!< The vertical position of the point. */
+	int16 x;	/*!< The horizontal position of the point. */
+	int16 y;	/*!< The vertical position of the point. */
 
 	constexpr Point() : x(0), y(0) {}
 
@@ -55,51 +55,35 @@ struct Point {
 	/**
 	 * Determine whether the position of two points is the same.
 	 */
-	bool  operator==(const Point &p)    const {
-		return x == p.x && y == p.y;
-	}
+	bool  operator==(const Point &p)    const { return x == p.x && y == p.y; }
 	/**
 	 * Determine whether the position of two points is not the same.
 	 */
-	bool  operator!=(const Point &p)    const {
-		return x != p.x || y != p.y;
-	}
+	bool  operator!=(const Point &p)    const { return x != p.x || y != p.y; }
 	/**
 	 * Create a point by adding the @p delta value to a point.
 	 */
-	Point operator+(const Point &delta) const {
-		return Point(x + delta.x, y + delta.y);
-	}
+	Point operator+(const Point &delta) const { return Point(x + delta.x, y + delta.y); }
 	/**
 	 * Create a point by subtracting the @p delta value from a point.
 	 */
-	Point operator-(const Point &delta) const {
-		return Point(x - delta.x, y - delta.y);
-	}
+	Point operator-(const Point &delta) const { return Point(x - delta.x, y - delta.y); }
 	/**
 	 * Create a point by dividing a point by the (int) @p divisor value.
 	 */
-	Point operator/(int divisor) const {
-		return Point(x / divisor, y / divisor);
-	}
+	Point operator/(int divisor) const { return Point(x / divisor, y / divisor); }
 	/**
 	 * Create a point by multiplying a point by the (int) @p multiplier value.
 	 */
-	Point operator*(int multiplier) const {
-		return Point(x * multiplier, y * multiplier);
-	}
+	Point operator*(int multiplier) const { return Point(x * multiplier, y * multiplier); }
 	/**
 	 * Create a point by dividing a point by the (double) @p divisor value.
 	 */
-	Point operator/(double divisor) const {
-		return Point((int16)(x / divisor), (int16)(y / divisor));
-	}
+	Point operator/(double divisor) const { return Point((int16)(x / divisor), (int16)(y / divisor)); }
 	/**
 	 * Create a point by multiplying a point by the (double) @p multiplier value.
 	 */
-	Point operator*(double multiplier) const {
-		return Point((int16)(x * multiplier), (int16)(y * multiplier));
-	}
+	Point operator*(double multiplier) const { return Point((int16)(x * multiplier), (int16)(y * multiplier)); }
 
 	/**
 	 * Change a point's position by adding @p delta to its x and y coordinates.
@@ -120,7 +104,7 @@ struct Point {
 	/**
 	 * Return the square of the distance between this point and the point @p p.
 	 *
-	 * @param p     The other point.
+	 * @param p		The other point.
 	 * @return      The distance between this and @p p.
 	 */
 	uint sqrDist(const Point &p) const {
@@ -136,12 +120,8 @@ struct Point {
 	}
 };
 
-static inline Point operator*(int multiplier, const Point &p) {
-	return Point(p.x * multiplier, p.y * multiplier);
-}
-static inline Point operator*(double multiplier, const Point &p) {
-	return Point((int16)(p.x * multiplier), (int16)(p.y * multiplier));
-}
+static inline Point operator*(int multiplier, const Point &p) { return Point(p.x * multiplier, p.y * multiplier); }
+static inline Point operator*(double multiplier, const Point &p) { return Point((int16)(p.x * multiplier), (int16)(p.y * multiplier)); }
 
 /**
  * Simple class for handling a rectangular zone.
@@ -162,8 +142,8 @@ static inline Point operator*(double multiplier, const Point &p) {
  * When writing code using our Rect class, always keep this principle in mind!
 */
 struct Rect {
-	int16 top, left;        /*!< The point at the top left of the rectangle (part of the Rect). */
-	int16 bottom, right;    /*!< The point at the bottom right of the rectangle (not part of the Rect). */
+	int16 top, left;		/*!< The point at the top left of the rectangle (part of the Rect). */
+	int16 bottom, right;	/*!< The point at the bottom right of the rectangle (not part of the Rect). */
 
 	constexpr Rect() : top(0), left(0), bottom(0), right(0) {}
 	/**
@@ -200,27 +180,17 @@ struct Rect {
 	 *
 	 * @return True if the rectangles are identical, false otherwise.
 	 */
-	bool operator==(const Rect &rhs) const {
-		return equals(rhs);
-	}
+	bool operator==(const Rect &rhs) const { return equals(rhs); }
 	/**
 	 * Check if two rectangles are different.
 	 *
 	 * @return True if the rectangles are different, false otherwise.
 	 */
-	bool operator!=(const Rect &rhs) const {
-		return !equals(rhs);
-	}
+	bool operator!=(const Rect &rhs) const { return !equals(rhs); }
 
-	Common::Point origin() const {
-		return Common::Point(left, top);    /*!< Return the origin of a rectangle. */
-	}
-	int16 width() const {
-		return right - left;    /*!< Return the width of a rectangle. */
-	}
-	int16 height() const {
-		return bottom - top;    /*!< Return the height of a rectangle. */
-	}
+	Common::Point origin() const { return Common::Point(left, top); } /*!< Return the origin of a rectangle. */
+	int16 width() const { return right - left; }                      /*!< Return the width of a rectangle. */
+	int16 height() const { return bottom - top; }                     /*!< Return the height of a rectangle. */
 
 	void setWidth(int16 aWidth) {   /*!< Set the width to @p aWidth value. */
 		right = left + aWidth;
@@ -345,14 +315,14 @@ struct Rect {
 		else if (right < r.left) right = r.left;
 	}
 
-	/**
+   	/**
 	 * Reduce the dimensions of this rectangle by setting max width and max height.
 	 */
 	void clip(int16 maxw, int16 maxh) {
 		clip(Rect(0, 0, maxw, maxh));
 	}
 
-	/**
+   	/**
 	 * Check if the rectangle is empty (its width or length is 0) or invalid (its width or length are negative).
 	 *
 	 * @retval true  The rectangle is empty or invalid.
@@ -383,10 +353,8 @@ struct Rect {
 	 * Move the rectangle by the given delta x and y values.
 	 */
 	void translate(int16 dx, int16 dy) {
-		left += dx;
-		right += dx;
-		top += dy;
-		bottom += dy;
+		left += dx; right += dx;
+		top += dy; bottom += dy;
 	}
 
 	/**
@@ -396,24 +364,24 @@ struct Rect {
 		moveTo(p.x, p.y);
 	}
 
-	/**
-	* Print debug messages related to this class.
-	*/
+	 /**
+	 * Print debug messages related to this class.
+	 */
 	void debugPrint(int debuglevel = 0, const char *caption = "Rect:") const {
 		debug(debuglevel, "%s %d, %d, %d, %d", caption, left, top, right, bottom);
 	}
 
-	/**
-	* Print debug messages related to this class.
-	*/
+	 /**
+	 * Print debug messages related to this class.
+	 */
 	void debugPrintC(int debuglevel, uint32 debugChannel, const char *caption = "Rect:") const {
 		debugC(debuglevel, debugChannel, "%s %d, %d, %d, %d", caption, left, top, right, bottom);
 	}
 
 	/**
-	* Create a rectangle around the given center.
-	* @note The center point is rounded up and left when given an odd width and height.
-	*/
+	 * Create a rectangle around the given center.
+	 * @note The center point is rounded up and left when given an odd width and height.
+	 */
 	static Rect center(int16 cx, int16 cy, int16 w, int16 h) {
 		int x = cx - w / 2, y = cy - h / 2;
 		return Rect(x, y, x + w, y + h);


Commit: 149089e01e72213575ba0cce9415357ba107ce8a
    https://github.com/scummvm/scummvm/commit/149089e01e72213575ba0cce9415357ba107ce8a
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:59+02:00

Commit Message:
GRAPHICS: Code formatting & convention adjustment to minimise diff bloat.
Remove unecessary whitespace & bracket layout changes.
Update outdated variable names in commented out old code in case it needs to be reinstated.

Changed paths:
    graphics/framelimiter.cpp
    graphics/framelimiter.h


diff --git a/graphics/framelimiter.cpp b/graphics/framelimiter.cpp
index f0b702b321f..a1f9bf610fe 100644
--- a/graphics/framelimiter.cpp
+++ b/graphics/framelimiter.cpp
@@ -20,6 +20,7 @@
  */
 
 #include "graphics/framelimiter.h"
+
 #include "common/util.h"
 
 namespace Graphics {
@@ -61,7 +62,7 @@ bool FrameLimiter::delayBeforeSwap() {
 	_now = _system->getMillis();
 	_loopDuration = _now - _frameStart;
 	if (_enabled) {
-		//delay = frameLimit - loopDuration;  //Original functionality, will tend to undershoot target framerate slightly due to finite screen.update() time.
+		//_delay = _frameLimit - _loopDuration;  //Original functionality, will tend to undershoot target framerate slightly due to finite screen.update() time.
 		_delay = _frameLimit - (_now - _drawStart); //Ensure EXACTLY the specified frame duration has elapsed since last screen.update() was called.
 		if (_delay > 0)
 			_system->delayMillis(_delay);
diff --git a/graphics/framelimiter.h b/graphics/framelimiter.h
index a5e1d9f474d..589ef76122e 100644
--- a/graphics/framelimiter.h
+++ b/graphics/framelimiter.h
@@ -93,6 +93,7 @@ public:
 
 private:
 	OSystem *_system;
+
 	bool _enabled;
 	bool _deferToVsync;
 	uint _frameStart;  //Time at which screen update completed and startFrame() was called; start of next cycle of game logic


Commit: ef1fced74c3f4457830611a655c026f4ab4c9280
    https://github.com/scummvm/scummvm/commit/ef1fced74c3f4457830611a655c026f4ab4c9280
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:59+02:00

Commit Message:
ZVISION: Code formatting & convention adjustment to minimise diff bloat.
Remove unecessary whitespace & bracket layout changes.
Remove unnecessary "fall through" comments.

Changed paths:
    engines/zvision/common/scroller.cpp
    engines/zvision/core/events.cpp
    engines/zvision/detection_tables.h
    engines/zvision/file/save_manager.cpp
    engines/zvision/graphics/cursors/cursor_manager.cpp
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h
    engines/zvision/metaengine.cpp
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/control.cpp
    engines/zvision/scripting/controls/fist_control.h
    engines/zvision/scripting/controls/hotmov_control.h
    engines/zvision/scripting/controls/input_control.h
    engines/zvision/scripting/controls/lever_control.h
    engines/zvision/scripting/controls/safe_control.h
    engines/zvision/scripting/effects/animation_effect.cpp
    engines/zvision/scripting/effects/animation_effect.h
    engines/zvision/scripting/effects/distort_effect.cpp
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/effects/music_effect.h
    engines/zvision/scripting/effects/syncsound_effect.cpp
    engines/zvision/scripting/menu.cpp
    engines/zvision/scripting/scr_file_handling.cpp
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/scripting/script_manager.h
    engines/zvision/sound/midi.cpp
    engines/zvision/sound/midi.h
    engines/zvision/sound/volume_manager.cpp
    engines/zvision/sound/zork_raw.cpp
    engines/zvision/sound/zork_raw.h
    engines/zvision/text/text.cpp
    engines/zvision/text/truetype_font.cpp
    engines/zvision/video/rlf_decoder.cpp
    engines/zvision/video/rlf_decoder.h
    engines/zvision/video/video.cpp
    engines/zvision/video/zork_avi_decoder.cpp
    engines/zvision/zvision.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/common/scroller.cpp b/engines/zvision/common/scroller.cpp
index c5a1b106050..871571e3e8b 100644
--- a/engines/zvision/common/scroller.cpp
+++ b/engines/zvision/common/scroller.cpp
@@ -19,7 +19,7 @@
  *
  */
 
-#include "./scroller.h"
+#include "zvision/common/scroller.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/core/events.cpp b/engines/zvision/core/events.cpp
index d1633273a34..714d24f8c26 100644
--- a/engines/zvision/core/events.cpp
+++ b/engines/zvision/core/events.cpp
@@ -202,7 +202,6 @@ void ZVision::processEvents() {
 		case Common::EVENT_CUSTOM_ENGINE_ACTION_START:
 			switch ((ZVisionAction)_event.customType) {
 			case kZVisionActionLeft:
-			// fall through
 			case kZVisionActionRight:
 				if (_renderManager->getRenderTable()->getRenderState() == RenderTable::PANORAMA)
 					_keyboardVelocity = (_event.customType == kZVisionActionLeft ?
@@ -211,7 +210,6 @@ void ZVision::processEvents() {
 				break;
 
 			case kZVisionActionUp:
-			// fall through
 			case kZVisionActionDown:
 				if (_renderManager->getRenderTable()->getRenderState() == RenderTable::TILT)
 					_keyboardVelocity = (_event.customType == kZVisionActionUp ?
@@ -256,13 +254,11 @@ void ZVision::processEvents() {
 		case Common::EVENT_CUSTOM_ENGINE_ACTION_END:
 			switch ((ZVisionAction)_event.customType) {
 			case kZVisionActionLeft:
-			// fall through
 			case kZVisionActionRight:
 				if (_renderManager->getRenderTable()->getRenderState() == RenderTable::PANORAMA)
 					_keyboardVelocity = 0;
 				break;
 			case kZVisionActionUp:
-			// fall through
 			case kZVisionActionDown:
 				if (_renderManager->getRenderTable()->getRenderState() == RenderTable::TILT)
 					_keyboardVelocity = 0;
@@ -370,7 +366,6 @@ void ZVision::onMouseMove(const Common::Point &pos) {
 				_mouseVelocity = 0;
 			break;
 		case RenderTable::FLAT:
-		// fall through
 		default:
 			_mouseVelocity = 0;
 			break;
diff --git a/engines/zvision/detection_tables.h b/engines/zvision/detection_tables.h
index 612f66a7154..bb56fe3dff0 100644
--- a/engines/zvision/detection_tables.h
+++ b/engines/zvision/detection_tables.h
@@ -63,8 +63,8 @@ static const ZVisionGameDescription gameDescriptions[] = {
 		{
 			"znemesis",
 			0,
-			AD_ENTRY2s("CSCR.ZFS",      "f04113357b4748c13efcb58b4629887c", 2577873,
-			           "NEMESIS.STR",   "333bcb17bbb7f57cae742fbbe44f56f3", 9219),
+			AD_ENTRY2s("CSCR.ZFS",		"f04113357b4748c13efcb58b4629887c", 2577873,
+					   "NEMESIS.STR",	"333bcb17bbb7f57cae742fbbe44f56f3", 9219),
 			Common::FR_FRA,
 			Common::kPlatformDOS,
 			ADGF_NO_FLAGS,
@@ -78,8 +78,8 @@ static const ZVisionGameDescription gameDescriptions[] = {
 		{
 			"znemesis",
 			0,
-			AD_ENTRY2s("CSCR.ZFS",      "f04113357b4748c13efcb58b4629887c", 2577873,
-			           "NEMESIS.STR",   "3d1a12b907751653866cffc6d4dfb331", 9505),
+			AD_ENTRY2s("CSCR.ZFS",		"f04113357b4748c13efcb58b4629887c", 2577873,
+					   "NEMESIS.STR",	"3d1a12b907751653866cffc6d4dfb331", 9505),
 			Common::DE_DEU,
 			Common::kPlatformDOS,
 			ADGF_NO_FLAGS,
@@ -93,8 +93,8 @@ static const ZVisionGameDescription gameDescriptions[] = {
 		{
 			"znemesis",
 			0,
-			AD_ENTRY2s("CSCR.ZFS",      "f04113357b4748c13efcb58b4629887c", 2577873,
-			           "NEMESIS.STR",   "7c568feca8d9f9ae855c47183612c305", 9061),
+			AD_ENTRY2s("CSCR.ZFS",		"f04113357b4748c13efcb58b4629887c", 2577873,
+					   "NEMESIS.STR",	"7c568feca8d9f9ae855c47183612c305", 9061),
 			Common::IT_ITA,
 			Common::kPlatformDOS,
 			ADGF_NO_FLAGS,
@@ -216,7 +216,7 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			"zgi",
 			"CD",
 			AD_ENTRY2s("SCRIPTS.ZFS",  "81efd40ecc3d22531e211368b779f17f", 8336944,
-			           "G0LPH10P.RAW", "c0b1f28b1cd1aaeb83c1a3985401bb14", 24462),
+					   "G0LPH10P.RAW", "c0b1f28b1cd1aaeb83c1a3985401bb14", 24462),
 			Common::EN_ANY,
 			Common::kPlatformMacintosh,
 			ADGF_NO_FLAGS,
@@ -234,11 +234,11 @@ static const ZVisionGameDescription gameDescriptions[] = {
 			Common::EN_ANY,
 			Common::kPlatformWindows,
 			ADGF_DVD,
-			#if defined(USE_MPEG2) && defined(USE_A52)
+#if defined(USE_MPEG2) && defined(USE_A52)
 			GUIO6(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_USE_HIRES_MPEG_MOVIES, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
-			#else
+#else
 			GUIO5(GAMEOPTION_ORIGINAL_SAVELOAD, GAMEOPTION_DOUBLE_FPS, GAMEOPTION_DISABLE_ANIM_WHILE_TURNING, GAMEOPTION_ENABLE_WIDESCREEN, GAMEOPTION_HQ_PANORAMA)
-			#endif
+#endif
 		},
 		GID_GRANDINQUISITOR
 	},
diff --git a/engines/zvision/file/save_manager.cpp b/engines/zvision/file/save_manager.cpp
index 10e1087ce86..1681715b238 100644
--- a/engines/zvision/file/save_manager.cpp
+++ b/engines/zvision/file/save_manager.cpp
@@ -36,7 +36,6 @@
 #include "gui/saveload.h"
 
 #include "common/config-manager.h"
-
 namespace ZVision {
 
 const uint32 SaveManager::SAVEGAME_ID = MKTAG('Z', 'E', 'N', 'G');
@@ -45,23 +44,30 @@ bool SaveManager::scummVMSaveLoadDialog(bool isSave) {
 	GUI::SaveLoadChooser *dialog;
 	Common::String desc;
 	int slot;
+
 	if (isSave) {
 		dialog = new GUI::SaveLoadChooser(_("Save game:"), _("Save"), true);
+
 		slot = dialog->runModalWithCurrentTarget();
 		desc = dialog->getResultString();
+
 		if (desc.empty()) {
 			// create our own description for the saved game, the user didn't enter it
 			desc = dialog->createDefaultSaveDescription(slot);
 		}
+
 		if (desc.size() > 28)
 			desc = Common::String(desc.c_str(), 28);
 	} else {
 		dialog = new GUI::SaveLoadChooser(_("Restore game:"), _("Restore"), false);
 		slot = dialog->runModalWithCurrentTarget();
 	}
+
 	delete dialog;
+
 	if (slot < 0)
 		return false;
+
 	if (isSave) {
 		saveGame(slot, desc, false);
 		return true;
@@ -74,32 +80,42 @@ bool SaveManager::scummVMSaveLoadDialog(bool isSave) {
 void SaveManager::saveGame(uint slot, const Common::String &saveName, bool useSaveBuffer) {
 	if (!_tempSave && useSaveBuffer)
 		return;
+
 	Common::SaveFileManager *saveFileManager = g_system->getSavefileManager();
 	Common::OutSaveFile *file = saveFileManager->openForSaving(_engine->getSaveStateName(slot));
+
 	writeSaveGameHeader(file, saveName, useSaveBuffer);
+
 	if (useSaveBuffer)
 		file->write(_tempSave->getData(), _tempSave->size());
 	else
 		_engine->getScriptManager()->serialize(file);
+
 	file->finalize();
 	delete file;
+
 	if (useSaveBuffer)
 		flushSaveBuffer();
+
 	_lastSaveTime = g_system->getMillis();
 }
 
 void SaveManager::writeSaveGameHeader(Common::OutSaveFile *file, const Common::String &saveName, bool useSaveBuffer) {
 	file->writeUint32BE(SAVEGAME_ID);
+
 	// Write version
 	file->writeByte(SAVE_VERSION);
+
 	// Write savegame name
 	file->writeString(saveName);
 	file->writeByte(0);
+
 	// Save the game thumbnail
 	if (useSaveBuffer)
 		file->write(_tempThumbnail->getData(), _tempThumbnail->size());
 	else
 		Graphics::saveThumbnail(*file);
+
 	// Write out the save date/time
 	TimeDate td;
 	g_system->getTimeAndDate(td);
@@ -108,6 +124,7 @@ void SaveManager::writeSaveGameHeader(Common::OutSaveFile *file, const Common::S
 	file->writeSint16LE(td.tm_mday);
 	file->writeSint16LE(td.tm_hour);
 	file->writeSint16LE(td.tm_min);
+
 	file->writeUint32LE(g_engine->getTotalPlayTime() / 1000);
 }
 
@@ -166,10 +183,12 @@ Common::Error SaveManager::loadGame(int slot) {
 					scriptManager->unsetStateFlag(4652, Puzzle::DISABLED);
 				}
 			}
+
 		}
 		g_engine->setTotalPlayTime(header.playTime * 1000);
 		return Common::kNoError;
 	}
+
 }
 
 bool SaveManager::readSaveGameHeader(Common::InSaveFile *in, SaveGameHeader &header, bool skipThumbnail) {
@@ -203,12 +222,12 @@ bool SaveManager::readSaveGameHeader(Common::InSaveFile *in, SaveGameHeader &hea
 	if (header.version > SAVE_VERSION) {
 		uint tempVersion = header.version;
 		GUI::MessageDialog dialog(
-		    Common::U32String::format(
-		        _("This saved game uses version %u, but this engine only "
-		          "supports up to version %d. You will need an updated version "
-		          "of the engine to use this saved game."), tempVersion, SAVE_VERSION
-		    ),
-		    _("OK"));
+			Common::U32String::format(
+				_("This saved game uses version %u, but this engine only "
+				  "supports up to version %d. You will need an updated version "
+				  "of the engine to use this saved game."), tempVersion, SAVE_VERSION
+			),
+		_("OK"));
 		dialog.runModal();
 	}
 
@@ -232,6 +251,7 @@ bool SaveManager::readSaveGameHeader(Common::InSaveFile *in, SaveGameHeader &hea
 	if (header.version >= 2) {
 		header.playTime  = in->readUint32LE();
 	}
+
 	return true;
 }
 
@@ -244,6 +264,7 @@ Common::SeekableReadStream *SaveManager::getSlotFile(uint slot) {
 			filename = Common::Path(Common::String::format("inqsav%u.sav", slot));
 		else if (_engine->getGameId() == GID_NEMESIS)
 			filename = Common::Path(Common::String::format("nemsav%u.sav", slot));
+
 		saveFile = _engine->getSearchManager()->openFile(filename);
 		if (saveFile == NULL) {
 			Common::File *tmpFile = new Common::File;
@@ -253,7 +274,9 @@ Common::SeekableReadStream *SaveManager::getSlotFile(uint slot) {
 				saveFile = tmpFile;
 			}
 		}
+
 	}
+
 	return saveFile;
 }
 
@@ -261,6 +284,7 @@ void SaveManager::prepareSaveBuffer() {
 	delete _tempThumbnail;
 	_tempThumbnail = new Common::MemoryWriteStreamDynamic(DisposeAfterUse::YES);
 	Graphics::saveThumbnail(*_tempThumbnail);
+
 	delete _tempSave;
 	_tempSave = new Common::MemoryWriteStreamDynamic(DisposeAfterUse::YES);
 	_engine->getScriptManager()->serialize(_tempSave);
@@ -269,6 +293,7 @@ void SaveManager::prepareSaveBuffer() {
 void SaveManager::flushSaveBuffer() {
 	delete _tempThumbnail;
 	_tempThumbnail = NULL;
+
 	delete _tempSave;
 	_tempSave = NULL;
 }
diff --git a/engines/zvision/graphics/cursors/cursor_manager.cpp b/engines/zvision/graphics/cursors/cursor_manager.cpp
index b697b390951..62a9ec1c781 100644
--- a/engines/zvision/graphics/cursors/cursor_manager.cpp
+++ b/engines/zvision/graphics/cursors/cursor_manager.cpp
@@ -33,16 +33,16 @@
 namespace ZVision {
 
 const char *CursorManager::_cursorNames[NUM_CURSORS] = { "active", "arrow", "backward", "downarrow", "forward", "handpt", "handpu", "hdown", "hleft",
-                                                         "hright", "hup", "idle", "leftarrow", "rightarrow", "suggest_surround", "suggest_tilt", "turnaround", "zuparrow"
-                                                       };
+														 "hright", "hup", "idle", "leftarrow", "rightarrow", "suggest_surround", "suggest_tilt", "turnaround", "zuparrow"
+													   };
 
 const char *CursorManager::_zgiCursorFileNames[NUM_CURSORS] = { "g0gbc011.zcr", "g0gac011.zcr", "g0gac021.zcr", "g0gac031.zcr", "g0gac041.zcr", "g0gac051.zcr", "g0gac061.zcr", "g0gac071.zcr", "g0gac081.zcr",
-                                                                "g0gac091.zcr", "g0gac101.zcr", "g0gac011.zcr", "g0gac111.zcr", "g0gac121.zcr", "g0gac131.zcr", "g0gac141.zcr", "g0gac151.zcr", "g0gac161.zcr"
-                                                              };
+																"g0gac091.zcr", "g0gac101.zcr", "g0gac011.zcr", "g0gac111.zcr", "g0gac121.zcr", "g0gac131.zcr", "g0gac141.zcr", "g0gac151.zcr", "g0gac161.zcr"
+															  };
 
 const char *CursorManager::_zNemCursorFileNames[NUM_CURSORS] = { "00act", "arrow", "back", "down", "forw", "handpt", "handpu", "hdown", "hleft",
-                                                                 "hright", "hup", "00idle", "left", "right", "ssurr", "stilt", "turn", "up"
-                                                               };
+																 "hright", "hup", "00idle", "left", "right", "ssurr", "stilt", "turn", "up"
+															   };
 
 CursorManager::CursorManager(ZVision *engine, const Graphics::PixelFormat &pixelFormat)
 	: _engine(engine),
@@ -88,13 +88,13 @@ void CursorManager::setItemID(int id) {
 				file = Common::Path(Common::String::format("%2.2d%s%c.zcr", id, "act", 'b'));
 				_cursors[NUM_CURSORS + 1][0] = ZorkCursor(_engine, file);
 			} else if (_engine->getGameId() == GID_GRANDINQUISITOR) {
-				file = Common::Path(Common::String::format("g0b%cc%2.2x1.zcr", 'a', id));
+				file = Common::Path(Common::String::format("g0b%cc%2.2x1.zcr", 'a' , id));
 				_cursors[NUM_CURSORS][0] = ZorkCursor(_engine, file);
-				file = Common::Path(Common::String::format("g0b%cc%2.2x1.zcr", 'c', id));
+				file = Common::Path(Common::String::format("g0b%cc%2.2x1.zcr", 'c' , id));
 				_cursors[NUM_CURSORS][1] = ZorkCursor(_engine, file);
-				file = Common::Path(Common::String::format("g0b%cc%2.2x1.zcr", 'b', id));
+				file = Common::Path(Common::String::format("g0b%cc%2.2x1.zcr", 'b' , id));
 				_cursors[NUM_CURSORS + 1][0] = ZorkCursor(_engine, file);
-				file = Common::Path(Common::String::format("g0b%cc%2.2x1.zcr", 'd', id));
+				file = Common::Path(Common::String::format("g0b%cc%2.2x1.zcr", 'd' , id));
 				_cursors[NUM_CURSORS + 1][1] = ZorkCursor(_engine, file);
 			} else
 				return;
diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 1a53e5fcb97..5f8b8d131ed 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -37,9 +37,7 @@
 #include "image/tga.h"
 
 #include "graphics/blit.h"
-
 #include "common/debug.h"
-
 namespace ZVision {
 
 RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const Graphics::PixelFormat pixelFormat, bool doubleFPS, bool widescreen)
@@ -209,7 +207,6 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
 		//Apply panorama/tilt warp to background image
 		switch (_renderTable.getRenderState()) {
 		case RenderTable::PANORAMA:
-		// fall through
 		case RenderTable::TILT:
 			debug(5, "Rendering panorama");
 			if (!_backgroundSurfaceDirtyRect.isEmpty()) {
@@ -272,6 +269,7 @@ Graphics::ManagedSurface &RenderManager::getVidSurface(Common::Rect &dstRect) {
 void RenderManager::renderImageToBackground(const Common::Path &fileName, int16 destX, int16 destY) {
 	Graphics::Surface surface;
 	readImageToSurface(fileName, surface);
+
 	blitSurfaceToBkg(surface, destX, destY);
 	surface.free();
 }
@@ -279,6 +277,7 @@ void RenderManager::renderImageToBackground(const Common::Path &fileName, int16
 void RenderManager::renderImageToBackground(const Common::Path &fileName, int16 destX, int16 destY, uint32 colorkey) {
 	Graphics::Surface surface;
 	readImageToSurface(fileName, surface);
+
 	blitSurfaceToBkg(surface, destX, destY, colorkey);
 	surface.free();
 }
@@ -286,7 +285,9 @@ void RenderManager::renderImageToBackground(const Common::Path &fileName, int16
 void RenderManager::renderImageToBackground(const Common::Path &fileName, int16 destX, int16 destY, int16  keyX, int16 keyY) {
 	Graphics::Surface surface;
 	readImageToSurface(fileName, surface);
+
 	uint16 keycolor = *(uint16 *)surface.getBasePtr(keyX, keyY);
+
 	blitSurfaceToBkg(surface, destX, destY, keycolor);
 	surface.free();
 }
@@ -298,23 +299,29 @@ void RenderManager::readImageToSurface(const Common::Path &fileName, Graphics::S
 
 void RenderManager::readImageToSurface(const Common::Path &fileName, Graphics::Surface &destination, bool transposed) {
 	Common::File file;
+
 	if (!_engine->getSearchManager()->openFile(file, fileName)) {
 		warning("Could not open file %s", fileName.toString().c_str());
 		return;
 	}
+
 	// Read the magic number
 	// Some files are true TGA, while others are TGZ
 	uint32 fileType = file.readUint32BE();
+
 	int imageWidth;
 	int imageHeight;
 	Image::TGADecoder tga;
 	uint16 *buffer;
 	// All Z-Vision images are in RGB 555
 	destination.format = _engine->_resourcePixelFormat;
+
 	bool isTGZ;
+
 	// Check for TGZ files
 	if (fileType == MKTAG('T', 'G', 'Z', '\0')) {
 		isTGZ = true;
+
 		// TGZ files have a header and then Bitmap data that is compressed with LZSS
 		uint32 decompressedSize = file.readSint32LE() / 2;
 		imageWidth = file.readSint32LE();
@@ -323,49 +330,62 @@ void RenderManager::readImageToSurface(const Common::Path &fileName, Graphics::S
 		LzssReadStream lzssStream(&file);
 		buffer = (uint16 *)(new uint16[decompressedSize]);
 		lzssStream.read(buffer, 2 * decompressedSize);
-		#ifndef SCUMM_LITTLE_ENDIAN
+#ifndef SCUMM_LITTLE_ENDIAN
 		for (uint32 i = 0; i < decompressedSize; ++i)
 			buffer[i] = FROM_LE_16(buffer[i]);
-		#endif
+#endif
 	} else {
 		isTGZ = false;
+
 		// Reset the cursor
 		file.seek(0);
+
 		// Decode
 		if (!tga.loadStream(file)) {
 			warning("Error while reading TGA image");
 			return;
 		}
+
 		Graphics::Surface tgaSurface = *(tga.getSurface());
 		imageWidth = tgaSurface.w;
 		imageHeight = tgaSurface.h;
+
 		buffer = (uint16 *)tgaSurface.getPixels();
 	}
 
 	// Flip the width and height if transposed
-	if (transposed)
+	if (transposed) {
 		SWAP(imageWidth, imageHeight);
+	}
+
 	// If the destination internal buffer is the same size as what we're copying into it,
 	// there is no need to free() and re-create
-	if (imageWidth != destination.w || imageHeight != destination.h)
+	if (imageWidth != destination.w || imageHeight != destination.h) {
 		destination.create(imageWidth, imageHeight, _engine->_resourcePixelFormat);
+	}
+
 	// If transposed, 'un-transpose' the data while copying it to the destination
 	// Otherwise, just do a simple copy
 	if (transposed) {
 		uint16 *dest = (uint16 *)destination.getPixels();
+
 		for (int y = 0; y < imageHeight; ++y) {
 			uint32 columnIndex = y * imageWidth;
+
 			for (int x = 0; x < imageWidth; ++x) {
 				dest[columnIndex + x] = buffer[x * imageHeight + y];
 			}
 		}
-	} else
+	} else {
 		memcpy(destination.getPixels(), buffer, imageWidth * imageHeight * destination.format.bytesPerPixel);
+	}
+
 	// Cleanup
-	if (isTGZ)
+	if (isTGZ) {
 		delete[] buffer;
-	else
+	} else {
 		tga.destroy();
+	}
 }
 
 const Common::Point RenderManager::screenSpaceToImageSpace(const Common::Point &point) {
@@ -385,10 +405,13 @@ const Common::Point RenderManager::screenSpaceToImageSpace(const Common::Point &
 		default:
 			break;
 		}
+
+
 		if (_backgroundWidth)
 			newPoint.x %= _backgroundWidth;
 		if (_backgroundHeight)
 			newPoint.y %= _backgroundHeight;
+
 		if (newPoint.x < 0)
 			newPoint.x += _backgroundWidth;
 		if (newPoint.y < 0)
@@ -415,7 +438,6 @@ void RenderManager::setBackgroundImage(const Common::Path &fileName) {
 void RenderManager::setBackgroundPosition(int offset) {
 	switch (_renderTable.getRenderState()) {
 	case RenderTable::PANORAMA :
-	// fall through
 	case RenderTable::TILT :
 		if (_backgroundOffset != offset)
 			_backgroundDirtyRect = Common::Rect(_backgroundWidth, _backgroundHeight);
@@ -424,13 +446,13 @@ void RenderManager::setBackgroundPosition(int offset) {
 		break;
 	}
 	_backgroundOffset = offset;
+
 	_engine->getScriptManager()->setStateValue(StateKey_ViewPos, offset);
 }
 
 uint32 RenderManager::getCurrentBackgroundOffset() {
 	switch (_renderTable.getRenderState()) {
 	case RenderTable::PANORAMA :
-	// fall through
 	case RenderTable::TILT :
 		return _backgroundOffset;
 	default :
@@ -441,20 +463,27 @@ uint32 RenderManager::getCurrentBackgroundOffset() {
 Graphics::Surface *RenderManager::tranposeSurface(const Graphics::Surface *surface) {
 	Graphics::Surface *tranposedSurface = new Graphics::Surface();
 	tranposedSurface->create(surface->h, surface->w, surface->format);
+
 	const uint16 *source = (const uint16 *)surface->getPixels();
 	uint16 *dest = (uint16 *)tranposedSurface->getPixels();
+
 	for (int y = 0; y < tranposedSurface->h; ++y) {
 		int columnIndex = y * tranposedSurface->w;
-		for (int x = 0; x < tranposedSurface->w; ++x)
+
+		for (int x = 0; x < tranposedSurface->w; ++x) {
 			dest[columnIndex + x] = source[x * surface->w + y];
+		}
 	}
+
 	return tranposedSurface;
 }
 
 void RenderManager::scaleBuffer(const void *src, void *dst, uint32 srcWidth, uint32 srcHeight, byte bytesPerPixel, uint32 dstWidth, uint32 dstHeight) {
 	assert(bytesPerPixel == 1 || bytesPerPixel == 2);
+
 	const float  xscale = (float)srcWidth / (float)dstWidth;
 	const float  yscale = (float)srcHeight / (float)dstHeight;
+
 	if (bytesPerPixel == 1) {
 		const byte *srcPtr = (const byte *)src;
 		byte *dstPtr = (byte *)dst;
@@ -476,7 +505,6 @@ void RenderManager::scaleBuffer(const void *src, void *dst, uint32 srcWidth, uin
 	}
 }
 
-
 //ORIGINAL FUNCTION
 //*
 void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect, Graphics::Surface &dst, int _x, int _y) {
@@ -587,13 +615,13 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Com
 }
 //*/
 
-void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect, Graphics::Surface &dst, int _x, int _y, uint32 colorkey) {
+void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect , Graphics::Surface &dst, int _x, int _y, uint32 colorkey) {
 	debug(9, "blitSurfaceToSurface");
 	Common::Rect srcRect = _srcRect;
 	if (srcRect.isEmpty())
 		srcRect = Common::Rect(src.w, src.h);
 	srcRect.clip(src.w, src.h);
-	Common::Rect dstRect = Common::Rect(-_x + srcRect.left, -_y + srcRect.top, -_x + srcRect.left + dst.w, -_y + srcRect.top + dst.h);
+	Common::Rect dstRect = Common::Rect(-_x + srcRect.left , -_y + srcRect.top, -_x + srcRect.left + dst.w, -_y + srcRect.top + dst.h);
 	srcRect.clip(dstRect);
 
 	//Abort if nothing to blit
@@ -618,6 +646,8 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Com
 		byte *dstBuffer = (byte *)dst.getBasePtr(xx, yy);
 		Graphics::keyBlit(dstBuffer, srcBuffer, dst.pitch, srcAdapted->pitch, srcRect.width(), srcRect.height(), srcAdapted->format.bytesPerPixel, keycolor);
 	}
+
+
 	srcAdapted->free();
 	delete srcAdapted;
 }
@@ -637,9 +667,9 @@ void RenderManager::blitSurfaceToBkg(const Graphics::Surface &src, int x, int y,
 }
 
 void RenderManager::blitSurfaceToBkgScaled(const Graphics::Surface &src, const Common::Rect &_dstRect, int32 colorkey) {
-	if (src.w == _dstRect.width() && src.h == _dstRect.height())
+	if (src.w == _dstRect.width() && src.h == _dstRect.height()) {
 		blitSurfaceToBkg(src, _dstRect.left, _dstRect.top, colorkey);
-	else {
+	} else {
 		Graphics::Surface *tmp = new Graphics::Surface;
 		tmp->create(_dstRect.width(), _dstRect.height(), src.format);
 		scaleBuffer(src.getPixels(), tmp->getPixels(), src.w, src.h, src.format.bytesPerPixel, _dstRect.width(), _dstRect.height());
@@ -717,11 +747,15 @@ Graphics::Surface *RenderManager::getBkgRect(Common::Rect &rect) {
 	debug(11, "getBkgRect()");
 	Common::Rect dst = rect;
 	dst.clip(_backgroundWidth, _backgroundHeight);
+
 	if (dst.isEmpty() || !dst.isValidRect())
 		return NULL;
+
 	Graphics::Surface *srf = new Graphics::Surface;
 	srf->create(dst.width(), dst.height(), _currentBackgroundImage.format);
+
 	srf->copyRectToSurface(_currentBackgroundImage, 0, 0, Common::Rect(dst));
+
 	return srf;
 }
 
@@ -749,8 +783,9 @@ void RenderManager::prepareBackground() {
 		drawRect.clip(viewPort);
 
 		// Render the visible portion
-		if (!drawRect.isEmpty())
+		if (!drawRect.isEmpty()) {
 			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, _workingAreaCenter.x - _backgroundOffset + drawRect.left, drawRect.top);
+		}
 
 		// Mark the dirty portion of the surface
 		_backgroundSurfaceDirtyRect = _backgroundDirtyRect;
@@ -794,6 +829,7 @@ void RenderManager::prepareBackground() {
 		drawRect.clip(viewPort);
 		if (!drawRect.isEmpty())
 			blitSurfaceToSurface(_currentBackgroundImage, drawRect, _backgroundSurface, drawRect.left, _workingAreaCenter.y - _backgroundOffset + drawRect.top);
+
 		// Mark the dirty portion of the surface
 		_backgroundSurfaceDirtyRect = _backgroundDirtyRect;
 		_backgroundSurfaceDirtyRect.translate(0, _workingAreaCenter.y - _backgroundOffset);
@@ -871,8 +907,10 @@ EffectMap *RenderManager::makeEffectMap(const Common::Point &xy, int16 depth, co
 	Common::Rect bkgRect(_backgroundWidth, _backgroundHeight);
 	if (!bkgRect.contains(xy))
 		return NULL;
+
 	if (!bkgRect.intersects(rect))
 		return NULL;
+
 	uint16 color = *(uint16 *)_currentBackgroundImage.getBasePtr(xy.x, xy.y);
 	uint8 stC1, stC2, stC3;
 	_currentBackgroundImage.format.colorToRGB(color, stC1, stC2, stC3);
@@ -914,10 +952,12 @@ EffectMap *RenderManager::makeEffectMap(const Common::Point &xy, int16 depth, co
 				        (stC3 - cC3 < depth8))
 					use = true;
 			}
+
 			if (first) {
 				unit.inEffect = use;
 				first = false;
 			}
+
 			if (use) {
 				uint8 cMinComp = MIN(MIN(cC1, cC2), cC3);
 				uint8 cMaxComp = MAX(MAX(cC1, cC2), cC3);
@@ -926,6 +966,7 @@ EffectMap *RenderManager::makeEffectMap(const Common::Point &xy, int16 depth, co
 				if (cMaxComp > maxComp)
 					maxComp = cMaxComp;
 			}
+
 			if (unit.inEffect == use)
 				unit.count++;
 			else {
@@ -936,6 +977,7 @@ EffectMap *RenderManager::makeEffectMap(const Common::Point &xy, int16 depth, co
 		}
 	}
 	newMap->push_back(unit);
+
 	if (_minComp) {
 		if (minComp - depth8 < 0)
 			*_minComp = -(minComp >> 3);
@@ -948,6 +990,7 @@ EffectMap *RenderManager::makeEffectMap(const Common::Point &xy, int16 depth, co
 		else
 			*_maxComp = depth;
 	}
+
 	return newMap;
 }
 
@@ -955,20 +998,26 @@ EffectMap *RenderManager::makeEffectMap(const Graphics::Surface &surf, uint16 tr
 	EffectMapUnit unit;
 	unit.count = 0;
 	unit.inEffect = false;
+
 	int16 w = surf.w;
 	int16 h = surf.h;
+
 	EffectMap *newMap = new EffectMap;
+
 	bool first = true;
+
 	for (int16 j = 0; j < h; j++) {
 		const uint16 *pix = (const uint16 *)surf.getBasePtr(0, j);
 		for (int16 i = 0; i < w; i++) {
 			bool use = false;
 			if (pix[i] != transp)
 				use = true;
+
 			if (first) {
 				unit.inEffect = use;
 				first = false;
 			}
+
 			if (unit.inEffect == use)
 				unit.count++;
 			else {
@@ -979,6 +1028,7 @@ EffectMap *RenderManager::makeEffectMap(const Graphics::Surface &surf, uint16 tr
 		}
 	}
 	newMap->push_back(unit);
+
 	return newMap;
 }
 
@@ -993,38 +1043,50 @@ void RenderManager::bkgFill(uint8 r, uint8 g, uint8 b) {
 }
 //*/
 
+
 void RenderManager::updateRotation() {
 	int16 _velocity = _engine->getMouseVelocity() + _engine->getKeyboardVelocity();
 	ScriptManager *scriptManager = _engine->getScriptManager();
+
 	if (_doubleFPS | !_frameLimiter.isEnabled()) //Assuming 60fps when in Vsync mode.
 		_velocity /= 2;
+
 	if (_velocity) {
 		switch (_renderTable.getRenderState()) {
 		case RenderTable::PANORAMA : {
 			int16 startPosition = scriptManager->getStateValue(StateKey_ViewPos);
+
 			int16 newPosition = startPosition + (_renderTable.getPanoramaReverse() ? -_velocity : _velocity);
+
 			int16 zeroPoint = _renderTable.getPanoramaZeroPoint();
 			if (startPosition >= zeroPoint && newPosition < zeroPoint)
 				scriptManager->setStateValue(StateKey_Rounds, scriptManager->getStateValue(StateKey_Rounds) - 1);
 			if (startPosition <= zeroPoint && newPosition > zeroPoint)
 				scriptManager->setStateValue(StateKey_Rounds, scriptManager->getStateValue(StateKey_Rounds) + 1);
+
 			int16 screenWidth = getBkgSize().x;
 			if (screenWidth)
 				newPosition %= screenWidth;
+
 			if (newPosition < 0)
 				newPosition += screenWidth;
+
 			setBackgroundPosition(newPosition);
 			break;
 		}
 		case RenderTable::TILT : {
 			int16 startPosition = scriptManager->getStateValue(StateKey_ViewPos);
+
 			int16 newPosition = startPosition + _velocity;
+
 			int16 screenHeight = getBkgSize().y;
 			int16 tiltGap = (int16)_renderTable.getTiltGap();
+
 			if (newPosition >= (screenHeight - tiltGap))
 				newPosition = screenHeight - tiltGap;
 			if (newPosition <= tiltGap)
 				newPosition = tiltGap;
+
 			setBackgroundPosition(newPosition);
 			break;
 		}
@@ -1038,25 +1100,34 @@ void RenderManager::checkBorders() {
 	switch (_renderTable.getRenderState()) {
 	case RenderTable::PANORAMA: {
 		int16 startPosition = _engine->getScriptManager()->getStateValue(StateKey_ViewPos);
+
 		int16 newPosition = startPosition;
+
 		int16 screenWidth = getBkgSize().x;
+
 		if (screenWidth)
 			newPosition %= screenWidth;
+
 		if (newPosition < 0)
 			newPosition += screenWidth;
+
 		if (startPosition != newPosition)
 			setBackgroundPosition(newPosition);
 		break;
 	}
 	case RenderTable::TILT: {
 		int16 startPosition = _engine->getScriptManager()->getStateValue(StateKey_ViewPos);
+
 		int16 newPosition = startPosition;
+
 		int16 screenHeight = getBkgSize().y;
 		int16 tiltGap = (int16)_renderTable.getTiltGap();
+
 		if (newPosition >= (screenHeight - tiltGap))
 			newPosition = screenHeight - tiltGap;
 		if (newPosition <= tiltGap)
 			newPosition = tiltGap;
+
 		if (startPosition != newPosition)
 			setBackgroundPosition(newPosition);
 		break;
@@ -1072,11 +1143,14 @@ void RenderManager::rotateTo(int16 _toPos, int16 _time) {
 	debug(1, "Rotating panorama to %d", _toPos);
 	if (_time == 0)
 		_time = 1;
+
 	int32 maxX = getBkgSize().x;
 	int32 curX = getCurrentBackgroundOffset();
 	int32 dx = 0;
+
 	if (curX == _toPos)
 		return;
+
 	if (curX > _toPos) {
 		if (curX - _toPos > maxX / 2)
 			dx = (_toPos + (maxX - curX)) / _time;
@@ -1088,21 +1162,29 @@ void RenderManager::rotateTo(int16 _toPos, int16 _time) {
 		else
 			dx = (_toPos - curX) / _time;
 	}
+
 	_engine->stopClock();
+
 	for (int16 i = 0; i <= _time; i++) {
 		if (i == _time)
 			curX = _toPos;
 		else
 			curX += dx;
+
 		if (curX < 0)
 			curX = maxX - curX;
 		else if (curX >= maxX)
 			curX %= maxX;
+
 		setBackgroundPosition(curX);
+
 		prepareBackground();
 		renderSceneToScreen();
+
+
 		_system->delayMillis(500 / _time);
 	}
+
 	_engine->startClock();
 }
 
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index 79144a7ba57..ca0135972b5 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -22,6 +22,7 @@
 #ifndef ZVISION_RENDER_MANAGER_H
 #define ZVISION_RENDER_MANAGER_H
 
+#include "zvision/graphics/render_table.h"
 #include "zvision/text/truetype_font.h"
 
 #include "common/rect.h"
@@ -34,9 +35,6 @@
 
 #include "zvision/graphics/graphics_effect.h"
 
-#include "zvision/graphics/render_table.h"
-
-
 class OSystem;
 
 namespace Common {
@@ -55,7 +53,9 @@ public:
 	RenderManager(ZVision *engine, const ScreenLayout layout, const Graphics::PixelFormat pixelFormat, bool doubleFPS, bool widescreen = false);
 	~RenderManager();
 
+
 	typedef Common::List<GraphicsEffect *> EffectsList;
+
 private:
 	ZVision *_engine;
 	OSystem *_system;
@@ -148,15 +148,17 @@ private:
 	// A buffer to store the result of the panorama / tilt warps
 	Graphics::Surface _warpedSceneSurface;
 
+
 	/** Used to warp the background image */
 	RenderTable _renderTable;
 
+
+
 	// Visual effects list
 	EffectsList _effects;
 
 	//Pointer to currently active backbuffer output surface
 	Graphics::Surface *_outputSurface;
-
 	bool _doubleFPS;
 	bool _widescreen;
 
diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index 038f8719c7d..bb23e8d8fce 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -19,13 +19,12 @@
  *
  */
 
+#include "zvision/graphics/render_table.h"
+
 #include "common/rect.h"
 #include "common/scummsys.h"
 #include "math/utils.h"
-#include "zvision/zvision.h"
 #include "common/system.h"
-
-#include "zvision/graphics/render_table.h"
 #include "zvision/scripting/script_manager.h"
 
 namespace ZVision {
@@ -38,7 +37,9 @@ RenderTable::RenderTable(ZVision *engine, uint numColumns, uint numRows, const G
 	  _renderState(FLAT),
 	  _pixelFormat(pixelFormat) {
 	assert(numRows != 0 && numColumns != 0);
+
 	_internalBuffer = new FilterPixel[numRows * numColumns];
+
 	memset(&_panoramaOptions, 0, sizeof(_panoramaOptions));
 	memset(&_tiltOptions, 0, sizeof(_tiltOptions));
 	_halfRows = floor((_numRows - 1) / 2);
@@ -53,6 +54,7 @@ RenderTable::~RenderTable() {
 
 void RenderTable::setRenderState(RenderState newState) {
 	_renderState = newState;
+
 	switch (newState) {
 	case PANORAMA:
 		_panoramaOptions.verticalFOV = Math::deg2rad<float>(27.0f);
@@ -80,10 +82,13 @@ const Common::Point RenderTable::convertWarpedCoordToFlatCoord(const Common::Poi
 		int16 y = CLIP<int16>(point.y, 0, (int16)_numRows);
 		return Common::Point(x, y);
 	}
+
 	_index = point.y * _numColumns + point.x;
+
 	Common::Point newPoint(point);
 	newPoint.x += (_internalBuffer[_index]._xDir ? _internalBuffer[_index]._Src.right : _internalBuffer[_index]._Src.left);
 	newPoint.y += (_internalBuffer[_index]._yDir ? _internalBuffer[_index]._Src.bottom : _internalBuffer[_index]._Src.top);
+
 	return newPoint;
 }
 
@@ -126,6 +131,7 @@ void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 d
 
 void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf, bool highQuality) {
 	_destOffset = 0;
+
 	uint16 *sourceBuffer = (uint16 *)srcBuf->getPixels();
 	uint16 *destBuffer = (uint16 *)dstBuf->getPixels();
 	if (highQuality != _highQuality) {
@@ -286,11 +292,13 @@ void RenderTable::generateLookupTable(bool tilt) {
 
 void RenderTable::setPanoramaFoV(float fov) {
 	assert(fov > 0.0f);
+
 	_panoramaOptions.verticalFOV = Math::deg2rad<float>(fov);
 }
 
 void RenderTable::setPanoramaScale(float scale) {
 	assert(scale > 0.0f);
+
 	_panoramaOptions.linearScale = scale;
 }
 
@@ -312,11 +320,13 @@ uint16 RenderTable::getPanoramaZeroPoint() {
 
 void RenderTable::setTiltFoV(float fov) {
 	assert(fov > 0.0f);
+
 	_tiltOptions.verticalFOV = Math::deg2rad<float>(fov);
 }
 
 void RenderTable::setTiltScale(float scale) {
 	assert(scale > 0.0f);
+
 	_tiltOptions.linearScale = scale;
 }
 
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index 99b339674cb..bcbd2b058fa 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -22,11 +22,11 @@
 #ifndef ZVISION_RENDER_TABLE_H
 #define ZVISION_RENDER_TABLE_H
 
+#include "zvision/zvision.h"
 #include "common/rect.h"
 #include "graphics/surface.h"
 
 class OSystem;
-
 namespace ZVision {
 
 class FilterPixel {
@@ -90,7 +90,6 @@ public:
 	~RenderTable();
 
 //	Common::Point testPixel = Common::Point(255,0);
-
 public:
 	enum RenderState {
 		PANORAMA,
@@ -152,7 +151,6 @@ public:
 
 //	void mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 destWidth, const Common::Rect &subRect);
 	void mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf, bool filter = false);
-
 	template <typename I>
 	Common::String pixelToBinary(I &pixel, bool splitColors = true) {
 		uint8 bits = sizeof(pixel) << 3;
@@ -167,7 +165,6 @@ public:
 		}
 		return str;
 	}
-
 	void generateRenderTable();
 
 	void setPanoramaFoV(float fov); //Degrees
diff --git a/engines/zvision/metaengine.cpp b/engines/zvision/metaengine.cpp
index 5601ecd6a47..c839d442815 100644
--- a/engines/zvision/metaengine.cpp
+++ b/engines/zvision/metaengine.cpp
@@ -161,21 +161,21 @@ public:
 
 bool ZVisionMetaEngine::hasFeature(MetaEngineFeature f) const {
 	return
-	    (f == kSupportsListSaves) ||
-	    (f == kSupportsLoadingDuringStartup) ||
-	    (f == kSupportsDeleteSave) ||
-	    (f == kSavesSupportMetaInfo) ||
-	    (f == kSavesSupportThumbnail) ||
-	    (f == kSavesSupportCreationDate) ||
-	    (f == kSavesSupportPlayTime) ||
-	    (f == kSimpleSavesNames);
+		(f == kSupportsListSaves) ||
+		(f == kSupportsLoadingDuringStartup) ||
+		(f == kSupportsDeleteSave) ||
+		(f == kSavesSupportMetaInfo) ||
+		(f == kSavesSupportThumbnail) ||
+		(f == kSavesSupportCreationDate) ||
+		(f == kSavesSupportPlayTime) ||
+		(f == kSimpleSavesNames);
 }
 
 bool ZVision::ZVision::hasFeature(EngineFeature f) const {
 	return
-	    (f == kSupportsReturnToLauncher) ||
-	    (f == kSupportsLoadingDuringRuntime) ||
-	    (f == kSupportsSavingDuringRuntime);
+		(f == kSupportsReturnToLauncher) ||
+		(f == kSupportsLoadingDuringRuntime) ||
+		(f == kSupportsSavingDuringRuntime);
 }
 
 Common::Error ZVision::ZVision::loadGameState(int slot) {
@@ -325,7 +325,7 @@ Common::KeymapArray ZVisionMetaEngine::initKeymaps(const char *target) const {
 }
 
 Common::Error ZVisionMetaEngine::createInstance(OSystem *syst, Engine **engine, const ZVision::ZVisionGameDescription *desc) const {
-	*engine = new ZVision::ZVision(syst, desc);
+	*engine = new ZVision::ZVision(syst,desc);
 	return Common::kNoError;
 }
 
diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index 552009caa95..5c047a59c28 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -83,6 +83,7 @@ bool ActionAdd::execute() {
 ActionAssign::ActionAssign(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
 	_key = 0;
+
 	char buf[64];
 	memset(buf, 0, 64);
 	sscanf(line.c_str(), "%u, %s", &_key, buf);
@@ -180,12 +181,14 @@ bool ActionCrossfade::execute() {
 			mus->setFade(_timeInMillis, _oneEndVolume);
 		}
 	}
+
 	if (_keyTwo) {
 		ScriptingEffect *fx = _scriptManager->getSideFX(_keyTwo);
 		if (fx && fx->getType() == ScriptingEffect::SCRIPTING_EFFECT_AUDIO) {
 			MusicNodeBASE *mus = (MusicNodeBASE *)fx;
 			if (_twoStartVolume >= 0)
 				mus->setVolume(_twoStartVolume);
+
 			mus->setFade(_timeInMillis, _twoEndVolume);
 		}
 	}
@@ -545,14 +548,17 @@ bool ActionMusic::execute() {
 		_scriptManager->killSideFx(_slotKey);
 		_scriptManager->setStateValue(_slotKey, 2);
 	}
+
 	uint volume = _volume->getValue();
-	if (_midi)
+	if (_midi) {
 		_scriptManager->addSideFX(new MusicMidiNode(_engine, _slotKey, _prog, _note, volume));
-	else {
+	} else {
 		if (!_engine->getSearchManager()->hasFile(_fileName))
 			return true;
+
 		_scriptManager->addSideFX(new MusicNode(_engine, _slotKey, _fileName, _loop, volume));
 	}
+
 	return true;
 }
 
@@ -597,7 +603,9 @@ bool ActionPanTrack::execute() {
 	debug(3, "Executing Action: PanTrack, slotkey %d, musicSlot %u, pos %d, mag %d", _slotKey, _musicSlot, _pos, _mag);
 	if (_scriptManager->getSideFX(_slotKey))
 		return true;
+
 	_scriptManager->addSideFX(new PanTrackNode(_engine, _slotKey, _musicSlot, _pos, _mag, _resetMixerOnDelete, _staticScreen));
+
 	return true;
 }
 
@@ -618,6 +626,7 @@ bool ActionPreferences::execute() {
 		_engine->saveSettings();
 	else
 		_engine->loadSettings();
+
 	return true;
 }
 
@@ -667,13 +676,16 @@ bool ActionPreloadAnimation::execute() {
 ActionUnloadAnimation::ActionUnloadAnimation(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
 	_key = 0;
+
 	sscanf(line.c_str(), "%u", &_key);
 }
 
 bool ActionUnloadAnimation::execute() {
 	AnimationEffect *nod = (AnimationEffect *)_scriptManager->getSideFX(_key);
+
 	if (nod && nod->getType() == ScriptingEffect::SCRIPTING_EFFECT_ANIM)
 		_scriptManager->deleteSideFx(_key);
+
 	return true;
 }
 
@@ -692,6 +704,7 @@ ActionPlayAnimation::ActionPlayAnimation(ZVision *engine, int32 slotKey, const C
 	_loopCount = 0;
 	_mask = 0;
 	_framerate = 0;
+
 	char fileName[25];
 
 	// The two %*u are always 0 and dont seem to have a use
@@ -704,6 +717,7 @@ ActionPlayAnimation::ActionPlayAnimation(ZVision *engine, int32 slotKey, const C
 	// color 0, which is used as a mask in some images
 	if (_mask == 0)
 		_mask = -1;
+
 	_fileName = Common::String(fileName);
 
 	// WORKAROUND for bug #6769, location me1g.scr (the "Alchemical debacle"
@@ -720,13 +734,16 @@ ActionPlayAnimation::~ActionPlayAnimation() {
 
 bool ActionPlayAnimation::execute() {
 	AnimationEffect *nod = (AnimationEffect *)_scriptManager->getSideFX(_slotKey);
+
 	if (!nod) {
 		nod = new AnimationEffect(_engine, _slotKey, _fileName, _mask, _framerate);
 		_scriptManager->addSideFX(nod);
 	} else
 		nod->stop();
+
 	if (nod)
 		nod->addPlayNode(_slotKey, _x, _y, _x2, _y2, _start, _end, _loopCount);
+
 	return true;
 }
 
@@ -744,6 +761,7 @@ ActionPlayPreloadAnimation::ActionPlayPreloadAnimation(ZVision *engine, int32 sl
 	_startFrame = 0;
 	_endFrame = 0;
 	_loopCount = 0;
+
 	sscanf(line.c_str(),
 	       "%u %u %u %u %u %u %u %u",
 	       &_controlKey, &_x1, &_y1, &_x2, &_y2, &_startFrame, &_endFrame, &_loopCount);
@@ -751,8 +769,10 @@ ActionPlayPreloadAnimation::ActionPlayPreloadAnimation(ZVision *engine, int32 sl
 
 bool ActionPlayPreloadAnimation::execute() {
 	AnimationEffect *nod = (AnimationEffect *)_scriptManager->getSideFX(_controlKey);
+
 	if (nod)
 		nod->addPlayNode(_slotKey, _x1, _y1, _x2, _y2, _startFrame, _endFrame, _loopCount);
+
 	return true;
 }
 
@@ -762,6 +782,7 @@ bool ActionPlayPreloadAnimation::execute() {
 
 bool ActionQuit::execute() {
 	_engine->quitGame();
+
 	return true;
 }
 
@@ -775,9 +796,12 @@ ActionRegion::ActionRegion(ZVision *engine, int32 slotKey, const Common::String
 	_type = 0;
 	_unk1 = 0;
 	_unk2 = 0;
+
 	char art[64];
 	char custom[64];
+
 	int32 x1 = 0, x2 = 0, y1 = 0, y2 = 0;
+
 	sscanf(line.c_str(), "%s %d %d %d %d %hu %hu %hu %hu %s", art, &x1, &y1, &x2, &y2, &_delay, &_type, &_unk1, &_unk2, custom);
 	_art = Common::String(art);
 	_custom = Common::String(custom);
@@ -792,6 +816,7 @@ bool ActionRegion::execute() {
 	debug(2, "Executing Action: Region");
 	if (_scriptManager->getSideFX(_slotKey))
 		return true;
+
 	GraphicsEffect *effect = NULL;
 	switch (_type) {
 	case 0: {
@@ -824,6 +849,7 @@ bool ActionRegion::execute() {
 			_rect.setWidth(tempMask.w);
 		if (_rect.height() != tempMask.h)
 			_rect.setHeight(tempMask.h);
+
 		EffectMap *_map = _engine->getRenderManager()->makeEffectMap(tempMask, 0);
 		effect = new FogFx(_engine, _slotKey, _rect, _unk1, _map, buf);
 		tempMask.free();
@@ -832,10 +858,12 @@ bool ActionRegion::execute() {
 	default:
 		break;
 	}
+
 	if (effect) {
 		_scriptManager->addSideFX(new RegionNode(_engine, _slotKey, effect, _delay));
 		_engine->getRenderManager()->addEffect(effect);
 	}
+
 	return true;
 }
 
@@ -885,11 +913,13 @@ ActionRotateTo::ActionRotateTo(ZVision *engine, int32 slotKey, const Common::Str
 	ResultAction(engine, slotKey) {
 	_time = 0;
 	_toPos = 0;
+
 	sscanf(line.c_str(), "%d, %d", &_toPos, &_time);
 }
 
 bool ActionRotateTo::execute() {
 	_engine->getRenderManager()->rotateTo(_toPos, _time);
+
 	return true;
 }
 
@@ -901,9 +931,13 @@ ActionSetPartialScreen::ActionSetPartialScreen(ZVision *engine, int32 slotKey, c
 	ResultAction(engine, slotKey) {
 	_x = 0;
 	_y = 0;
+
 	char fileName[25];
+
 	sscanf(line.c_str(), "%u %u %24s %*u %d", &_x, &_y, fileName, &_backgroundColor);
+
 	_fileName = Common::String(fileName);
+
 	if (_backgroundColor > 65535) {
 		warning("Background color for ActionSetPartialScreen is bigger than a uint16");
 	}
@@ -911,6 +945,7 @@ ActionSetPartialScreen::ActionSetPartialScreen(ZVision *engine, int32 slotKey, c
 
 bool ActionSetPartialScreen::execute() {
 	RenderManager *renderManager = _engine->getRenderManager();
+
 	if (_engine->getGameId() == GID_NEMESIS) {
 		if (_backgroundColor)
 			renderManager->renderImageToBackground(_fileName, _x, _y, 0, 0);
@@ -924,6 +959,7 @@ bool ActionSetPartialScreen::execute() {
 		else
 			renderManager->renderImageToBackground(_fileName, _x, _y);
 	}
+
 	return true;
 }
 
@@ -935,11 +971,13 @@ ActionSetScreen::ActionSetScreen(ZVision *engine, int32 slotKey, const Common::S
 	ResultAction(engine, slotKey) {
 	char fileName[25];
 	sscanf(line.c_str(), "%24s", fileName);
+
 	_fileName = Common::String(fileName);
 }
 
 bool ActionSetScreen::execute() {
 	_engine->getRenderManager()->setBackgroundImage(_fileName);
+
 	return true;
 }
 
@@ -970,9 +1008,12 @@ ActionStreamVideo::ActionStreamVideo(ZVision *engine, int32 slotKey, const Commo
 	_y1 = 0;
 	_y2 = 0;
 	_flags = 0;
+
 	char fileName[25];
 	uint skipline = 0;    //skipline - render video with skip every second line, not skippable.
+
 	sscanf(line.c_str(), "%24s %u %u %u %u %u %u", fileName, &_x1, &_y1, &_x2, &_y2, &_flags, &skipline);
+
 	_fileName = Common::String(fileName);
 	_skippable = true;
 }
@@ -993,7 +1034,7 @@ bool ActionStreamVideo::execute() {
 
 // NOTE: We only show the hires MPEG2 videos when libmpeg2 and liba52 are compiled in,
 // otherwise we fall back to the lowres ones
-	#if defined(USE_MPEG2) && defined(USE_A52)
+#if defined(USE_MPEG2) && defined(USE_A52)
 	Common::String hiresFileName = _fileName.baseName();
 	hiresFileName.setChar('d', hiresFileName.size() - 8);
 	hiresFileName.setChar('v', hiresFileName.size() - 3);
@@ -1002,19 +1043,21 @@ bool ActionStreamVideo::execute() {
 
 	Common::Path hiresPath(_fileName.getParent().appendComponent(hiresFileName));
 
-	if (_scriptManager->getStateValue(StateKey_MPEGMovies) == 1 && _engine->getSearchManager()->hasFile(hiresPath)) {
+	if (_scriptManager->getStateValue(StateKey_MPEGMovies) == 1 &&_engine->getSearchManager()->hasFile(hiresPath)) {
 		_fileName = hiresPath;
 		switchToHires = true;
 	} else if (!_engine->getSearchManager()->hasFile(_fileName))
 		return true;
-	#else
+#else
 	if (!_engine->getSearchManager()->hasFile(_fileName))
 		return true;
-	#endif
+#endif
 
 	decoder = _engine->loadAnimation(_fileName);
 	uint16 sub = (subtitleExists) ? _engine->getSubtitleManager()->create(subpath, switchToHires) : 0;
+
 	_engine->getCursorManager()->showMouse(false);
+
 	if (switchToHires) {
 		_engine->getRenderManager()->initialize(true);
 		srcRect = Common::Rect(Common::Point(0, 69), 720, 344);
@@ -1034,17 +1077,26 @@ bool ActionStreamVideo::execute() {
 	// simply pause the ScummVM mixer during the ride.
 
 	bool pauseBackgroundMusic = _engine->getGameId() == GID_GRANDINQUISITOR && (_fileName == "hp3ea021.avi" || _fileName == "hp4ea051.avi");
-	if (pauseBackgroundMusic)
+
+	if (pauseBackgroundMusic) {
 		_engine->_mixer->pauseAll(true);
+	}
+
 	_engine->playVideo(*decoder, destRect, _skippable, sub, srcRect);
-	if (pauseBackgroundMusic)
+
+	if (pauseBackgroundMusic) {
 		_engine->_mixer->pauseAll(false);
-	if (switchToHires)
+	}
+
+	if (switchToHires) {
 		_engine->getRenderManager()->initialize(false);
+	}
+
 	_engine->getCursorManager()->showMouse(true);
 	_engine->getSubtitleManager()->destroy(sub);
 	_engine->setRenderDelay(2); //Necessary for avoiding redraw of previous scene between sequential videos (eg totemization sequence in ZGI) & when changing location right after a video (e.g. opening temple door in Nemesis)
 	debug(3, "Completed executing video stream");
+
 	return true;
 }
 
@@ -1055,9 +1107,12 @@ bool ActionStreamVideo::execute() {
 ActionSyncSound::ActionSyncSound(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
 	_syncto = 0;
+
 	char fileName[25];
 	int notUsed = 0;
+
 	sscanf(line.c_str(), "%d %d %24s", &_syncto, &notUsed, fileName);
+
 	_fileName = Common::String(fileName);
 }
 
@@ -1066,8 +1121,10 @@ bool ActionSyncSound::execute() {
 	ScriptingEffect *fx = _scriptManager->getSideFX(_syncto);
 	if (!fx)
 		return true;
+
 	if (!(fx->getType() & ScriptingEffect::SCRIPTING_EFFECT_ANIM))
 		return true;
+
 	_scriptManager->addSideFX(new SyncSoundNode(_engine, _slotKey, _fileName, _syncto));
 	return true;
 }
diff --git a/engines/zvision/scripting/control.cpp b/engines/zvision/scripting/control.cpp
index 9132091fc25..08c58e231d2 100644
--- a/engines/zvision/scripting/control.cpp
+++ b/engines/zvision/scripting/control.cpp
@@ -66,9 +66,11 @@ void Control::parsePanoramaControl(ZVision *engine, Common::SeekableReadStream &
 			sscanf(line.c_str(), "zeropoint(%u)", &point);
 			renderTable->setPanoramaZeroPoint(point);
 		}
+
 		line = stream.readLine();
 		engine->getScriptManager()->trimCommentsAndWhiteSpace(&line);
 	}
+
 	renderTable->generateRenderTable();
 }
 
@@ -98,26 +100,34 @@ void Control::parseTiltControl(ZVision *engine, Common::SeekableReadStream &stre
 				renderTable->setTiltReverse(true);
 			}
 		}
+
 		line = stream.readLine();
 		engine->getScriptManager()->trimCommentsAndWhiteSpace(&line);
 	}
+
 	renderTable->generateRenderTable();
 }
 
 void Control::getParams(const Common::String &inputStr, Common::String &parameter, Common::String &values) {
 	const char *chrs = inputStr.c_str();
 	uint lbr;
+
 	for (lbr = 0; lbr < inputStr.size(); lbr++)
 		if (chrs[lbr] == '(')
 			break;
+
 	if (lbr >= inputStr.size())
 		return;
+
 	uint rbr;
+
 	for (rbr = lbr + 1; rbr < inputStr.size(); rbr++)
 		if (chrs[rbr] == ')')
 			break;
+
 	if (rbr >= inputStr.size())
 		return;
+
 	parameter = Common::String(chrs, chrs + lbr);
 	values = Common::String(chrs + lbr + 1, chrs + rbr);
 }
diff --git a/engines/zvision/scripting/controls/fist_control.h b/engines/zvision/scripting/controls/fist_control.h
index ffbd4b986e4..7b7ab780f70 100644
--- a/engines/zvision/scripting/controls/fist_control.h
+++ b/engines/zvision/scripting/controls/fist_control.h
@@ -28,7 +28,7 @@
 #include "common/rect.h"
 
 namespace Video {
-class VideoDecoder;
+	class VideoDecoder;
 }
 
 namespace ZVision {
diff --git a/engines/zvision/scripting/controls/hotmov_control.h b/engines/zvision/scripting/controls/hotmov_control.h
index fcb1f3bb5b9..cdc6fe85c24 100644
--- a/engines/zvision/scripting/controls/hotmov_control.h
+++ b/engines/zvision/scripting/controls/hotmov_control.h
@@ -29,7 +29,7 @@
 #include "common/rect.h"
 
 namespace Video {
-class VideoDecoder;
+	class VideoDecoder;
 }
 
 namespace ZVision {
diff --git a/engines/zvision/scripting/controls/input_control.h b/engines/zvision/scripting/controls/input_control.h
index f2ac644363f..b99dd4c0c8b 100644
--- a/engines/zvision/scripting/controls/input_control.h
+++ b/engines/zvision/scripting/controls/input_control.h
@@ -29,7 +29,7 @@
 #include "common/rect.h"
 
 namespace Video {
-class VideoDecoder;
+	class VideoDecoder;
 }
 
 namespace ZVision {
diff --git a/engines/zvision/scripting/controls/lever_control.h b/engines/zvision/scripting/controls/lever_control.h
index e8ead352681..3abb2525866 100644
--- a/engines/zvision/scripting/controls/lever_control.h
+++ b/engines/zvision/scripting/controls/lever_control.h
@@ -29,7 +29,7 @@
 #include "common/rect.h"
 
 namespace Video {
-class VideoDecoder;
+	class VideoDecoder;
 }
 
 namespace ZVision {
diff --git a/engines/zvision/scripting/controls/safe_control.h b/engines/zvision/scripting/controls/safe_control.h
index d6b9059336e..5bf0e51f5c2 100644
--- a/engines/zvision/scripting/controls/safe_control.h
+++ b/engines/zvision/scripting/controls/safe_control.h
@@ -28,7 +28,7 @@
 #include "common/rect.h"
 
 namespace Video {
-class VideoDecoder;
+	class VideoDecoder;
 }
 
 namespace ZVision {
diff --git a/engines/zvision/scripting/effects/animation_effect.cpp b/engines/zvision/scripting/effects/animation_effect.cpp
index 4bda3ddf93e..928cd4eba72 100644
--- a/engines/zvision/scripting/effects/animation_effect.cpp
+++ b/engines/zvision/scripting/effects/animation_effect.cpp
@@ -64,7 +64,7 @@ AnimationEffect::~AnimationEffect() {
 
 		if ((*it)._scaled) {
 			(*it)._scaled->free();
-			delete (*it)._scaled;
+			delete(*it)._scaled;
 		}
 	}
 
@@ -203,7 +203,7 @@ bool AnimationEffect::stop() {
 		_engine->getScriptManager()->setStateValue((*it).slot, 2);
 		if ((*it)._scaled) {
 			(*it)._scaled->free();
-			delete (*it)._scaled;
+			delete(*it)._scaled;
 		}
 	}
 
diff --git a/engines/zvision/scripting/effects/animation_effect.h b/engines/zvision/scripting/effects/animation_effect.h
index d836035245c..0124ed82e68 100644
--- a/engines/zvision/scripting/effects/animation_effect.h
+++ b/engines/zvision/scripting/effects/animation_effect.h
@@ -32,7 +32,7 @@ struct Surface;
 }
 
 namespace Video {
-class VideoDecoder;
+	class VideoDecoder;
 }
 
 namespace ZVision {
diff --git a/engines/zvision/scripting/effects/distort_effect.cpp b/engines/zvision/scripting/effects/distort_effect.cpp
index 66cb47bb1e9..b89d8e5425b 100644
--- a/engines/zvision/scripting/effects/distort_effect.cpp
+++ b/engines/zvision/scripting/effects/distort_effect.cpp
@@ -34,21 +34,27 @@ namespace ZVision {
 
 DistortNode::DistortNode(ZVision *engine, uint32 key, int16 speed, float startAngle, float endAngle, float startLineScale, float endLineScale)
 	: ScriptingEffect(engine, key, SCRIPTING_EFFECT_DISTORT) {
+
 	_angle = _engine->getRenderManager()->getRenderTable()->getAngle();
 	_linScale = _engine->getRenderManager()->getRenderTable()->getLinscale();
+
 	_speed = speed;
 	_incr = true;
 	_startAngle = startAngle;
 	_endAngle = endAngle;
 	_startLineScale = startLineScale;
 	_endLineScale = endLineScale;
+
 	_curFrame = 1.0;
+
 	_diffAngle = endAngle - startAngle;
 	_diffLinScale = endLineScale - startLineScale;
+
 	_frmSpeed = (float)speed / 15.0;
 	_frames = (int)ceil((5.0 - _frmSpeed * 2.0) / _frmSpeed);
 	if (_frames <= 0)
 		_frames = 1;
+
 	if (_key != StateKey_NotSet)
 		_engine->getScriptManager()->setStateValue(_key, 1);
 }
@@ -59,10 +65,12 @@ DistortNode::~DistortNode() {
 
 bool DistortNode::process(uint32 deltaTimeInMillis) {
 	float updTime = deltaTimeInMillis / (1000.0 / 60.0);
+
 	if (_incr)
 		_curFrame += updTime;
 	else
 		_curFrame -= updTime;
+
 	if (_curFrame < 1.0) {
 		_curFrame = 1.0;
 		_incr = true;
@@ -70,8 +78,10 @@ bool DistortNode::process(uint32 deltaTimeInMillis) {
 		_curFrame = _frames;
 		_incr = false;
 	}
+
 	float diff = (1.0 / (5.0 - (_curFrame * _frmSpeed))) / (5.0 - _frmSpeed);
 	setParams(_startAngle + diff * _diffAngle, _startLineScale + diff * _diffLinScale);
+
 	return false;
 }
 
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 877b1e7b5cb..d850e9f73f6 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -30,14 +30,12 @@
 #include "zvision/sound/zork_raw.h"
 
 #include "zvision/sound/volume_manager.h"
-
 #include "common/stream.h"
 #include "common/file.h"
 #include "audio/decoders/wave.h"
 
 #include "math/utils.h"
 #include "math/angle.h"
-
 namespace ZVision {
 
 void MusicNodeBASE::setDirection(Math::Angle azimuth, uint8 magnitude) {
@@ -84,18 +82,23 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 
 	if (filename.baseName().contains(".wav")) {
 		Common::File *file = new Common::File();
-		if (_engine->getSearchManager()->openFile(*file, filename))
+		if (_engine->getSearchManager()->openFile(*file, filename)) {
 			audioStream = Audio::makeWAVStream(file, DisposeAfterUse::YES);
-	} else
+		}
+	} else {
 		audioStream = makeRawZorkStream(filename, _engine);
+	}
 
 	if (audioStream) {
 		_stereo = audioStream->isStereo();
+
 		if (_loop) {
 			Audio::LoopingAudioStream *loopingAudioStream = new Audio::LoopingAudioStream(audioStream, 0, DisposeAfterUse::YES);
 			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, loopingAudioStream, -1, _volume);
-		} else
+		} else {
 			_engine->_mixer->playStream(Audio::Mixer::kPlainSoundType, &_handle, audioStream, -1, _volume);
+		}
+
 		if (_key != StateKey_NotSet) {
 			debug(3, "setting musicnode state value to 1");
 			_engine->getScriptManager()->setStateValue(_key, 1);
@@ -110,6 +113,7 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 		Common::Path subpath(filename.getParent().appendComponent(subname));
 		if (_engine->getSearchManager()->hasFile(subpath))
 			_sub = _engine->getSubtitleManager()->create(subpath, _handle); //NB automatic subtitle!
+
 		_loaded = true;
 		updateMixer();
 	}
@@ -160,6 +164,7 @@ bool MusicNode::process(uint32 deltaTimeInMillis) {
 				setVolume(_newvol);
 		}
 		/*  //Redundant with switch to automatic subtitles
+
 		if (_sub && _engine->getScriptManager()->getStateValue(StateKey_Subtitles) == 1)
 		  _engine->getSubtitleManager()->update(_engine->_mixer->getSoundElapsedTime(_handle) / 100, _sub);
 		//*/
@@ -223,9 +228,7 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 				}
 				break;
 			case RenderTable::FLAT :
-			// fall through
 			case RenderTable::TILT :
-			// fall through
 			default :
 				debug(3, "PanTrackNode in FLAT/TILT mode");
 				_sourcePos.setDegrees(0);
@@ -251,19 +254,23 @@ MusicMidiNode::MusicMidiNode(ZVision *engine, uint32 key, uint8 program, uint8 n
 	_prog = program;
 	_noteNumber = note;
 	_pan = 0;
+
 	_chan = _engine->getMidiManager()->getFreeChannel();
+
 	if (_chan >= 0) {
 		updateMixer();
 		_engine->getMidiManager()->setProgram(_chan, _prog);
 		_engine->getMidiManager()->noteOn(_chan, _noteNumber, _volume);
 	}
+
 	if (_key != StateKey_NotSet)
 		_engine->getScriptManager()->setStateValue(_key, 1);
 }
 
 MusicMidiNode::~MusicMidiNode() {
-	if (_chan >= 0)
+	if (_chan >= 0) {
 		_engine->getMidiManager()->noteOff(_chan);
+	}
 	if (_key != StateKey_NotSet)
 		_engine->getScriptManager()->setStateValue(_key, 2);
 }
diff --git a/engines/zvision/scripting/effects/music_effect.h b/engines/zvision/scripting/effects/music_effect.h
index fa13bd60a78..5bb4fc067f5 100644
--- a/engines/zvision/scripting/effects/music_effect.h
+++ b/engines/zvision/scripting/effects/music_effect.h
@@ -79,7 +79,9 @@ public:
 	 * @return                     If true, the node can be deleted after process() finishes
 	 */
 	bool process(uint32 deltaTimeInMillis) override;
+
 	void setVolume(uint8 volume) override;
+
 	void setFade(int32 time, uint8 target) override;
 
 private:
@@ -110,7 +112,9 @@ public:
 	 * @return                     If true, the node can be deleted after process() finishes
 	 */
 	bool process(uint32 deltaTimeInMillis) override;
+
 	void setVolume(uint8 volume) override;
+
 	void setFade(int32 time, uint8 target) override;
 
 private:
@@ -125,6 +129,7 @@ class PanTrackNode : public ScriptingEffect {
 public:
 	PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos, uint8 mag = 255, bool resetMixerOnDelete = false, bool staticScreen = false);
 	~PanTrackNode() override;
+
 	bool process(uint32 deltaTimeInMillis) override;
 
 private:
diff --git a/engines/zvision/scripting/effects/syncsound_effect.cpp b/engines/zvision/scripting/effects/syncsound_effect.cpp
index 7207a8008d7..b9cecbf8e19 100644
--- a/engines/zvision/scripting/effects/syncsound_effect.cpp
+++ b/engines/zvision/scripting/effects/syncsound_effect.cpp
@@ -72,6 +72,7 @@ bool SyncSoundNode::process(uint32 deltaTimeInMillis) {
 	if (! _engine->_mixer->isSoundHandleActive(_handle))
 		return stop();
 	else {
+
 		if (_engine->getScriptManager()->getSideFX(_syncto) == NULL)
 			return stop();
 		/*  //Redundant with switch to automatic subtitles
diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index d0c5a2f2c89..574d0cbc077 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -22,9 +22,6 @@
 #include "zvision/graphics/render_manager.h"
 #include "zvision/scripting/menu.h"
 
-//FOR BUG TEST ONLY
-//#include "common/debug.h"
-
 namespace ZVision {
 
 enum {
@@ -254,13 +251,13 @@ MenuZGI::MenuZGI(ZVision *engine, const Common::Rect menuArea) :
 }
 
 MenuZGI::~MenuZGI() {
-	for (int i = 0; i < 3; i++)
+	for (int i = 0; i < 3; i++) {
 		_menuBack[i].free();
-
-	for (int i = 0; i < 4; i++)
+	}
+	for (int i = 0; i < 4; i++) {
 		for (int j = 0; j < 2; j++)
 			_mainButtons[i][j].free();
-
+	}
 	for (int i = 0; i < 50; i++) {
 		if (_items[i][0]) {
 			_items[i][0]->free();
@@ -308,10 +305,12 @@ void MenuZGI::onMouseUp(const Common::Point &Pos) {
 				}
 			}
 			break;
+
 		case kFocusMagic:
 			if (_enableFlags.get(kMagicMenu)) {
 				int i = mouseOverMagic(Pos);
 				if (i != -1) {
+
 					uint itemnum = _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + i);
 					if (itemnum != 0) {
 						if (_engine->getScriptManager()->getStateValue(StateKey_Reversed_Spellbooc) == 1)
@@ -323,11 +322,14 @@ void MenuZGI::onMouseUp(const Common::Point &Pos) {
 						if (_engine->getScriptManager()->getStateValue(StateKey_InventoryItem) == 0 || _engine->getScriptManager()->getStateValue(StateKey_InventoryItem) >= 0xE0)
 							_engine->getScriptManager()->setStateValue(StateKey_Active_Spell, itemnum);
 				}
+
 			}
 			break;
+
 		case kFocusMain:
 			MenuManager::onMouseUp(Pos);
 			break;
+
 		default:
 			break;
 		}
@@ -384,13 +386,16 @@ void MenuZGI::onMouseMove(const Common::Point &Pos) {
 						_redraw = true;
 			}
 			break;
+
 		case kFocusMagic:
 			if (_enableFlags.get(kMagicMenu)) {
 				int lastItem = _mouseOnItem;
 				_mouseOnItem = mouseOverMagic(Pos);
+
 				if (lastItem != _mouseOnItem)
 					if (_engine->getScriptManager()->getStateValue(StateKey_Spell_1 + _mouseOnItem) || _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + lastItem))
 						_redraw = true;
+
 			}
 			break;
 		case kFocusMain:
@@ -554,20 +559,20 @@ MenuNemesis::MenuNemesis(ZVision *engine, const Common::Rect menuArea) :
 	_engine->getRenderManager()->readImageToSurface("bar.tga", _mainBack, false);
 
 	char buf[24];
-	for (int i = 0; i < 4; i++) {
+	for (int i = 0; i < 4; i++)
 		//Buffer menu buttons
 		for (int j = 0; j < 6; j++) {
 			Common::sprintf_s(buf, "butfrm%d%d.tga", i + 1, j);
 			_engine->getRenderManager()->readImageToSurface(buf, _mainButtons[i][j], false);
 		}
-	}
+
 }
 
 MenuNemesis::~MenuNemesis() {
-	for (int i = 0; i < 4; i++) {
+	for (int i = 0; i < 4; i++)
 		for (int j = 0; j < 6; j++)
 			_mainButtons[i][j].free();
-	};
+
 }
 
 bool MenuNemesis::inMenu(const Common::Point &Pos) {
diff --git a/engines/zvision/scripting/scr_file_handling.cpp b/engines/zvision/scripting/scr_file_handling.cpp
index 93e8026cf1f..dd5b6a56040 100644
--- a/engines/zvision/scripting/scr_file_handling.cpp
+++ b/engines/zvision/scripting/scr_file_handling.cpp
@@ -97,10 +97,11 @@ void ScriptManager::parseScrFile(const Common::Path &fileName, ScriptScope &scop
 void ScriptManager::parsePuzzle(Puzzle *puzzle, Common::SeekableReadStream &stream) {
 	Common::String line = stream.readLine();
 	trimCommentsAndWhiteSpace(&line);
+
 	while (!stream.eos() && !line.contains('}')) {
-		if (line.matchString("criteria {", true))
+		if (line.matchString("criteria {", true)) {
 			parseCriteria(stream, puzzle->criteriaList, puzzle->key);
-		else if (line.matchString("results {", true)) {
+		} else if (line.matchString("results {", true)) {
 			parseResults(stream, puzzle->resultActions, puzzle->key);
 			//WORKAROUNDS:
 			switch (_engine->getGameId()) {
@@ -138,9 +139,7 @@ void ScriptManager::parsePuzzle(Puzzle *puzzle, Common::SeekableReadStream &stre
 				// WORKAROUND for a script bug in Zork: Grand Inquisitor, room dc10.
 				// Background heartbeat sound effect never terminates upon location change.
 				case 2341:
-				// fall through
 				case 2344:
-				// fall through
 				case 17545:
 					puzzle->resultActions.push_front(new ActionKill(_engine, 11, "02310"));
 					break;
@@ -152,11 +151,14 @@ void ScriptManager::parsePuzzle(Puzzle *puzzle, Common::SeekableReadStream &stre
 			default:
 				break;
 			}
-		} else if (line.matchString("flags {", true))
+		} else if (line.matchString("flags {", true)) {
 			setStateFlag(puzzle->key, parseFlags(stream));
+		}
+
 		line = stream.readLine();
 		trimCommentsAndWhiteSpace(&line);
 	}
+
 	puzzle->addedBySetState = false;
 }
 
@@ -171,9 +173,12 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 		line = stream.readLine();
 		trimCommentsAndWhiteSpace(&line);
 	}
+
 	// Criteria can be empty
-	if (line.contains('}'))
+	if (line.contains('}')) {
 		return false;
+	}
+
 	// Create a new List to hold the CriteriaEntries
 	criteriaList.push_back(Common::List<Puzzle::CriteriaEntry>());
 
@@ -191,6 +196,7 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 			entry.criteriaOperator = Puzzle::NOT_EQUAL_TO;
 			entry.argumentIsAKey = false;
 			entry.argument = 1;
+
 			criteriaList.back().push_back(entry);
 		}
 		break;
@@ -207,6 +213,7 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 			entry.criteriaOperator = Puzzle::EQUAL_TO;
 			entry.argumentIsAKey = false;
 			entry.argument = 0;
+
 			criteriaList.back().push_back(entry);
 		}
 		break;
@@ -246,10 +253,11 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 		// There are supposed to be three tokens, but there is no
 		// guarantee that there will be a space between the second and
 		// the third one (bug #6774)
-		if (token.size() == 1)
+		if (token.size() == 1) {
 			token = tokenizer.nextToken();
-		else
+		} else {
 			token.deleteChar(0);
+		}
 
 		// First determine if the last token is an id or a value
 		// Then parse it into 'argument'
@@ -276,15 +284,19 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 			entry0.criteriaOperator = Puzzle::GREATER_THAN;
 			entry0.argumentIsAKey = false;
 			entry0.argument = 0;
+
 			criteriaList.back().push_back(entry0);
+
 			entry.criteriaOperator = Puzzle::NOT_EQUAL_TO;
 			entry.argument = 2;
 		}
 
 		criteriaList.back().push_back(entry);
+
 		line = stream.readLine();
 		trimCommentsAndWhiteSpace(&line);
 	}
+
 	return true;
 }
 
@@ -329,13 +341,16 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 			for (pos = startpos; pos < line.size(); pos++)
 				if (chrs[pos] == ':' || chrs[pos] == '(')
 					break;
+
 			debug(4, "startpos %d, pos %d, line.size %d", startpos, pos, line.size());
 			int32 slot = 11;  //Non-setting default slot
 			Common::String args = "";
 			Common::String act(chrs + startpos, chrs + pos);
 			//Extract arguments, if any
 			if (pos < line.size()) {
+
 				startpos = pos + 1;
+
 				if (chrs[pos] == ':') {
 					for (pos = startpos; pos < line.size(); pos++)
 						if (chrs[pos] == '(')
@@ -343,30 +358,33 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 					//Extract slotkey, if specified
 					Common::String strSlot(chrs + startpos, chrs + pos);
 					slot = atoi(strSlot.c_str());
+
 					startpos = pos + 1;
 				}
+
 				if (pos < line.size()) {
 					for (pos = startpos; pos < line.size(); pos++)
 						if (chrs[pos] == ')')
 							break;
+
 					args = Common::String(chrs + startpos, chrs + pos);
 				}
 			}
 			debug(4, "Action string: '%s', slot %d, arguments string '%s'", act.c_str(), slot, args.c_str());
 
-			// Parse for the action type
-			if (act.matchString("add", true)) {
-				actionList.push_back(new ActionAdd(_engine, slot, args));
-			} else if (act.matchString("animplay", true)) {
-				actionList.push_back(new ActionPlayAnimation(_engine, slot, args));
-			} else if (act.matchString("animpreload", true)) {
-				actionList.push_back(new ActionPreloadAnimation(_engine, slot, args));
-			} else if (act.matchString("animunload", true)) {
-				// Only used by ZGI (locations cd6e, cd6k, dg2f, dg4e, dv1j)
-				actionList.push_back(new ActionUnloadAnimation(_engine, slot, args));
-			} else if (act.matchString("attenuate", true)) {
-				actionList.push_back(new ActionAttenuate(_engine, slot, args));
-			} else if (act.matchString("assign", true)) {
+				// Parse for the action type
+				if (act.matchString("add", true)) {
+					actionList.push_back(new ActionAdd(_engine, slot, args));
+				} else if (act.matchString("animplay", true)) {
+					actionList.push_back(new ActionPlayAnimation(_engine, slot, args));
+				} else if (act.matchString("animpreload", true)) {
+					actionList.push_back(new ActionPreloadAnimation(_engine, slot, args));
+				} else if (act.matchString("animunload", true)) {
+					// Only used by ZGI (locations cd6e, cd6k, dg2f, dg4e, dv1j)
+					actionList.push_back(new ActionUnloadAnimation(_engine, slot, args));
+				} else if (act.matchString("attenuate", true)) {
+					actionList.push_back(new ActionAttenuate(_engine, slot, args));
+				} else if (act.matchString("assign", true)) {
 				if (_engine->getGameId() == GID_GRANDINQUISITOR && key == 17761) {
 					// WORKAROUND for a script bug in Zork: Grand Inquisitor, room tp1e.
 					// Background looping sound effect continuously restarts on every game cycle.
@@ -374,116 +392,114 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 					// Simple fix is to simply not generate this result assignment action at all.
 				} else
 					actionList.push_back(new ActionAssign(_engine, slot, args));
-			} else if (act.matchString("change_location", true)) {
-				actionList.push_back(new ActionChangeLocation(_engine, slot, args));
-			} else if (act.matchString("crossfade", true)) {
-				actionList.push_back(new ActionCrossfade(_engine, slot, args));
-//					debug(1,"\tpush.ActionCrossFade, script line: %s", line.c_str());
-			} else if (act.matchString("cursor", true)) {
-				actionList.push_back(new ActionCursor(_engine, slot, args));
-			} else if (act.matchString("debug", true)) {
-				// Not used. Purposely left empty
-			} else if (act.matchString("delay_render", true)) {
-				actionList.push_back(new ActionDelayRender(_engine, slot, args));
-			} else if (act.matchString("disable_control", true)) {
-				actionList.push_back(new ActionDisableControl(_engine, slot, args));
-			} else if (act.matchString("disable_venus", true)) {
-				// Not used. Purposely left empty
-			} else if (act.matchString("display_message", true)) {
-				actionList.push_back(new ActionDisplayMessage(_engine, slot, args));
-			} else if (act.matchString("dissolve", true)) {
-				actionList.push_back(new ActionDissolve(_engine));
-			} else if (act.matchString("distort", true)) {
-				// Only used by Zork: Nemesis for the "treatment" puzzle in the Sanitarium (aj30)
-				actionList.push_back(new ActionDistort(_engine, slot, args));
-			} else if (act.matchString("enable_control", true)) {
-				actionList.push_back(new ActionEnableControl(_engine, slot, args));
-			} else if (act.matchString("flush_mouse_events", true)) {
-				actionList.push_back(new ActionFlushMouseEvents(_engine, slot));
-			} else if (act.matchString("inventory", true)) {
-				actionList.push_back(new ActionInventory(_engine, slot, args));
-			} else if (act.matchString("kill", true)) {
-				// Only used by ZGI
-				actionList.push_back(new ActionKill(_engine, slot, args));
-			} else if (act.matchString("menu_bar_enable", true)) {
-				actionList.push_back(new ActionMenuBarEnable(_engine, slot, args));
-			} else if (act.matchString("music", true)) {
-				actionList.push_back(new ActionMusic(_engine, slot, args, false));
-//					debug(1,"\tpush.ActionMusic, script line: %s", line.c_str());
-			} else if (act.matchString("pan_track", true)) {
-				actionList.push_back(new ActionPanTrack(_engine, slot, args));
-//					debug(1,"\tpush.ActionPanTrack, script line: %s", line.c_str());
-			} else if (act.matchString("playpreload", true)) {
-				actionList.push_back(new ActionPlayPreloadAnimation(_engine, slot, args));
-			} else if (act.matchString("preferences", true)) {
-				actionList.push_back(new ActionPreferences(_engine, slot, args));
-			} else if (act.matchString("quit", true)) {
-				actionList.push_back(new ActionQuit(_engine, slot));
-			} else if (act.matchString("random", true)) {
-				actionList.push_back(new ActionRandom(_engine, slot, args));
-			} else if (act.matchString("region", true)) {
-				// Only used by Zork: Nemesis
-				actionList.push_back(new ActionRegion(_engine, slot, args));
-			} else if (act.matchString("restore_game", true)) {
-				// Only used by ZGI to load the restart game slot, r.svr.
-				// Used by the credits screen.
-				actionList.push_back(new ActionRestoreGame(_engine, slot, args));
-			} else if (act.matchString("rotate_to", true)) {
-				actionList.push_back(new ActionRotateTo(_engine, slot, args));
-			} else if (act.matchString("save_game", true)) {
-				// Not used. Purposely left empty
-			} else if (act.matchString("set_partial_screen", true)) {
-				actionList.push_back(new ActionSetPartialScreen(_engine, slot, args));
-			} else if (act.matchString("set_screen", true)) {
-				actionList.push_back(new ActionSetScreen(_engine, slot, args));
-			} else if (act.matchString("set_venus", true)) {
-				// Not used. Purposely left empty
-			} else if (act.matchString("stop", true)) {
-				actionList.push_back(new ActionStop(_engine, slot, args));
-			} else if (act.matchString("streamvideo", true)) {
-				actionList.push_back(new ActionStreamVideo(_engine, slot, args));
-			} else if (act.matchString("syncsound", true)) {
-				actionList.push_back(new ActionSyncSound(_engine, slot, args));
-			} else if (act.matchString("timer", true)) {
-				actionList.push_back(new ActionTimer(_engine, slot, args));
-			} else if (act.matchString("ttytext", true)) {
-				actionList.push_back(new ActionTtyText(_engine, slot, args));
-			} else if (act.matchString("universe_music", true)) {
-				if (_engine->getGameId() == GID_GRANDINQUISITOR && slot == 2310 && false) { //DISABLED - not effective, sound stops on all zoom-ins for some reason?
-					// WORKAROUND for a script bug in Zork: Grand Inquisitor, room dc10.
-					// Background looping sound effect never terminates upon location change.
-					// Seems that it should have been "music" instead of "universe_music."
+				} else if (act.matchString("change_location", true)) {
+					actionList.push_back(new ActionChangeLocation(_engine, slot, args));
+				} else if (act.matchString("crossfade", true)) {
+					actionList.push_back(new ActionCrossfade(_engine, slot, args));
+				} else if (act.matchString("cursor", true)) {
+					actionList.push_back(new ActionCursor(_engine, slot, args));
+				} else if (act.matchString("debug", true)) {
+					// Not used. Purposely left empty
+				} else if (act.matchString("delay_render", true)) {
+					actionList.push_back(new ActionDelayRender(_engine, slot, args));
+				} else if (act.matchString("disable_control", true)) {
+					actionList.push_back(new ActionDisableControl(_engine, slot, args));
+				} else if (act.matchString("disable_venus", true)) {
+					// Not used. Purposely left empty
+				} else if (act.matchString("display_message", true)) {
+					actionList.push_back(new ActionDisplayMessage(_engine, slot, args));
+				} else if (act.matchString("dissolve", true)) {
+					actionList.push_back(new ActionDissolve(_engine));
+				} else if (act.matchString("distort", true)) {
+					// Only used by Zork: Nemesis for the "treatment" puzzle in the Sanitarium (aj30)
+					actionList.push_back(new ActionDistort(_engine, slot, args));
+				} else if (act.matchString("enable_control", true)) {
+					actionList.push_back(new ActionEnableControl(_engine, slot, args));
+				} else if (act.matchString("flush_mouse_events", true)) {
+					actionList.push_back(new ActionFlushMouseEvents(_engine, slot));
+				} else if (act.matchString("inventory", true)) {
+					actionList.push_back(new ActionInventory(_engine, slot, args));
+				} else if (act.matchString("kill", true)) {
+					// Only used by ZGI
+					actionList.push_back(new ActionKill(_engine, slot, args));
+				} else if (act.matchString("menu_bar_enable", true)) {
+					actionList.push_back(new ActionMenuBarEnable(_engine, slot, args));
+				} else if (act.matchString("music", true)) {
 					actionList.push_back(new ActionMusic(_engine, slot, args, false));
-				} else
+				} else if (act.matchString("pan_track", true)) {
+					actionList.push_back(new ActionPanTrack(_engine, slot, args));
+				} else if (act.matchString("playpreload", true)) {
+					actionList.push_back(new ActionPlayPreloadAnimation(_engine, slot, args));
+				} else if (act.matchString("preferences", true)) {
+					actionList.push_back(new ActionPreferences(_engine, slot, args));
+				} else if (act.matchString("quit", true)) {
+					actionList.push_back(new ActionQuit(_engine, slot));
+				} else if (act.matchString("random", true)) {
+					actionList.push_back(new ActionRandom(_engine, slot, args));
+				} else if (act.matchString("region", true)) {
+					// Only used by Zork: Nemesis
+					actionList.push_back(new ActionRegion(_engine, slot, args));
+				} else if (act.matchString("restore_game", true)) {
+					// Only used by ZGI to load the restart game slot, r.svr.
+					// Used by the credits screen.
+					actionList.push_back(new ActionRestoreGame(_engine, slot, args));
+				} else if (act.matchString("rotate_to", true)) {
+					actionList.push_back(new ActionRotateTo(_engine, slot, args));
+				} else if (act.matchString("save_game", true)) {
+					// Not used. Purposely left empty
+				} else if (act.matchString("set_partial_screen", true)) {
+					actionList.push_back(new ActionSetPartialScreen(_engine, slot, args));
+				} else if (act.matchString("set_screen", true)) {
+					actionList.push_back(new ActionSetScreen(_engine, slot, args));
+				} else if (act.matchString("set_venus", true)) {
+					// Not used. Purposely left empty
+				} else if (act.matchString("stop", true)) {
+					actionList.push_back(new ActionStop(_engine, slot, args));
+				} else if (act.matchString("streamvideo", true)) {
+					actionList.push_back(new ActionStreamVideo(_engine, slot, args));
+				} else if (act.matchString("syncsound", true)) {
+					actionList.push_back(new ActionSyncSound(_engine, slot, args));
+				} else if (act.matchString("timer", true)) {
+					actionList.push_back(new ActionTimer(_engine, slot, args));
+				} else if (act.matchString("ttytext", true)) {
+					actionList.push_back(new ActionTtyText(_engine, slot, args));
+				} else if (act.matchString("universe_music", true)) {
 					actionList.push_back(new ActionMusic(_engine, slot, args, true));
-			} else if (act.matchString("copy_file", true)) {
-				// Not used. Purposely left empty
-			} else {
-				warning("Unhandled result action type: %s", line.c_str());
+				} else if (act.matchString("copy_file", true)) {
+					// Not used. Purposely left empty
+				} else {
+					warning("Unhandled result action type: %s", line.c_str());
 			}
 		}
+
 		line = stream.readLine();
 		trimCommentsAndWhiteSpace(&line);
 		line.toLowercase();
 	}
+
 	return;
 }
 
 uint ScriptManager::parseFlags(Common::SeekableReadStream &stream) const {
 	uint flags = 0;
+
 	// Loop until we find the closing brace
 	Common::String line = stream.readLine();
 	trimCommentsAndWhiteSpace(&line);
+
 	while (!stream.eos() && !line.contains('}')) {
-		if (line.matchString("ONCE_PER_INST", true))
+		if (line.matchString("ONCE_PER_INST", true)) {
 			flags |= Puzzle::ONCE_PER_INST;
-		else if (line.matchString("DO_ME_NOW", true))
+		} else if (line.matchString("DO_ME_NOW", true)) {
 			flags |= Puzzle::DO_ME_NOW;
-		else if (line.matchString("DISABLED", true))
+		} else if (line.matchString("DISABLED", true)) {
 			flags |= Puzzle::DISABLED;
+		}
+
 		line = stream.readLine();
 		trimCommentsAndWhiteSpace(&line);
 	}
+
 	return flags;
 }
 
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index c40d67efb53..fb21868c90d 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -66,6 +66,7 @@ void ScriptManager::initialize(bool restarted) {
 	_currentLocation.world = 0;
 	_currentLocation.room = 0;
 	_currentLocation.view = 0;
+
 	_changeLocationDelayCycles = 0;
 	if (restarted) {
 		for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); iter++)
@@ -83,13 +84,13 @@ void ScriptManager::initialize(bool restarted) {
 			setStateValue(19848, 1);
 			break;
 		case GID_NEMESIS:
-		// fall through
 		default:
 			break;
 		}
 	}
 	parseScrFile("universe.scr", _universe);
 	changeLocation('g', 'a', 'r', 'y', 0);
+
 	_controlEvents.clear();
 	if (restarted)
 		_engine->loadSettings();
@@ -106,19 +107,25 @@ void ScriptManager::update(uint deltaTimeMillis) {
 		// in the exec queues, but that could cause this to hang
 		// indefinitely.
 		// TODO - this causes noticeable pauses on location change; see if these can be reduced by improving this functionality.
-		if (_changeLocationDelayCycles-- <= 0)
+		if (_changeLocationDelayCycles-- <= 0) {
 			ChangeLocationReal(false);
+		}
 	}
+
 	updateNodes(deltaTimeMillis);
 	debug(5, "Script nodes updated");
-	if (!execScope(_nodeview))
+	if (!execScope(_nodeview)) {
 		return;
-	if (!execScope(_room))
+	}
+	if (!execScope(_room)) {
 		return;
-	if (!execScope(_world))
+	}
+	if (!execScope(_world)) {
 		return;
-	if (!execScope(_universe))
+	}
+	if (!execScope(_universe)) {
 		return;
+	}
 	updateControls(deltaTimeMillis);
 }
 
@@ -129,22 +136,27 @@ bool ScriptManager::execScope(ScriptScope &scope) {
 	scope.scopeQueue = tmp;
 	scope.scopeQueue->clear();
 
-	for (PuzzleList::iterator PuzzleIter = scope.puzzles.begin(); PuzzleIter != scope.puzzles.end(); ++PuzzleIter)
+	for (PuzzleList::iterator PuzzleIter = scope.puzzles.begin(); PuzzleIter != scope.puzzles.end(); ++PuzzleIter) {
 		(*PuzzleIter)->addedBySetState = false;
+	}
 
 	if (scope.procCount < 2 || getStateValue(StateKey_ExecScopeStyle)) {
 		for (PuzzleList::iterator PuzzleIter = scope.puzzles.begin(); PuzzleIter != scope.puzzles.end(); ++PuzzleIter) {
-			if (!checkPuzzleCriteria(*PuzzleIter, scope.procCount))
+			if (!checkPuzzleCriteria(*PuzzleIter, scope.procCount)) {
 				return false;
+			}
 		}
 	} else {
 		for (PuzzleList::iterator PuzzleIter = scope.execQueue->begin(); PuzzleIter != scope.execQueue->end(); ++PuzzleIter) {
-			if (!checkPuzzleCriteria(*PuzzleIter, scope.procCount))
+			if (!checkPuzzleCriteria(*PuzzleIter, scope.procCount)) {
 				return false;
+			}
 		}
 	}
-	if (scope.procCount < 2)
+
+	if (scope.procCount < 2) {
 		scope.procCount++;
+	}
 	return true;
 }
 
@@ -152,10 +164,12 @@ void ScriptManager::referenceTableAddPuzzle(uint32 key, PuzzleRef ref) {
 	if (_referenceTable.contains(key)) {
 		Common::Array<PuzzleRef> *arr = &_referenceTable[key];
 		for (uint32 i = 0; i < arr->size(); i++) {
-			if ((*arr)[i].puz == ref.puz)
+			if ((*arr)[i].puz == ref.puz) {
 				return;
+			}
 		}
 	}
+
 	_referenceTable[key].push_back(ref);
 }
 
@@ -163,14 +177,18 @@ void ScriptManager::addPuzzlesToReferenceTable(ScriptScope &scope) {
 	// Iterate through each local Puzzle
 	for (PuzzleList::iterator PuzzleIter = scope.puzzles.begin(); PuzzleIter != scope.puzzles.end(); ++PuzzleIter) {
 		Puzzle *puzzlePtr = (*PuzzleIter);
+
 		PuzzleRef ref;
 		ref.scope = &scope;
 		ref.puz = puzzlePtr;
+
 		referenceTableAddPuzzle(puzzlePtr->key, ref);
+
 		// Iterate through each CriteriaEntry and add a reference from the criteria key to the Puzzle
 		for (Common::List<Common::List<Puzzle::CriteriaEntry> >::iterator criteriaIter = (*PuzzleIter)->criteriaList.begin(); criteriaIter != (*PuzzleIter)->criteriaList.end(); ++criteriaIter) {
-			for (Common::List<Puzzle::CriteriaEntry>::iterator entryIter = criteriaIter->begin(); entryIter != criteriaIter->end(); ++entryIter)
+			for (Common::List<Puzzle::CriteriaEntry>::iterator entryIter = criteriaIter->begin(); entryIter != criteriaIter->end(); ++entryIter) {
 				referenceTableAddPuzzle(entryIter->key, ref);
+			}
 		}
 	}
 }
@@ -179,16 +197,20 @@ void ScriptManager::updateNodes(uint deltaTimeMillis) {
 	// If process() returns true, it means the node can be deleted
 	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end();) {
 		if ((*iter)->process(deltaTimeMillis)) {
-			delete (*iter); // Remove the node
+			delete(*iter);
+			// Remove the node
 			iter = _activeSideFx.erase(iter);
-		} else
+		} else {
 			++iter;
+		}
 	}
 }
 
 void ScriptManager::updateControls(uint deltaTimeMillis) {
-	if (!_activeControls)
+	if (!_activeControls) {
 		return;
+	}
+
 	// Process only one event
 	if (!_controlEvents.empty()) {
 		Common::Event _event = _controlEvents.front();
@@ -213,9 +235,11 @@ void ScriptManager::updateControls(uint deltaTimeMillis) {
 		}
 		_controlEvents.pop_front();
 	}
+
 	for (ControlList::iterator iter = _activeControls->begin(); iter != _activeControls->end(); iter++) {
-		if ((*iter)->process(deltaTimeMillis))
+		if ((*iter)->process(deltaTimeMillis)) {
 			break;
+		}
 	}
 }
 
@@ -234,13 +258,16 @@ bool ScriptManager::checkPuzzleCriteria(Puzzle *puzzle, uint counter) {
 	bool criteriaMet = false;
 	for (Common::List<Common::List<Puzzle::CriteriaEntry> >::iterator criteriaIter = puzzle->criteriaList.begin(); criteriaIter != puzzle->criteriaList.end(); ++criteriaIter) {
 		criteriaMet = false;
+
 		for (Common::List<Puzzle::CriteriaEntry>::iterator entryIter = criteriaIter->begin(); entryIter != criteriaIter->end(); ++entryIter) {
 			// Get the value to compare against
 			int argumentValue;
-			if (entryIter->argumentIsAKey)
+			if (entryIter->argumentIsAKey) {
 				argumentValue = getStateValue(entryIter->argument);
-			else
+			} else {
 				argumentValue = entryIter->argument;
+			}
+
 			// Do the comparison
 			switch (entryIter->criteriaOperator) {
 			case Puzzle::EQUAL_TO:
@@ -258,24 +285,33 @@ bool ScriptManager::checkPuzzleCriteria(Puzzle *puzzle, uint counter) {
 			default:
 				break;
 			}
+
 			// If one check returns false, don't keep checking
-			if (!criteriaMet)
+			if (!criteriaMet) {
 				break;
+			}
 		}
+
 		// If any of the Criteria are *fully* met, then execute the results
-		if (criteriaMet)
+		if (criteriaMet) {
 			break;
+		}
 	}
+
 	// criteriaList can be empty. Aka, the puzzle should be executed immediately
 	if (puzzle->criteriaList.empty() || criteriaMet) {
-		debug(5, "Puzzle %u criteria passed. Executing its ResultActions", puzzle->key);
+		debug(1, "Puzzle %u criteria passed. Executing its ResultActions", puzzle->key);
+
 		// Set the puzzle as completed
 		setStateValue(puzzle->key, 1);
+
 		for (Common::List<ResultAction *>::iterator resultIter = puzzle->resultActions.begin(); resultIter != puzzle->resultActions.end(); ++resultIter) {
-			if (!(*resultIter)->execute())
+			if (!(*resultIter)->execute()) {
 				return false;
+			}
 		}
 	}
+
 	return true;
 }
 
@@ -283,8 +319,10 @@ void ScriptManager::cleanStateTable() {
 	for (StateMap::iterator iter = _globalState.begin(); iter != _globalState.end(); ++iter) {
 		// If the value is equal to zero, we can purge it since getStateValue()
 		// will return zero if _globalState doesn't contain a key
-		if (iter->_value == 0)
-			_globalState.erase(iter); // Remove the node
+		if (iter->_value == 0) {
+			// Remove the node
+			_globalState.erase(iter);
+		}
 	}
 }
 
@@ -293,20 +331,27 @@ void ScriptManager::cleanScriptScope(ScriptScope &scope) {
 	scope.privQueueTwo.clear();
 	scope.scopeQueue = &scope.privQueueOne;
 	scope.execQueue = &scope.privQueueTwo;
-	for (PuzzleList::iterator iter = scope.puzzles.begin(); iter != scope.puzzles.end(); ++iter)
-		delete (*iter);
+	for (PuzzleList::iterator iter = scope.puzzles.begin(); iter != scope.puzzles.end(); ++iter) {
+		delete(*iter);
+	}
+
 	scope.puzzles.clear();
-	for (ControlList::iterator iter = scope.controls.begin(); iter != scope.controls.end(); ++iter)
-		delete (*iter);
+
+	for (ControlList::iterator iter = scope.controls.begin(); iter != scope.controls.end(); ++iter) {
+		delete(*iter);
+	}
+
 	scope.controls.clear();
+
 	scope.procCount = 0;
 }
 
 int ScriptManager::getStateValue(uint32 key) {
-	if (_globalState.contains(key))
+	if (_globalState.contains(key)) {
 		return _globalState[key];
-	else
+	} else {
 		return 0;
+	}
 }
 
 void ScriptManager::queuePuzzles(uint32 key) {
@@ -322,68 +367,84 @@ void ScriptManager::queuePuzzles(uint32 key) {
 }
 
 void ScriptManager::setStateValue(uint32 key, int value) {
-	if (value == 0)
+	if (value == 0) {
 		_globalState.erase(key);
-	else
+	} else {
 		_globalState[key] = value;
+	}
+
 	queuePuzzles(key);
 }
 
 void ScriptManager::setStateValueSilent(uint32 key, int value) {
-	if (value == 0)
+	if (value == 0) {
 		_globalState.erase(key);
-	else
+	} else {
 		_globalState[key] = value;
+	}
 }
 
 uint ScriptManager::getStateFlag(uint32 key) {
-	if (_globalStateFlags.contains(key))
+	if (_globalStateFlags.contains(key)) {
 		return _globalStateFlags[key];
-	else
+	} else {
 		return 0;
+	}
 }
 
 void ScriptManager::setStateFlag(uint32 key, uint value) {
 	queuePuzzles(key);
+
 	_globalStateFlags[key] |= value;
 }
 
 void ScriptManager::setStateFlagSilent(uint32 key, uint value) {
-	if (value == 0)
+	if (value == 0) {
 		_globalStateFlags.erase(key);
-	else
+	} else {
 		_globalStateFlags[key] = value;
+	}
 }
 
 void ScriptManager::unsetStateFlag(uint32 key, uint value) {
 	queuePuzzles(key);
+
 	if (_globalStateFlags.contains(key)) {
 		_globalStateFlags[key] &= ~value;
-		if (_globalStateFlags[key] == 0)
+
+		if (_globalStateFlags[key] == 0) {
 			_globalStateFlags.erase(key);
+		}
 	}
 }
 
 Control *ScriptManager::getControl(uint32 key) {
 	for (ControlList::iterator iter = _activeControls->begin(); iter != _activeControls->end(); ++iter) {
-		if ((*iter)->getKey() == key)
+		if ((*iter)->getKey() == key) {
 			return *iter;
+		}
 	}
+
 	return nullptr;
 }
 
 void ScriptManager::focusControl(uint32 key) {
-	if (!_activeControls)
+	if (!_activeControls) {
 		return;
-	if (_currentlyFocusedControl == key)
+	}
+	if (_currentlyFocusedControl == key) {
 		return;
+	}
 	for (ControlList::iterator iter = _activeControls->begin(); iter != _activeControls->end(); ++iter) {
 		uint32 controlKey = (*iter)->getKey();
-		if (controlKey == key)
+
+		if (controlKey == key) {
 			(*iter)->focus();
-		else if (controlKey == _currentlyFocusedControl)
+		} else if (controlKey == _currentlyFocusedControl) {
 			(*iter)->unfocus();
+		}
 	}
+
 	_currentlyFocusedControl = key;
 }
 
@@ -397,16 +458,18 @@ void ScriptManager::addSideFX(ScriptingEffect *fx) {
 
 ScriptingEffect *ScriptManager::getSideFX(uint32 key) {
 	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); ++iter) {
-		if ((*iter)->getKey() == key)
+		if ((*iter)->getKey() == key) {
 			return (*iter);
+		}
 	}
+
 	return nullptr;
 }
 
 void ScriptManager::deleteSideFx(uint32 key) {
 	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); ++iter) {
 		if ((*iter)->getKey() == key) {
-			delete (*iter);
+			delete(*iter);
 			_activeSideFx.erase(iter);
 			break;
 		}
@@ -418,7 +481,7 @@ void ScriptManager::stopSideFx(uint32 key) {
 		if ((*iter)->getKey() == key) {
 			bool ret = (*iter)->stop();
 			if (ret) {
-				delete (*iter);
+				delete(*iter);
 				_activeSideFx.erase(iter);
 			}
 			break;
@@ -430,7 +493,7 @@ void ScriptManager::killSideFx(uint32 key) {
 	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); ++iter) {
 		if ((*iter)->getKey() == key) {
 			(*iter)->kill();
-			delete (*iter);
+			delete(*iter);
 			_activeSideFx.erase(iter);
 			break;
 		}
@@ -441,67 +504,80 @@ void ScriptManager::killSideFxType(ScriptingEffect::ScriptingEffectType type) {
 	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end();) {
 		if ((*iter)->getType() & type) {
 			(*iter)->kill();
-			delete (*iter);
+			delete(*iter);
 			iter = _activeSideFx.erase(iter);
-		} else
+		} else {
 			++iter;
+		}
 	}
 }
 
 void ScriptManager::onMouseDown(const Common::Point &screenSpacePos, const Common::Point &backgroundImageSpacePos) {
 	debug(1, "Mouse panorama/script coordinates %d x %d", backgroundImageSpacePos.x, backgroundImageSpacePos.y);
-	if (!_activeControls)
+	if (!_activeControls) {
 		return;
+	}
 	for (ControlList::iterator iter = _activeControls->reverse_begin(); iter != _activeControls->end(); iter--) {
-		if ((*iter)->onMouseDown(screenSpacePos, backgroundImageSpacePos))
+		if ((*iter)->onMouseDown(screenSpacePos, backgroundImageSpacePos)) {
 			return;
+		}
 	}
 }
 
 void ScriptManager::onMouseUp(const Common::Point &screenSpacePos, const Common::Point &backgroundImageSpacePos) {
-	if (!_activeControls)
+	if (!_activeControls) {
 		return;
+	}
 	for (ControlList::iterator iter = _activeControls->reverse_begin(); iter != _activeControls->end(); iter--) {
-		if ((*iter)->onMouseUp(screenSpacePos, backgroundImageSpacePos))
+		if ((*iter)->onMouseUp(screenSpacePos, backgroundImageSpacePos)) {
 			return;
+		}
 	}
 }
 
 bool ScriptManager::onMouseMove(const Common::Point &screenSpacePos, const Common::Point &backgroundImageSpacePos) {
-	if (!_activeControls)
+	if (!_activeControls) {
 		return false;
+	}
+
 	for (ControlList::iterator iter = _activeControls->reverse_begin(); iter != _activeControls->end(); iter--) {
-		if ((*iter)->onMouseMove(screenSpacePos, backgroundImageSpacePos))
+		if ((*iter)->onMouseMove(screenSpacePos, backgroundImageSpacePos)) {
 			return true;
+		}
 	}
+
 	return false;
 }
 
 void ScriptManager::onKeyDown(Common::KeyState keyState) {
-	if (!_activeControls)
+	if (!_activeControls) {
 		return;
+	}
 	for (ControlList::iterator iter = _activeControls->begin(); iter != _activeControls->end(); ++iter) {
-		if ((*iter)->onKeyDown(keyState))
+		if ((*iter)->onKeyDown(keyState)) {
 			return;
+		}
 	}
 }
 
 void ScriptManager::onKeyUp(Common::KeyState keyState) {
-	if (!_activeControls)
+	if (!_activeControls) {
 		return;
+	}
 	for (ControlList::iterator iter = _activeControls->begin(); iter != _activeControls->end(); ++iter) {
-		if ((*iter)->onKeyUp(keyState))
+		if ((*iter)->onKeyUp(keyState)) {
 			return;
+		}
 	}
 }
 
 void ScriptManager::changeLocation(const Location &_newLocation) {
-
 	changeLocation(_newLocation.world, _newLocation.room, _newLocation.node, _newLocation.view, _newLocation.offset);
 }
 
 void ScriptManager::changeLocation(char world, char room, char node, char view, uint32 offset) {
 	_changeLocationDelayCycles = 1;
+
 	_nextLocation.world = world;
 	_nextLocation.room = room;
 	_nextLocation.node = node;
@@ -528,10 +604,12 @@ void ScriptManager::changeLocation(char world, char room, char node, char view,
 void ScriptManager::ChangeLocationReal(bool isLoading) {
 	assert(_nextLocation.world != 0);
 	debug(1, "\tChanging location to: World %c, Room %c, Node %c, View %c, Offset %u", _nextLocation.world, _nextLocation.room, _nextLocation.node, _nextLocation.view, _nextLocation.offset);
+
 	const bool enteringMenu = (_nextLocation.world == 'g' && _nextLocation.room == 'j');
 	const bool leavingMenu = (_currentLocation.world == 'g' && _currentLocation.room == 'j');
 	const bool isSaveScreen = (enteringMenu && _nextLocation.node == 's' && _nextLocation.view == 'e');
 	const bool isRestoreScreen = (enteringMenu && _nextLocation.node == 'r' && _nextLocation.view == 'e');
+
 	if (enteringMenu && !ConfMan.getBool("originalsaveload")) {
 		if (isSaveScreen || isRestoreScreen) {
 			// Hook up the ScummVM save/restore dialog
@@ -543,6 +621,7 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 				_nextLocation.node = _currentLocation.node;
 				_nextLocation.view = _currentLocation.view;
 				_nextLocation.offset = _currentLocation.offset;
+
 				return;
 			} else {
 				_currentLocation.world = 'g';
@@ -553,7 +632,9 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 			}
 		}
 	}
+
 	//_engine->setRenderDelay(2); //Uncertain if this is necessary; doesn't seem to cause any problems when disabled, but keep an eye on it.
+
 	if (!leavingMenu) {
 		if (!isLoading && !enteringMenu) {
 			setStateValue(StateKey_LastWorld, getStateValue(StateKey_World));
@@ -571,10 +652,14 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 	}
 
 	if (enteringMenu) {
-		if (isSaveScreen && !leavingMenu)
+		if (isSaveScreen && !leavingMenu) {
 			_engine->getSaveManager()->prepareSaveBuffer();
-	} else if (leavingMenu)
-		_engine->getSaveManager()->flushSaveBuffer();
+		}
+	} else {
+		if (leavingMenu) {
+			_engine->getSaveManager()->flushSaveBuffer();
+		}
+	}
 
 	setStateValue(StateKey_World, _nextLocation.world);
 	setStateValue(StateKey_Room, _nextLocation.room);
@@ -591,29 +676,38 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 		cleanScriptScope(_nodeview);
 		cleanScriptScope(_room);
 		cleanScriptScope(_world);
+
 		Common::Path fileName(Common::String::format("%c%c%c%c.scr", _nextLocation.world, _nextLocation.room, _nextLocation.node, _nextLocation.view));
 		parseScrFile(fileName, _nodeview);
 		addPuzzlesToReferenceTable(_nodeview);
+
 		fileName = Common::Path(Common::String::format("%c%c.scr", _nextLocation.world, _nextLocation.room));
 		parseScrFile(fileName, _room);
 		addPuzzlesToReferenceTable(_room);
+
 		fileName = Common::Path(Common::String::format("%c.scr", _nextLocation.world));
 		parseScrFile(fileName, _world);
 		addPuzzlesToReferenceTable(_world);
 	} else if (_nextLocation.room != _currentLocation.room) {
 		cleanScriptScope(_nodeview);
 		cleanScriptScope(_room);
+
 		addPuzzlesToReferenceTable(_world);
+
 		Common::Path fileName(Common::String::format("%c%c%c%c.scr", _nextLocation.world, _nextLocation.room, _nextLocation.node, _nextLocation.view));
 		parseScrFile(fileName, _nodeview);
 		addPuzzlesToReferenceTable(_nodeview);
+
 		fileName = Common::Path(Common::String::format("%c%c.scr", _nextLocation.world, _nextLocation.room));
 		parseScrFile(fileName, _room);
 		addPuzzlesToReferenceTable(_room);
+
 	} else if (_nextLocation.node != _currentLocation.node || _nextLocation.view != _currentLocation.view) {
 		cleanScriptScope(_nodeview);
+
 		addPuzzlesToReferenceTable(_room);
 		addPuzzlesToReferenceTable(_world);
+
 		Common::Path fileName(Common::String::format("%c%c%c%c.scr", _nextLocation.world, _nextLocation.room, _nextLocation.node, _nextLocation.view));
 		parseScrFile(fileName, _nodeview);
 		addPuzzlesToReferenceTable(_nodeview);
@@ -659,51 +753,74 @@ void ScriptManager::serialize(Common::WriteStream *stream) {
 	stream->writeByte(getStateValue(StateKey_Node));
 	stream->writeByte(getStateValue(StateKey_View));
 	stream->writeUint32LE(getStateValue(StateKey_ViewPos));
-	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); ++iter)
+
+	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); ++iter) {
 		(*iter)->serialize(stream);
+	}
+
 	stream->writeUint32BE(MKTAG('F', 'L', 'A', 'G'));
+
 	int32 slots = _engine->getGameId() == GID_NEMESIS ? 31000 : 21000;
 	//Original games use key values up to 29500 and 19737, respectively
 	//Values 30001~31000 and 20001~21000 are now set aside for auxiliary scripting to add extra directional audio effects.
+
 	stream->writeUint32LE(slots * 2);
-	for (int32 i = 0; i < slots; i++)
+
+	for (int32 i = 0; i < slots; i++) {
 		stream->writeUint16LE(getStateFlag(i));
+	}
+
 	stream->writeUint32BE(MKTAG('P', 'U', 'Z', 'Z'));
+
 	stream->writeUint32LE(slots * 2);
-	for (int32 i = 0; i < slots; i++)
+
+	for (int32 i = 0; i < slots; i++) {
 		stream->writeSint16LE(getStateValue(i));
+	}
 }
 
 void ScriptManager::deserialize(Common::SeekableReadStream *stream) {
 	// Clear out the current table values
 	_globalState.clear();
 	_globalStateFlags.clear();
+
 	cleanScriptScope(_nodeview);
 	cleanScriptScope(_room);
 	cleanScriptScope(_world);
+
 	_currentLocation.node = 0;
 	_currentLocation.world = 0;
 	_currentLocation.room = 0;
 	_currentLocation.view = 0;
-	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); iter++)
-		delete (*iter);
+
+	for (SideFXList::iterator iter = _activeSideFx.begin(); iter != _activeSideFx.end(); iter++) {
+		delete(*iter);
+	}
+
 	_activeSideFx.clear();
+
 	_referenceTable.clear();
+
 	if (stream->readUint32BE() != MKTAG('Z', 'N', 'S', 'G') || stream->readUint32LE() != 4) {
 		changeLocation('g', 'a', 'r', 'y', 0);
 		return;
 	}
+
 	stream->seek(4, SEEK_CUR);
+
 	if (stream->readUint32BE() != MKTAG('L', 'O', 'C', ' ') || stream->readUint32LE() != 8) {
 		changeLocation('g', 'a', 'r', 'y', 0);
 		return;
 	}
+
 	Location nextLocation;
+
 	nextLocation.world = stream->readByte();
 	nextLocation.room = stream->readByte();
 	nextLocation.node = stream->readByte();
 	nextLocation.view = stream->readByte();
 	nextLocation.offset = stream->readUint32LE() & 0x0000FFFF;
+
 	while (stream->pos() < stream->size()) {
 		uint32 tag = stream->readUint32BE();
 		uint32 tagSize = stream->readUint32LE();
@@ -711,36 +828,43 @@ void ScriptManager::deserialize(Common::SeekableReadStream *stream) {
 		case MKTAG('T', 'I', 'M', 'R'): {
 			uint32 key = stream->readUint32LE();
 			uint32 time = stream->readUint32LE();
-			if (_engine->getGameId() == GID_GRANDINQUISITOR)
+			if (_engine->getGameId() == GID_GRANDINQUISITOR) {
 				time /= 100;
-			else if (_engine->getGameId() == GID_NEMESIS)
+			} else if (_engine->getGameId() == GID_NEMESIS) {
 				time /= 1000;
+			}
 			addSideFX(new TimerNode(_engine, key, time));
 		}
 		break;
 		case MKTAG('F', 'L', 'A', 'G'):
-			for (uint32 i = 0; i < tagSize / 2; i++)
+			for (uint32 i = 0; i < tagSize / 2; i++) {
 				setStateFlagSilent(i, stream->readUint16LE());
+			}
 			break;
 		case MKTAG('P', 'U', 'Z', 'Z'):
-			for (uint32 i = 0; i < tagSize / 2; i++)
+			for (uint32 i = 0; i < tagSize / 2; i++) {
 				setStateValueSilent(i, stream->readUint16LE());
+			}
 			break;
 		default:
 			stream->seek(tagSize, SEEK_CUR);
-			break;
 		}
 	}
+
 	_nextLocation = nextLocation;
+
 	ChangeLocationReal(true);
+
 	_engine->setRenderDelay(10);
 	setStateValue(StateKey_RestoreFlag, 1);
+
 	_engine->loadSettings();
 }
 
 Location ScriptManager::getCurrentLocation() const {
 	Location location = _currentLocation;
 	location.offset = _engine->getRenderManager()->getCurrentBackgroundOffset();
+
 	return location;
 }
 
@@ -751,6 +875,7 @@ Location ScriptManager::getLastLocation() {
 	location.node = getStateValue(StateKey_LastNode);
 	location.view = getStateValue(StateKey_LastView);
 	location.offset = getStateValue(StateKey_LastViewPos);
+
 	return location;
 }
 
@@ -761,6 +886,7 @@ Location ScriptManager::getLastMenuLocation() {
 	location.node = getStateValue(StateKey_Menu_LastNode);
 	location.view = getStateValue(StateKey_Menu_LastView);
 	location.offset = getStateValue(StateKey_Menu_LastViewPos);
+
 	return location;
 }
 
@@ -771,18 +897,22 @@ void ScriptManager::addEvent(Common::Event event) {
 void ScriptManager::flushEvent(Common::EventType type) {
 	EventList::iterator it = _controlEvents.begin();
 	while (it != _controlEvents.end()) {
-		if ((*it).type == type)
+
+		if ((*it).type == type) {
 			it = _controlEvents.erase(it);
-		else
+		} else {
 			it++;
+		}
 	}
 }
 
 void ScriptManager::trimCommentsAndWhiteSpace(Common::String *string) const {
 	for (int i = string->size() - 1; i >= 0; i--) {
-		if ((*string)[i] == '#')
+		if ((*string)[i] == '#') {
 			string->erase(i);
+		}
 	}
+
 	string->trim();
 }
 
@@ -801,12 +931,15 @@ ValueSlot::ValueSlot(ScriptManager *scriptManager, const char *slotValue):
 }
 int16 ValueSlot::getValue() {
 	if (_slot) {
-		if (_value >= 0)
+		if (_value >= 0) {
 			return _scriptManager->getStateValue(_value);
-		else
+		}
+		else {
 			return 0;
-	} else
+		}
+	} else {
 		return _value;
+	}
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/script_manager.h b/engines/zvision/scripting/script_manager.h
index cd4341f7698..ed6496778ef 100644
--- a/engines/zvision/scripting/script_manager.h
+++ b/engines/zvision/scripting/script_manager.h
@@ -104,6 +104,7 @@ enum StateKey {
 
 struct Location {
 	Location() : world('g'), room('a'), node('r'), view('y'), offset(0) {}
+
 	char world;
 	char room;
 	char node;
@@ -111,25 +112,25 @@ struct Location {
 	uint32 offset;
 };
 
-inline bool operator==(const Location &lhs, const Location &rhs) {
+inline bool operator==(const Location& lhs, const Location& rhs) {
 	return (
-	           lhs.world == rhs.world &&
-	           lhs.room == rhs.room &&
-	           lhs.node == rhs.node &&
-	           lhs.view == rhs.view
-	       );
+		lhs.world == rhs.world &&
+		lhs.room == rhs.room &&
+		lhs.node == rhs.node &&
+		lhs.view == rhs.view
+	);
 }
 
-inline bool operator==(const Location &lhs, const char *rhs) {
+inline bool operator==(const Location& lhs, const char* rhs) {
 	Common::String lhsStr = Common::String::format("%c%c%c%c", lhs.world, lhs.room, lhs.node, lhs.view);
 	return lhsStr == rhs;
 }
 
-inline bool operator!=(const Location &lhs, const Location &rhs) {
+inline bool operator!=(const Location& lhs, const Location& rhs) {
 	return !(lhs == rhs);
 }
 
-inline bool operator!=(const Location &lhs, const char *rhs) {
+inline bool operator!=(const Location& lhs, const char* rhs) {
 	return !(lhs == rhs);
 }
 
diff --git a/engines/zvision/sound/midi.cpp b/engines/zvision/sound/midi.cpp
index c9fc97294e9..16f19002d3a 100644
--- a/engines/zvision/sound/midi.cpp
+++ b/engines/zvision/sound/midi.cpp
@@ -64,6 +64,7 @@ void MidiManager::stop() {
 
 void MidiManager::noteOn(uint8 channel, uint8 note, uint8 velocity) {
 	assert(channel <= 15);
+
 	_activeChannels[channel].playing = true;
 	_activeChannels[channel].note = note;
 	send(0x90 | channel, note, velocity);
@@ -72,6 +73,7 @@ void MidiManager::noteOn(uint8 channel, uint8 note, uint8 velocity) {
 
 void MidiManager::noteOff(uint8 channel) {
 	assert(channel <= 15);
+
 	if (_activeChannels[channel].playing) {
 		_activeChannels[channel].playing = false;
 		send(0x80 | channel, _activeChannels[channel].note);
diff --git a/engines/zvision/sound/midi.h b/engines/zvision/sound/midi.h
index 7a1267ba124..d285824ae44 100644
--- a/engines/zvision/sound/midi.h
+++ b/engines/zvision/sound/midi.h
@@ -50,6 +50,7 @@ protected:
 	struct chan {
 		bool playing;
 		uint8 note;
+
 		chan() : playing(false), note(0) {};
 	};
 	void send(uint8 status, uint8 data1 = 0x00, uint8 data2 = 0x00);
diff --git a/engines/zvision/sound/volume_manager.cpp b/engines/zvision/sound/volume_manager.cpp
index 2d636671dc3..474935b8b78 100644
--- a/engines/zvision/sound/volume_manager.cpp
+++ b/engines/zvision/sound/volume_manager.cpp
@@ -179,7 +179,6 @@ uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode) {
 		output = pow(scaledInput, 4) / pow(255, 3);
 		break;
 	case kVolumeLinear:
-	// fall through
 	default:
 		output = scaledInput;
 		break;
diff --git a/engines/zvision/sound/zork_raw.cpp b/engines/zvision/sound/zork_raw.cpp
index 60016d6ee23..2f74c964b59 100644
--- a/engines/zvision/sound/zork_raw.cpp
+++ b/engines/zvision/sound/zork_raw.cpp
@@ -232,9 +232,9 @@ bool RawZorkStream::rewind() {
 }
 
 Audio::RewindableAudioStream *makeRawZorkStream(Common::SeekableReadStream *stream,
-        int rate,
-        bool stereo,
-        DisposeAfterUse::Flag disposeAfterUse) {
+		int rate,
+		bool stereo,
+		DisposeAfterUse::Flag disposeAfterUse) {
 	if (stereo)
 		assert(stream->size() % 2 == 0);
 
diff --git a/engines/zvision/sound/zork_raw.h b/engines/zvision/sound/zork_raw.h
index 47803188e2e..257896a542f 100644
--- a/engines/zvision/sound/zork_raw.h
+++ b/engines/zvision/sound/zork_raw.h
@@ -130,9 +130,9 @@ public:
  * @return           The new SeekableAudioStream (or 0 on failure).
  */
 Audio::RewindableAudioStream *makeRawZorkStream(Common::SeekableReadStream *stream,
-        int rate,
-        bool stereo,
-        DisposeAfterUse::Flag disposeAfterUse = DisposeAfterUse::YES);
+		int rate,
+		bool stereo,
+		DisposeAfterUse::Flag disposeAfterUse = DisposeAfterUse::YES);
 
 Audio::RewindableAudioStream *makeRawZorkStream(const Common::Path &filePath, ZVision *engine);
 
diff --git a/engines/zvision/text/text.cpp b/engines/zvision/text/text.cpp
index f515e37b70f..40aa80da165 100644
--- a/engines/zvision/text/text.cpp
+++ b/engines/zvision/text/text.cpp
@@ -42,16 +42,16 @@ TextStyleState::TextStyleState() {
 	_green = 255;
 	_red = 255;
 	_bold = false;
-	#if 0
+#if 0
 	_newline = false;
 	_escapement = 0;
-	#endif
+#endif
 	_italic = false;
 	_justification = TEXT_JUSTIFY_LEFT;
 	_size = 12;
-	#if 0
+#if 0
 	_skipcolor = false;
-	#endif
+#endif
 	_strikeout = false;
 	_underline = false;
 	_statebox = 0;
@@ -117,12 +117,12 @@ TextChange TextStyleState::parseStyle(const Common::String &str, int16 len) {
 				}
 			}
 		} else if (token.matchString("newline", true)) {
-			#if 0
+#if 0
 			if ((retval & TXT_RET_NEWLN) == 0)
 				_newline = 0;
 
 			_newline++;
-			#endif
+#endif
 			retval |= TEXT_CHANGE_NEWLINE;
 		} else if (token.matchString("point", true)) {
 			if (!tokenizer.empty()) {
@@ -136,10 +136,10 @@ TextChange TextStyleState::parseStyle(const Common::String &str, int16 len) {
 		} else if (token.matchString("escapement", true)) {
 			if (!tokenizer.empty()) {
 				token = tokenizer.nextToken();
-				#if 0
+#if 0
 				int32 tmp = atoi(token.c_str());
 				_escapement = tmp;
-				#endif
+#endif
 			}
 		} else if (token.matchString("italic", true)) {
 			if (!tokenizer.empty()) {
@@ -204,13 +204,13 @@ TextChange TextStyleState::parseStyle(const Common::String &str, int16 len) {
 		} else if (token.matchString("skipcolor", true)) {
 			if (!tokenizer.empty()) {
 				token = tokenizer.nextToken();
-				#if 0
+#if 0
 				if (token.matchString("on", true)) {
 					_skipcolor = true;
 				} else if (token.matchString("off", true)) {
 					_skipcolor = false;
 				}
-				#endif
+#endif
 			}
 		} else if (token.matchString("image", true)) {
 			// Not used
@@ -238,6 +238,7 @@ TextChange TextStyleState::parseStyle(const Common::String &str, int16 len) {
 void TextStyleState::readAllStyles(const Common::String &txt) {
 	int16 startTextPosition = -1;
 	int16 endTextPosition = -1;
+
 	for (uint16 i = 0; i < txt.size(); i++) {
 		if (txt[i] == '<')
 			startTextPosition = i;
@@ -249,11 +250,13 @@ void TextStyleState::readAllStyles(const Common::String &txt) {
 				}
 			}
 		}
+
 	}
 }
 
 void TextStyleState::updateFontWithTextState(StyledTTFont &font) {
 	uint tempStyle = 0;
+
 	if (_bold) {
 		tempStyle |= StyledTTFont::TTF_STYLE_BOLD;
 	}
@@ -269,6 +272,7 @@ void TextStyleState::updateFontWithTextState(StyledTTFont &font) {
 	if (_sharp) {
 		tempStyle |= StyledTTFont::TTF_STYLE_SHARP;
 	}
+
 	font.loadFont(_fontname, _size, tempStyle);
 }
 
@@ -289,8 +293,10 @@ void TextRenderer::drawTextWithJustification(const Common::String &text, StyledT
 int32 TextRenderer::drawText(const Common::String &text, TextStyleState &state, Graphics::Surface &dest) {
 	StyledTTFont font(_engine);
 	state.updateFontWithTextState(font);
+
 	uint32 color = _engine->_resourcePixelFormat.RGBToColor(state._red, state._green, state._blue);
 	drawTextWithJustification(text, font, color, dest, 0, state._justification);
+
 	return font.getStringWidth(text);
 }
 
@@ -343,6 +349,7 @@ void TextRenderer::drawTextWithWordWrapping(const Common::String &text, Graphics
 			// Flush the currentWord to the currentSentence
 			currentSentence += currentWord;
 			sentenceWidth += wordWidth;
+
 			// Reset the word variables
 			currentWord.clear();
 			wordWidth = 0;
@@ -480,10 +487,13 @@ void TextRenderer::drawTextWithWordWrapping(const Common::String &text, Graphics
 	if (!currentWord.empty() || !currentSentence.empty()) {
 		currentSentence += currentWord;
 		sentenceWidth += wordWidth;
+
 		textSurfaces.push_back(TextSurface(font.renderSolidText(currentSentence, currentState.getTextColor(_engine)), sentencePixelOffset, currentLineNumber));
 	}
+
 	lineWidths.push_back(lineWidth + sentenceWidth);
 	lineJustifications.push_back(currentState._justification);
+
 	for (Common::Array<TextSurface>::iterator iter = textSurfaces.begin(); iter != textSurfaces.end(); ++iter) {
 		Common::Rect empty;
 		int16 Xpos = iter->_surfaceOffset.x;
@@ -521,6 +531,7 @@ Common::U32String readWideLine(Common::SeekableReadStream &stream) {
 			// End of the line. Break
 			break;
 		}
+
 		asciiString += value;
 	}
 	return asciiString;
diff --git a/engines/zvision/text/truetype_font.cpp b/engines/zvision/text/truetype_font.cpp
index 6de91b4d71c..83d9a1422ec 100644
--- a/engines/zvision/text/truetype_font.cpp
+++ b/engines/zvision/text/truetype_font.cpp
@@ -38,15 +38,15 @@
 namespace ZVision {
 
 const FontStyle systemFonts[] = {
-	{ "*times new roman*",    "times",   "LiberationSerif"  },
-	{ "*times*",          "times",   "LiberationSerif"  },
+	{ "*times new roman*",	  "times",   "LiberationSerif"  },
+	{ "*times*",		  "times",   "LiberationSerif"  },
 	{ "*century schoolbook*", "censcbk", "LiberationSerif"  },
-	{ "*garamond*",       "gara",    "LiberationSerif"  },
-	{ "*courier new*",    "cour",    "LiberationMono" },
-	{ "*courier*",        "cour",    "LiberationMono" },
-	{ "*ZorkDeath*",      "cour",    "LiberationMono" },
-	{ "*arial*",          "arial",   "LiberationSans" },
-	{ "*ZorkNormal*",     "arial",   "LiberationSans" }
+	{ "*garamond*", 	  "gara",    "LiberationSerif"  },
+	{ "*courier new*",	  "cour",    "LiberationMono" },
+	{ "*courier*",		  "cour",    "LiberationMono" },
+	{ "*ZorkDeath*",	  "cour",    "LiberationMono" },
+	{ "*arial*",		  "arial",   "LiberationSans" },
+	{ "*ZorkNormal*",	  "arial",   "LiberationSans" }
 };
 
 const FontStyle getSystemFont(int fontIndex) {
diff --git a/engines/zvision/video/rlf_decoder.cpp b/engines/zvision/video/rlf_decoder.cpp
index 93cb67c93e9..48cbc9073fd 100644
--- a/engines/zvision/video/rlf_decoder.cpp
+++ b/engines/zvision/video/rlf_decoder.cpp
@@ -196,50 +196,60 @@ bool RLFDecoder::RLFVideoTrack::seek(const Audio::Timestamp &time) {
 const Graphics::Surface *RLFDecoder::RLFVideoTrack::decodeNextFrame() {
 	if (_displayedFrame >= (int)_frameCount)
 		return NULL;
+
 	_displayedFrame++;
 	applyFrameToCurrent(_displayedFrame);
+
 	return &_currentFrameBuffer;
 }
 
 void RLFDecoder::RLFVideoTrack::applyFrameToCurrent(uint frameNumber) {
-	if (_frames[frameNumber].type == Masked)
+	if (_frames[frameNumber].type == Masked) {
 		decodeMaskedRunLengthEncoding(_frames[frameNumber].encodedData, (int8 *)_currentFrameBuffer.getPixels(), _frames[frameNumber].encodedSize, _frameBufferByteSize);
-	else if (_frames[frameNumber].type == Simple)
+	} else if (_frames[frameNumber].type == Simple) {
 		decodeSimpleRunLengthEncoding(_frames[frameNumber].encodedData, (int8 *)_currentFrameBuffer.getPixels(), _frames[frameNumber].encodedSize, _frameBufferByteSize);
+	}
 }
 
 void RLFDecoder::RLFVideoTrack::decodeMaskedRunLengthEncoding(int8 *source, int8 *dest, uint32 sourceSize, uint32 destSize) const {
 	uint32 sourceOffset = 0;
 	uint32 destOffset = 0;
 	int16 numberOfCopy = 0;
+
 	while (sourceOffset < sourceSize) {
 		int8 numberOfSamples = source[sourceOffset];
 		sourceOffset++;
+
 		// If numberOfSamples is negative, the next abs(numberOfSamples) samples should
 		// be copied directly from source to dest
 		if (numberOfSamples < 0) {
 			numberOfCopy = -numberOfSamples;
+
 			while (numberOfCopy > 0) {
-				if (sourceOffset + 1 >= sourceSize)
+				if (sourceOffset + 1 >= sourceSize) {
 					return;
-				else if (destOffset + 1 >= destSize) {
+				} else if (destOffset + 1 >= destSize) {
 					debug(3, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
 					return;
 				}
+
 				WRITE_UINT16(dest + destOffset, READ_LE_UINT16(source + sourceOffset));
+
 				sourceOffset += 2;
 				destOffset += 2;
 				numberOfCopy--;
 			}
+
 			// If numberOfSamples is >= 0, move destOffset forward ((numberOfSamples * 2) + 2)
 			// This function assumes the dest buffer has been memset with 0's.
 		} else {
-			if (sourceOffset + 1 >= sourceSize)
+			if (sourceOffset + 1 >= sourceSize) {
 				return;
-			else if (destOffset + 1 >= destSize) {
+			} else if (destOffset + 1 >= destSize) {
 				debug(3, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
 				return;
 			}
+
 			destOffset += (numberOfSamples * 2) + 2;
 		}
 	}
@@ -249,13 +259,16 @@ void RLFDecoder::RLFVideoTrack::decodeSimpleRunLengthEncoding(int8 *source, int8
 	uint32 sourceOffset = 0;
 	uint32 destOffset = 0;
 	int16 numberOfCopy = 0;
+
 	while (sourceOffset < sourceSize) {
 		int8 numberOfSamples = source[sourceOffset];
 		sourceOffset++;
+
 		// If numberOfSamples is negative, the next abs(numberOfSamples) samples should
 		// be copied directly from source to dest
 		if (numberOfSamples < 0) {
 			numberOfCopy = -numberOfSamples;
+
 			while (numberOfCopy > 0) {
 				if (sourceOffset + 1 >= sourceSize) {
 					return;
@@ -263,24 +276,31 @@ void RLFDecoder::RLFVideoTrack::decodeSimpleRunLengthEncoding(int8 *source, int8
 					debug(3, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
 					return;
 				}
+
 				WRITE_UINT16(dest + destOffset, READ_LE_UINT16(source + sourceOffset));
+
 				sourceOffset += 2;
 				destOffset += 2;
 				numberOfCopy--;
 			}
+
 			// If numberOfSamples is >= 0, copy one sample from source to the
 			// next (numberOfSamples + 2) dest spots
 		} else {
-			if (sourceOffset + 1 >= sourceSize)
+			if (sourceOffset + 1 >= sourceSize) {
 				return;
+			}
+
 			uint16 sampleColor = READ_LE_UINT16(source + sourceOffset);
 			sourceOffset += 2;
+
 			numberOfCopy = numberOfSamples + 2;
 			while (numberOfCopy > 0) {
 				if (destOffset + 1 >= destSize) {
 					debug(3, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
 					return;
 				}
+
 				WRITE_UINT16(dest + destOffset, sampleColor);
 				destOffset += 2;
 				numberOfCopy--;
diff --git a/engines/zvision/video/rlf_decoder.h b/engines/zvision/video/rlf_decoder.h
index 32f640676f7..27b117f3648 100644
--- a/engines/zvision/video/rlf_decoder.h
+++ b/engines/zvision/video/rlf_decoder.h
@@ -42,31 +42,17 @@ private:
 		RLFVideoTrack(Common::SeekableReadStream *stream);
 		~RLFVideoTrack() override;
 
-		uint16 getWidth() const override {
-			return _width;
-		}
-		uint16 getHeight() const override {
-			return _height;
-		}
-		Graphics::PixelFormat getPixelFormat() const override {
-			return Graphics::PixelFormat(2, 5, 5, 5, 0, 10, 5, 0, 0); /* RGB 555 */
-		}
-		int getCurFrame() const override {
-			return _displayedFrame;
-		}
-		int getFrameCount() const override {
-			return _frameCount;
-		}
+		uint16 getWidth() const override { return _width; }
+		uint16 getHeight() const override { return _height; }
+		Graphics::PixelFormat getPixelFormat() const override { return Graphics::PixelFormat(2, 5, 5, 5, 0, 10, 5, 0, 0); /* RGB 555 */ }
+		int getCurFrame() const override { return _displayedFrame; }
+		int getFrameCount() const override { return _frameCount; }
 		const Graphics::Surface *decodeNextFrame() override;
-		bool isSeekable() const override {
-			return true;
-		}
+		bool isSeekable() const override { return true; }
 		bool seek(const Audio::Timestamp &time) override;
 
 	protected:
-		Common::Rational getFrameRate() const override {
-			return Common::Rational(1000, _frameTime);
-		}
+		Common::Rational getFrameRate() const override { return Common::Rational(1000, _frameTime); }
 
 	private:
 		enum EncodingType {
@@ -139,7 +125,7 @@ private:
 		uint32 _frameBufferByteSize;
 
 		Common::SeekableReadStream *_readStream;
-	};  // RLFVideoTrack
+	};	// RLFVideoTrack
 };
 
 } // End of namespace ZVision
diff --git a/engines/zvision/video/video.cpp b/engines/zvision/video/video.cpp
index 38ba7b8dbb9..f82254a03b9 100644
--- a/engines/zvision/video/video.cpp
+++ b/engines/zvision/video/video.cpp
@@ -23,7 +23,7 @@
 #include "common/system.h"
 #include "video/video_decoder.h"
 #if defined(USE_MPEG2) && defined(USE_A52)
-	#include "video/mpegps_decoder.h"
+#include "video/mpegps_decoder.h"
 #endif
 #include "engines/util.h"
 #include "graphics/surface.h"
@@ -51,20 +51,23 @@ Video::VideoDecoder *ZVision::loadAnimation(const Common::Path &fileName) {
 		animation = new RLFDecoder();
 	else if (tmpFileName.hasSuffix(".avi"))
 		animation = new ZorkAVIDecoder();
-	#if defined(USE_MPEG2) && defined(USE_A52)
+#if defined(USE_MPEG2) && defined(USE_A52)
 	else if (tmpFileName.hasSuffix(".vob")) {
-		double amplification = getVobAmplification(tmpFileName);
+ 		double amplification = getVobAmplification(tmpFileName);
 		animation = new Video::MPEGPSDecoder(amplification);
 	}
-	#endif
+#endif
 	else
 		error("Unknown suffix for animation %s", fileName.toString().c_str());
+
 	Common::File *_file = getSearchManager()->openFile(fileName);
 	if (!_file)
 		error("Error opening %s", fileName.toString().c_str());
+
 	bool loaded = animation->loadStream(_file);
 	if (!loaded)
 		error("Error loading animation %s", fileName.toString().c_str());
+
 	return animation;
 }
 
@@ -115,10 +118,13 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 		debug(1, "Video will be scaled from %dx%d to %dx%d", _srcRect.width(), _srcRect.height(), _dstRect.width(), _dstRect.height());
 		scaled = true;
 	}
+
 	bool showSubs = (_scriptManager->getStateValue(StateKey_Subtitles) == 1);
+
 	_clock.stop();
 	vid.start();
 	_videoIsPlaying = true;
+
 	_cutscenesKeymap->setEnabled(true);
 	_gameKeymap->setEnabled(false);
 
@@ -133,8 +139,9 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 					quitGame();
 					break;
 				case kZVisionActionSkipCutscene:
-					if (skippable)
+					if (skippable) {
 						vid.stop();
+					}
 					break;
 				default:
 					break;
@@ -148,6 +155,7 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 			const Graphics::Surface *frame = vid.decodeNextFrame();
 			if (showSubs && sub > 0)
 				_subtitleManager->update(vid.getCurFrame(), sub);
+
 			if (frame) {
 				_renderManager->renderSceneToScreen(true, true, true); //Redraw text area to clean background of subtitles for videos that don't fill entire working area, e.g, Nemesis sarcophagi
 				if (scaled) {
@@ -160,14 +168,19 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 				_subtitleManager->process(0);
 			}
 		}
+
 		// Always update the screen so the mouse continues to render & video does not skip
 		_renderManager->renderSceneToScreen(true, true, false);
+
 		_system->delayMillis(vid.getTimeToNextFrame() / 2); //Exponentially decaying delay
 	}
+
 	_cutscenesKeymap->setEnabled(false);
 	_gameKeymap->setEnabled(true);
+
 	_videoIsPlaying = false;
 	_clock.start();
+
 	debug(1, "Video playback complete");
 }
 
diff --git a/engines/zvision/video/zork_avi_decoder.cpp b/engines/zvision/video/zork_avi_decoder.cpp
index 4545d5065d8..7137ceabdfc 100644
--- a/engines/zvision/video/zork_avi_decoder.cpp
+++ b/engines/zvision/video/zork_avi_decoder.cpp
@@ -41,7 +41,7 @@ Video::AVIDecoder::AVIAudioTrack *ZorkAVIDecoder::createAudioTrack(Video::AVIDec
 }
 
 ZorkAVIDecoder::ZorkAVIAudioTrack::ZorkAVIAudioTrack(const AVIStreamHeader &streamHeader, const PCMWaveFormat &waveFormat, Audio::Mixer::SoundType soundType) :
-	Video::AVIDecoder::AVIAudioTrack(streamHeader, waveFormat, soundType), _queueStream(0), _decoder(waveFormat.channels == 2) {
+		Video::AVIDecoder::AVIAudioTrack(streamHeader, waveFormat, soundType), _queueStream(0), _decoder(waveFormat.channels == 2) {
 }
 
 void ZorkAVIDecoder::ZorkAVIAudioTrack::createAudioStream() {
@@ -57,10 +57,10 @@ void ZorkAVIDecoder::ZorkAVIAudioTrack::queueSound(Common::SeekableReadStream *s
 		byte flags = Audio::FLAG_16BITS;
 		if (_wvInfo.channels == 2)
 			flags |= Audio::FLAG_STEREO;
-		#ifdef SCUMM_LITTLE_ENDIAN
+#ifdef SCUMM_LITTLE_ENDIAN
 		// RawChunkStream produces native endianness int16
 		flags |= Audio::FLAG_LITTLE_ENDIAN;
-		#endif
+#endif
 		_queueStream->queueBuffer((byte *)chunk.data, chunk.size, DisposeAfterUse::YES, flags);
 	}
 
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index ce745f6ccc3..ae6ed4ecb0a 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -54,7 +54,6 @@
 #include "engines/util.h"
 #include "audio/mixer.h"
 
-
 namespace ZVision {
 
 #define ZVISION_SETTINGS_KEYS_COUNT 12
@@ -62,7 +61,7 @@ namespace ZVision {
 struct ZvisionIniSettings {
 	const char *name;
 	int16 slot;
-	int16 defaultValue; // -1: use the bool value
+	int16 defaultValue;	// -1: use the bool value
 	bool defaultBoolValue;
 	bool allowEditing;
 } settingsKeys[ZVISION_SETTINGS_KEYS_COUNT] = {
@@ -79,7 +78,7 @@ struct ZvisionIniSettings {
 	{"highquality", StateKey_HighQuality, -1, true, false}, // high panorama quality; enables bilinear filtering in RenderTable
 	{"venusenabled", StateKey_VenusEnable, -1, true, true},
 	{"subtitles", StateKey_Subtitles, -1, true, true},
-	{"mpegmovies", StateKey_MPEGMovies, -1, true, true}     // Zork: Grand Inquisitor DVD hi-res MPEG movies (0 = normal, 1 = hires, 2 = disable option)
+	{"mpegmovies", StateKey_MPEGMovies, -1, true, true}		// Zork: Grand Inquisitor DVD hi-res MPEG movies (0 = normal, 1 = hires, 2 = disable option)
 };
 
 const char *mainKeymapId = "zvision";
@@ -121,12 +120,13 @@ ZVision::ZVision(OSystem *syst, const ZVisionGameDescription *gameDesc)
 
 ZVision::~ZVision() {
 	debug(1, "ZVision::~ZVision");
+
 	// Dispose of resources
 	delete _cursorManager;
 	delete _stringManager;
 	delete _saveManager;
 	delete _scriptManager;
-	delete _renderManager;  // should be deleted after the script manager
+	delete _renderManager;	// should be deleted after the script manager
 	delete _subtitleManager;
 	delete _rnd;
 	delete _midiManager;
@@ -148,15 +148,18 @@ void ZVision::registerDefaultSettings() {
 void ZVision::loadSettings() {
 	int16 value = 0;
 	bool boolValue = false;
+
 	for (int i = 0; i < ZVISION_SETTINGS_KEYS_COUNT; i++) {
-		if (settingsKeys[i].defaultValue >= 0)
+		if (settingsKeys[i].defaultValue >= 0) {
 			value = (settingsKeys[i].allowEditing) ? ConfMan.getInt(settingsKeys[i].name) : settingsKeys[i].defaultValue;
-		else {
+		} else {
 			boolValue = (settingsKeys[i].allowEditing) ? ConfMan.getBool(settingsKeys[i].name) : settingsKeys[i].defaultBoolValue;
 			value = (boolValue) ? 1 : 0;
 		}
+
 		_scriptManager->setStateValue(settingsKeys[i].slot, value);
 	}
+
 	if (getGameId() == GID_NEMESIS)
 		_scriptManager->setStateValue(StateKey_ExecScopeStyle, 1);
 	else
@@ -164,20 +167,24 @@ void ZVision::loadSettings() {
 }
 
 void ZVision::saveSettings() {
-	for (int i = 0; i < ZVISION_SETTINGS_KEYS_COUNT; i++)
+	for (int i = 0; i < ZVISION_SETTINGS_KEYS_COUNT; i++) {
 		if (settingsKeys[i].allowEditing) {
 			if (settingsKeys[i].defaultValue >= 0)
 				ConfMan.setInt(settingsKeys[i].name, _scriptManager->getStateValue(settingsKeys[i].slot));
 			else
 				ConfMan.setBool(settingsKeys[i].name, (_scriptManager->getStateValue(settingsKeys[i].slot) == 1));
 		}
+	}
+
 	ConfMan.flushToDisk();
 }
 
 void ZVision::initialize() {
 	//File Paths
 	const Common::FSNode gameDataDir(ConfMan.getPath("path"));
+
 	_searchManager = new SearchManager(ConfMan.getPath("path"), 6);
+
 	_searchManager->addDir("FONTS");
 	_searchManager->addDir("addon");
 	switch (getGameId()) {
@@ -192,7 +199,6 @@ void ZVision::initialize() {
 				error("Unable to load the file ZNEMSCR/MEDIUM.ZIX");
 		break;
 	case GID_NONE:
-	// fall through
 	default:
 		error("Unknown/unspecified GameId");
 		break;
@@ -203,6 +209,7 @@ void ZVision::initialize() {
 	_doubleFPS = ConfMan.getBool("doublefps");
 
 	//Keymaps
+
 	Common::Keymapper *keymapper = _system->getEventManager()->getKeymapper();
 	_gameKeymap = keymapper->getKeymap(gameKeymapId);
 	_gameKeymap->setEnabled(true);
@@ -227,7 +234,6 @@ void ZVision::initialize() {
 		_volumeManager = new VolumeManager(this, kVolumeLogAmplitude);
 		break;
 	case GID_NONE:
-	// fall through
 	default:
 		error("Unknown/unspecified GameId");
 		break;
@@ -239,6 +245,7 @@ void ZVision::initialize() {
 	_textRenderer = new TextRenderer(this);
 	_midiManager = new MidiManager();
 
+
 	// Initialize the managers
 	_renderManager->initialize();
 	_cursorManager->initialize();
@@ -246,19 +253,19 @@ void ZVision::initialize() {
 	_stringManager->initialize(getGameId());
 
 	registerDefaultSettings();
+
 	loadSettings();
 
-	#if !defined(USE_MPEG2) || !defined(USE_A52)
+#if !defined(USE_MPEG2) || !defined(USE_A52)
 	// libmpeg2 or liba52 not loaded, disable the MPEG2 movies option
 	_scriptManager->setStateValue(StateKey_MPEGMovies, 2);
-	#endif
+#endif
 
 	// Create debugger console. It requires GFX to be initialized
 	setDebugger(new Console(this));
 
 	// Initialize FPS timer callback
 	getTimerManager()->installTimerProc(&fpsTimerCallback, 1000000, this, "zvisionFPS");
-
 	//Ensure a new game is launched with correct panorama quality setting
 	_scriptManager->setStateValue(StateKey_HighQuality, ConfMan.getBool("highquality"));
 }
@@ -272,8 +279,9 @@ Common::Error ZVision::run() {
 	if (ConfMan.hasKey("save_slot"))
 		_saveManager->loadGame(ConfMan.getInt("save_slot"));
 
-	// Before starting, make absolutely sure that the user has copied the needed fonts
 	bool foundAllFonts = true;
+
+	// Before starting, make absolutely sure that the user has copied the needed fonts
 	for (int i = 0; i < FONT_COUNT; i++) {
 		FontStyle curFont = getSystemFont(i);
 
@@ -299,26 +307,28 @@ Common::Error ZVision::run() {
 			liberationFontName += ".ttf";
 
 			if (!Common::File::exists(Common::Path(fontName)) && !_searchManager->hasFile(Common::Path(fontName)) &&
-			        !Common::File::exists(Common::Path(liberationFontName)) && !_searchManager->hasFile(Common::Path(liberationFontName)) &&
-			        !Common::File::exists("fonts.dat") && !_searchManager->hasFile("fonts.dat")) {
+				!Common::File::exists(Common::Path(liberationFontName)) && !_searchManager->hasFile(Common::Path(liberationFontName)) &&
+				!Common::File::exists("fonts.dat") && !_searchManager->hasFile("fonts.dat")) {
 				foundAllFonts = false;
 				break;
 			}
 		}
+
 		if (!foundAllFonts)
 			break;
 	}
+
 	if (!foundAllFonts) {
 		GUI::MessageDialog dialog(_(
-		                              "Before playing this game, you'll need to copy the required "
-		                              "fonts into ScummVM's extras directory, or into the game directory. "
-		                              "On Windows, you'll need the following font files from the Windows "
-		                              "font directory: Times New Roman, Century Schoolbook, Garamond, "
-		                              "Courier New and Arial. Alternatively, you can download the "
-		                              "Liberation Fonts package. You'll need all the fonts from the "
-		                              "font package you choose, i.e., LiberationMono, LiberationSans "
-		                              "and LiberationSerif."
-		                          ));
+				"Before playing this game, you'll need to copy the required "
+				"fonts into ScummVM's extras directory, or into the game directory. "
+				"On Windows, you'll need the following font files from the Windows "
+				"font directory: Times New Roman, Century Schoolbook, Garamond, "
+				"Courier New and Arial. Alternatively, you can download the "
+				"Liberation Fonts package. You'll need all the fonts from the "
+				"font package you choose, i.e., LiberationMono, LiberationSans "
+				"and LiberationSerif."
+		));
 		dialog.runModal();
 		quitGame();
 		return Common::kUnknownError;
@@ -361,20 +371,24 @@ Common::Error ZVision::run() {
 		debug(5, "Render");
 		// Render the backBuffer to the screen
 		_renderManager->prepareBackground();
-		if (_renderManager->renderSceneToScreen())
+		if (_renderManager->renderSceneToScreen()) {
 			_renderedFrameCount++;
-		else
+		} else {
 			_frameRenderDelay--;
+		}
 	}
+
 	return Common::kNoError;
 }
 
 void ZVision::pauseEngineIntern(bool pause) {
 	_mixer->pauseAll(pause);
-	if (pause)
+
+	if (pause) {
 		_clock.stop();
-	else
+	} else {
 		_clock.start();
+	}
 }
 
 void ZVision::setRenderDelay(uint delay) {
@@ -388,6 +402,7 @@ bool ZVision::canRender() {
 
 void ZVision::syncSoundSettings() {
 	Engine::syncSoundSettings();
+
 	_scriptManager->setStateValue(StateKey_Subtitles, ConfMan.getBool("subtitles") ? 1 : 0);
 }
 
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index a34a515074c..9ed9d9e6bd2 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -114,8 +114,10 @@ static const ScreenLayout zgiLayout {
 };
 //*/
 enum {
+
 	ROTATION_SCREEN_EDGE_OFFSET = 60,
 	MAX_ROTATION_SPEED = 400, // Pixels per second
+
 	KEYBUF_SIZE = 20
 };
 
@@ -131,6 +133,7 @@ enum ZVisionAction {
 	kZVisionActionPreferences,
 	kZVisionActionShowFPS,
 	kZVisionActionSkipCutscene,
+
 	kZVisionActionCount
 };
 
@@ -144,27 +147,13 @@ public:
 	~ZVision() override;
 
 public:
-	/**
-	 * A Rectangle centered inside the game window. All in-game coordinates
-	 * are given in this coordinate space. Also, all images are clipped to the
-	 * edges of this Rectangle
-	 */
-//	Common::Rect _workingArea;
-	/**
-	 * A Rectangle in which the menu will be rendered.
-	 * In the original game, this is always separate from the working window,
-	 * and thus may be rendered completely independently.
-	 * In the widescreen mod, this window may intersect the working window,
-	 * and thus must be composited and rendered within renderSceneToScreen().
-	 */
-//	Common::Rect _menuArea;
-//	Common::Rect _textArea;
 	const Graphics::PixelFormat _resourcePixelFormat;
 	const Graphics::PixelFormat _screenPixelFormat;
 
 private:
 	const ZVisionGameDescription *_gameDescription;
 
+
 	// We need random numbers
 	Common::RandomSource *_rnd;
 
@@ -276,7 +265,7 @@ public:
 	 *
 	 * @param videoDecoder    The video to play
 	 * @param destRect        Where to put the video. (In working window coords)
-	 * @param clipRect        What subset of video to blit to destRect (In video frame coords)  //TODO implement
+	 * @param srcRect         What subset of video to blit to destRect (In video frame coords)  //TODO implement
 	 * @param skippable       If true, the video can be skipped at any time using [Spacebar]
 	 */
 	void playVideo(Video::VideoDecoder &videoDecoder, const Common::Rect &destRect = Common::Rect(0, 0, 0, 0), bool skippable = true, uint16 sub = 0, const Common::Rect &srcRect = Common::Rect(0, 0, 0, 0));


Commit: f71aeba9722831e3352b8e6f5d5771bdd89f8ac5
    https://github.com/scummvm/scummvm/commit/f71aeba9722831e3352b8e6f5d5771bdd89f8ac5
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:59+02:00

Commit Message:
ZVISION: Code formatting & convention compliance:
Converted focus_list.h inclusion macro definition to all upper case & prefixed with engine name.

Changed paths:
    engines/zvision/common/focus_list.h


diff --git a/engines/zvision/common/focus_list.h b/engines/zvision/common/focus_list.h
index 3ea6955103b..bc698b95f73 100644
--- a/engines/zvision/common/focus_list.h
+++ b/engines/zvision/common/focus_list.h
@@ -19,8 +19,8 @@
  *
  */
 
-#ifndef focus_list_H
-#define focus_list_H
+#ifndef ZVISION_FOCUS_LIST_H
+#define ZVISION_FOCUS_LIST_H
 
 #include "common/array.h"
 


Commit: 3ebd8c2b7d27a6b287fd9d7260da1f6d08e6f1df
    https://github.com/scummvm/scummvm/commit/3ebd8c2b7d27a6b287fd9d7260da1f6d08e6f1df
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:59+02:00

Commit Message:
ZVISION: Add fix for script bug in room tl9e.
Animation coordinates & frames were incorrect.

Changed paths:
    engines/zvision/scripting/actions.cpp


diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index 5c047a59c28..4b42ed81ea7 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -765,6 +765,29 @@ ActionPlayPreloadAnimation::ActionPlayPreloadAnimation(ZVision *engine, int32 sl
 	sscanf(line.c_str(),
 	       "%u %u %u %u %u %u %u %u",
 	       &_controlKey, &_x1, &_y1, &_x2, &_y2, &_startFrame, &_endFrame, &_loopCount);
+	       
+	// WORKAROUND for script bug in Zork Nemesis, room tl9e
+	// Original script gives wrong coordinates & frames
+	if (engine->getGameId() == GID_NEMESIS)
+		switch (_slotKey) {
+			case 1282:
+				_x1 = 146;
+				_y1 = 142;
+				_x2 = 298;
+				_y2 = 236;
+				_startFrame = 16;
+				_endFrame = 31;
+				break;
+			case 1289:
+				_x1 = 146;
+				_y1 = 142;
+				_x2 = 298;
+				_y2 = 236;
+				_endFrame = 15;
+				break;
+			default:
+				break;
+		}
 }
 
 bool ActionPlayPreloadAnimation::execute() {


Commit: e1bdf680b27e9b7aed0b72b10614e5f63bf9a651
    https://github.com/scummvm/scummvm/commit/e1bdf680b27e9b7aed0b72b10614e5f63bf9a651
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:59+02:00

Commit Message:
ZVISION: Add usage documentation for FocusList and Scroller.

Changed paths:
    engines/zvision/common/focus_list.h
    engines/zvision/common/scroller.h


diff --git a/engines/zvision/common/focus_list.h b/engines/zvision/common/focus_list.h
index bc698b95f73..e5d038682c9 100644
--- a/engines/zvision/common/focus_list.h
+++ b/engines/zvision/common/focus_list.h
@@ -24,12 +24,28 @@
 
 #include "common/array.h"
 
+/**
+ * FILO list of unique members
+ * 
+ * Tracks redraw order of layered graphical elements.
+ * When an element has current focus, it is reshuffled to the top of the pile.
+ * When redrawing, start with last (bottom) element of list and finish with first (top)
+ * Used to: 
+ *	ensure scrolling menus are drawn in the order in which they last had mouse focus.
+ * 	ensure most recently updated subtitle is drawn atop all others.
+ * Provides limited Common::Array functionality
+ */
+
 template<typename T>
 class FocusList {
 private:
 	Common::Array<T> _focus;
 	typedef uint SizeType;  //TODO - find a way to make this typedef inherit from the definition in Common::Array
 public:
+/**
+ * Move unique entry to front of list; add to list if not already present.
+ * Sequence of all remaining members remains unchanged.
+ */
 	void set(T currentFocus) {
 		if (!_focus.size())
 			_focus.push_back(currentFocus);
@@ -71,6 +87,10 @@ public:
 		_focus.clear();
 	}
 
+/**
+ * Remove unique entry, if present.
+ * Sequence of all remaining members remains unchanged.
+ */
 	void remove(T value) {
 		if (_focus.size()) {
 			Common::Array<T> buffer;
diff --git a/engines/zvision/common/scroller.h b/engines/zvision/common/scroller.h
index f645692e0d2..bda8d0d341c 100644
--- a/engines/zvision/common/scroller.h
+++ b/engines/zvision/common/scroller.h
@@ -27,13 +27,21 @@
 
 namespace ZVision {
 
+/**
+ * Automatically scroll a GUI menu or similar graphical element between an active and an idle position
+ * Movement in one dimension; idle & active positions specified as int16.
+ * Movement is at constant speed determined by period, specified in ms.
+ * If active/idle status is changed mid-transition, will scroll from current position to the appropriate position.
+ * LinearScroller also be used to reversibly scroll animation frames.
+ */
+
 class LinearScroller {
 public:
 	LinearScroller(const int16 activePos, const int16 idlePos, const int16 period = 500);
 	~LinearScroller();
-	void reset();
-	bool update(uint32 deltatime);  //Calculate updated position of scrolled graphics; return true if redraw is necessary.
-	void setActive(bool active);
+	void reset();  ///< Set idle and immediately jump to idle position
+	bool update(uint32 deltatime);  ///< Calculate updated position of scrolled graphics; return true if redraw is necessary.
+	void setActive(bool active);	  ///< Set active or idle & scroll at set speed from current position to that position.
 	bool isMoving();
 	int16 getPos();
 
@@ -49,13 +57,20 @@ private:
 	const int16 _period;
 };
 
+/**
+ * Automatically scroll a GUI menu or similar graphical element between an active and an idle position
+ * Movement in two dimensions; idle & active positions specified as Common::Point
+ * Movement is at constant speed determined by period, specified in ms.
+ * If active/idle status is changed mid-transition, will scroll from current position to the appropriate position.
+ */
+
 class Scroller {
 public:
 	Scroller(const Common::Point &activePos, const Common::Point &idlePos, const int16 period = 500);
 	~Scroller();
-	void reset();
-	bool update(uint32 deltatime);  //Calculate updated position of scrolled graphics; return true if redraw is necessary.
-	void setActive(bool active);
+	void reset();  ///< Set idle and immediately jump to idle position
+	bool update(uint32 deltatime);  ///< Calculate updated position of scrolled graphics; return true if redraw is necessary.
+	void setActive(bool active);  ///< Set active or idle & scroll at set speed from current position to that position.
 	bool isMoving();
 	
 	Common::Point _pos;


Commit: eff73d2b29eab07308d121977881f844601dca31
    https://github.com/scummvm/scummvm/commit/eff73d2b29eab07308d121977881f844601dca31
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:59+02:00

Commit Message:
ZVISION: Convert FocusList to subclass of Common::Array

Changed paths:
    engines/zvision/common/focus_list.h
    engines/zvision/text/subtitle_manager.cpp


diff --git a/engines/zvision/common/focus_list.h b/engines/zvision/common/focus_list.h
index e5d038682c9..6e9b48e236c 100644
--- a/engines/zvision/common/focus_list.h
+++ b/engines/zvision/common/focus_list.h
@@ -24,8 +24,10 @@
 
 #include "common/array.h"
 
+namespace ZVision {
+
 /**
- * FILO list of unique members
+ * FILO array of unique members
  * 
  * Tracks redraw order of layered graphical elements.
  * When an element has current focus, it is reshuffled to the top of the pile.
@@ -33,74 +35,51 @@
  * Used to: 
  *	ensure scrolling menus are drawn in the order in which they last had mouse focus.
  * 	ensure most recently updated subtitle is drawn atop all others.
- * Provides limited Common::Array functionality
  */
 
-template<typename T>
-class FocusList {
+template<class T>
+class FocusList : public Common::Array<T> {
 private:
-	Common::Array<T> _focus;
-	typedef uint SizeType;  //TODO - find a way to make this typedef inherit from the definition in Common::Array
+	typedef uint size_type;
 public:
 /**
  * Move unique entry to front of list; add to list if not already present.
  * Sequence of all remaining members remains unchanged.
  */
-	void set(T currentFocus) {
-		if (!_focus.size())
-			_focus.push_back(currentFocus);
+	void set(const T currentFocus) {
+		if (!this->size())
+			this->push_back(currentFocus);
 		else {
-			if (_focus.front() != currentFocus) {
+			if (this->front() != currentFocus) {
 				Common::Array<T> buffer;
-				while (_focus.size() > 0) {
-					if (_focus.back() != currentFocus)
-						buffer.push_back(_focus.back());
-					_focus.pop_back();
+				while (this->size() > 0) {
+					if (this->back() != currentFocus)
+						buffer.push_back(this->back());
+					this->pop_back();
 				}
-				_focus.push_back(currentFocus);
+				this->push_back(currentFocus);
 				while (buffer.size() > 0) {
-					_focus.push_back(buffer.back());
+					this->push_back(buffer.back());
 					buffer.pop_back();
 				}
 			}
 		}
 	}
 
-	T get(SizeType idx = 0) {
-		return _focus[idx];
-	}
-
-	T front() {
-		return _focus.front();
-	}
-
-	T &operator[](SizeType idx) {
-		assert(idx < _focus.size());
-		return _focus[idx];
-	}
-
-	SizeType size() {
-		return _focus.size();
-	}
-
-	void clear() {
-		_focus.clear();
-	}
-
 /**
  * Remove unique entry, if present.
  * Sequence of all remaining members remains unchanged.
  */
-	void remove(T value) {
-		if (_focus.size()) {
+	void remove(const T value) {
+		if (this->size()) {
 			Common::Array<T> buffer;
-			while (_focus.size() > 0) {
-				if (_focus.back() != value)
-					buffer.push_back(_focus.back());
-				_focus.pop_back();
+			while (this->size() > 0) {
+				if (this->back() != value)
+					buffer.push_back(this->back());
+				this->pop_back();
 			}
 			while (buffer.size() > 0) {
-				_focus.push_back(buffer.back());
+				this->push_back(buffer.back());
 				buffer.pop_back();
 			}
 		}
@@ -108,4 +87,6 @@ public:
 
 };
 
+}  // End of namespace ZVision
+
 #endif
diff --git a/engines/zvision/text/subtitle_manager.cpp b/engines/zvision/text/subtitle_manager.cpp
index 88ced580c95..4a7dc96e905 100644
--- a/engines/zvision/text/subtitle_manager.cpp
+++ b/engines/zvision/text/subtitle_manager.cpp
@@ -75,7 +75,7 @@ void SubtitleManager::process(int32 deltatime) {
 		_renderManager->clearTextSurface();
 		//Render just the most recent subtitle
 		if (_subsFocus.size()) {
-			uint16 curSub = _subsFocus.get();
+			uint16 curSub = _subsFocus.front();
 			debug(4, "Rendering subtitle %d", curSub);
 			Subtitle *sub = _subsList[curSub];
 			if (sub->_lineId >= 0) {


Commit: 518cd2982d76dda527361d12ad3b9e962f8bd766
    https://github.com/scummvm/scummvm/commit/518cd2982d76dda527361d12ad3b9e962f8bd766
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:53:59+02:00

Commit Message:
ZVISION: Append self to credits.pl

Changed paths:
    engines/zvision/credits.pl


diff --git a/engines/zvision/credits.pl b/engines/zvision/credits.pl
index d5a756d6414..ce43e25c4c9 100644
--- a/engines/zvision/credits.pl
+++ b/engines/zvision/credits.pl
@@ -2,4 +2,5 @@ begin_section("Z-Vision");
 	add_person("Adrian Astley", "RichieSams", "");
 	add_person("Filippos Karapetis", "bluegr", "");
 	add_person("Anton Yarcev", "Zidane", "");
+	add_person("Thomas N McEwan", "tnm23", "Widescreen mod, HQ panoramas, 3D audio enhancement");
 end_section();


Commit: 31297741b4781e6181a606d286fb78a1942185f6
    https://github.com/scummvm/scummvm/commit/31297741b4781e6181a606d286fb78a1942185f6
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:00+02:00

Commit Message:
ZVISION: Simple formatting fixes for code review.

Changed paths:
    engines/zvision/common/scroller.cpp
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/scripting/effects/music_effect.cpp


diff --git a/engines/zvision/common/scroller.cpp b/engines/zvision/common/scroller.cpp
index 871571e3e8b..c242ffb9a62 100644
--- a/engines/zvision/common/scroller.cpp
+++ b/engines/zvision/common/scroller.cpp
@@ -96,7 +96,7 @@ Scroller::~Scroller() {
 void Scroller::reset() {
 	_xScroller.reset();
 	_yScroller.reset();
-};
+}
 
 
 void Scroller::setActive(bool active) {
diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 5f8b8d131ed..962a1c4aa18 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -254,8 +254,8 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
 		} else {
 			debug(2, "Skipping screen update; engine forbids rendering at this time.");
 			return false;
-		};
-	};
+		}
+	}
 }
 
 Graphics::ManagedSurface &RenderManager::getVidSurface(Common::Rect &dstRect) {
@@ -437,12 +437,12 @@ void RenderManager::setBackgroundImage(const Common::Path &fileName) {
 
 void RenderManager::setBackgroundPosition(int offset) {
 	switch (_renderTable.getRenderState()) {
-	case RenderTable::PANORAMA :
-	case RenderTable::TILT :
+	case RenderTable::PANORAMA:
+	case RenderTable::TILT:
 		if (_backgroundOffset != offset)
 			_backgroundDirtyRect = Common::Rect(_backgroundWidth, _backgroundHeight);
 		break;
-	default :
+	default:
 		break;
 	}
 	_backgroundOffset = offset;
@@ -452,10 +452,10 @@ void RenderManager::setBackgroundPosition(int offset) {
 
 uint32 RenderManager::getCurrentBackgroundOffset() {
 	switch (_renderTable.getRenderState()) {
-	case RenderTable::PANORAMA :
-	case RenderTable::TILT :
+	case RenderTable::PANORAMA:
+	case RenderTable::TILT:
 		return _backgroundOffset;
-	default :
+	default:
 		return 0;
 	}
 }
@@ -1048,12 +1048,12 @@ void RenderManager::updateRotation() {
 	int16 _velocity = _engine->getMouseVelocity() + _engine->getKeyboardVelocity();
 	ScriptManager *scriptManager = _engine->getScriptManager();
 
-	if (_doubleFPS | !_frameLimiter.isEnabled()) //Assuming 60fps when in Vsync mode.
+	if (_doubleFPS || !_frameLimiter.isEnabled()) //Assuming 60fps when in Vsync mode.
 		_velocity /= 2;
 
 	if (_velocity) {
 		switch (_renderTable.getRenderState()) {
-		case RenderTable::PANORAMA : {
+		case RenderTable::PANORAMA: {
 			int16 startPosition = scriptManager->getStateValue(StateKey_ViewPos);
 
 			int16 newPosition = startPosition + (_renderTable.getPanoramaReverse() ? -_velocity : _velocity);
@@ -1074,7 +1074,7 @@ void RenderManager::updateRotation() {
 			setBackgroundPosition(newPosition);
 			break;
 		}
-		case RenderTable::TILT : {
+		case RenderTable::TILT: {
 			int16 startPosition = scriptManager->getStateValue(StateKey_ViewPos);
 
 			int16 newPosition = startPosition + _velocity;
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index d850e9f73f6..7e504cce819 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -215,7 +215,7 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 		if (!_staticScreen)
 			//Original game scripted behaviour
 			switch (_engine->getRenderManager()->getRenderTable()->getRenderState()) {
-			case RenderTable::PANORAMA :
+			case RenderTable::PANORAMA:
 				debug(3, "PanTrackNode in panorama mode");
 				_width = _engine->getRenderManager()->getBkgSize().x;
 				if (_width) {
@@ -227,9 +227,9 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 					//_viewPos.setDegrees(0);
 				}
 				break;
-			case RenderTable::FLAT :
-			case RenderTable::TILT :
-			default :
+			case RenderTable::FLAT:
+			case RenderTable::TILT:
+			default:
 				debug(3, "PanTrackNode in FLAT/TILT mode");
 				_sourcePos.setDegrees(0);
 				_viewPos.setDegrees(0);


Commit: b475d9ed6561aa4420396ae34c2eec285017e7db
    https://github.com/scummvm/scummvm/commit/b475d9ed6561aa4420396ae34c2eec285017e7db
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:00+02:00

Commit Message:
ZVISION: Corrected non-member variable names to meet coding convention.

Changed paths:
    engines/zvision/core/events.cpp
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/video/video.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/core/events.cpp b/engines/zvision/core/events.cpp
index 714d24f8c26..ff5705353ff 100644
--- a/engines/zvision/core/events.cpp
+++ b/engines/zvision/core/events.cpp
@@ -288,7 +288,7 @@ void ZVision::onMouseMove(const Common::Point &pos) {
 	debug(6, "ZVision::onMouseMove()");
 	_menu->onMouseMove(pos);
 	Common::Point imageCoord(_renderManager->screenSpaceToImageSpace(pos));
-	Common::Rect _workingArea = _renderManager->getWorkingArea();
+	Common::Rect workingArea = _renderManager->getWorkingArea();
 	bool cursorWasChanged = false;
 
 	// Graph of the function governing rotation velocity:
@@ -322,44 +322,44 @@ void ZVision::onMouseMove(const Common::Point &pos) {
 	//               ^
 
 	// Clip the horizontal mouse position to the working window
-	debug(6, "Mouse pos.x, %d, clipping with %d+1, %d+1", pos.x, _workingArea.left, _workingArea.right);
+	debug(6, "Mouse pos.x, %d, clipping with %d+1, %d+1", pos.x, workingArea.left, workingArea.right);
 	Common::Point clippedPos = pos;
-	clippedPos.x = CLIP<int16>(pos.x, _workingArea.left + 1, _workingArea.right - 1);
-	if (_workingArea.contains(clippedPos) && !_menu->inMenu()) {
+	clippedPos.x = CLIP<int16>(pos.x, workingArea.left + 1, workingArea.right - 1);
+	if (workingArea.contains(clippedPos) && !_menu->inMenu()) {
 		cursorWasChanged = _scriptManager->onMouseMove(clippedPos, imageCoord);
 		RenderTable::RenderState renderState = _renderManager->getRenderTable()->getRenderState();
 		switch (renderState) {
 		case RenderTable::PANORAMA:
-			if (clippedPos.x >= _workingArea.left && clippedPos.x < _workingArea.left + ROTATION_SCREEN_EDGE_OFFSET) {
+			if (clippedPos.x >= workingArea.left && clippedPos.x < workingArea.left + ROTATION_SCREEN_EDGE_OFFSET) {
 				int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
 				if (mspeed <= 0)
 					mspeed = 25;
-				_mouseVelocity  = MIN(((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (clippedPos.x - _workingArea.left)) - mspeed).toInt(), -1);
+				_mouseVelocity  = MIN(((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (clippedPos.x - workingArea.left)) - mspeed).toInt(), -1);
 				_cursorManager->changeCursor(CursorIndex_Left);
 				cursorWasChanged = true;
-			} else if (clippedPos.x <= _workingArea.right && clippedPos.x > _workingArea.right - ROTATION_SCREEN_EDGE_OFFSET) {
+			} else if (clippedPos.x <= workingArea.right && clippedPos.x > workingArea.right - ROTATION_SCREEN_EDGE_OFFSET) {
 				int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
 				if (mspeed <= 0)
 					mspeed = 25;
-				_mouseVelocity  = MAX((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (clippedPos.x - _workingArea.right + ROTATION_SCREEN_EDGE_OFFSET)).toInt(), 1);
+				_mouseVelocity  = MAX((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (clippedPos.x - workingArea.right + ROTATION_SCREEN_EDGE_OFFSET)).toInt(), 1);
 				_cursorManager->changeCursor(CursorIndex_Right);
 				cursorWasChanged = true;
 			} else
 				_mouseVelocity = 0;
 			break;
 		case RenderTable::TILT:
-			if (clippedPos.y >= _workingArea.top && clippedPos.y < _workingArea.top + ROTATION_SCREEN_EDGE_OFFSET) {
+			if (clippedPos.y >= workingArea.top && clippedPos.y < workingArea.top + ROTATION_SCREEN_EDGE_OFFSET) {
 				int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
 				if (mspeed <= 0)
 					mspeed = 25;
-				_mouseVelocity  = MIN(((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (pos.y - _workingArea.top)) - mspeed).toInt(), -1);
+				_mouseVelocity  = MIN(((Common::Rational(mspeed, ROTATION_SCREEN_EDGE_OFFSET) * (pos.y - workingArea.top)) - mspeed).toInt(), -1);
 				_cursorManager->changeCursor(CursorIndex_UpArr);
 				cursorWasChanged = true;
-			} else if (clippedPos.y <= _workingArea.bottom && clippedPos.y > _workingArea.bottom - ROTATION_SCREEN_EDGE_OFFSET) {
+			} else if (clippedPos.y <= workingArea.bottom && clippedPos.y > workingArea.bottom - ROTATION_SCREEN_EDGE_OFFSET) {
 				int16 mspeed = _scriptManager->getStateValue(StateKey_RotateSpeed) >> 4;
 				if (mspeed <= 0)
 					mspeed = 25;
-				_mouseVelocity = MAX((Common::Rational(MAX_ROTATION_SPEED, ROTATION_SCREEN_EDGE_OFFSET) * (pos.y - _workingArea.bottom + ROTATION_SCREEN_EDGE_OFFSET)).toInt(), 1);
+				_mouseVelocity = MAX((Common::Rational(MAX_ROTATION_SPEED, ROTATION_SCREEN_EDGE_OFFSET) * (pos.y - workingArea.bottom + ROTATION_SCREEN_EDGE_OFFSET)).toInt(), 1);
 				_cursorManager->changeCursor(CursorIndex_DownArr);
 				cursorWasChanged = true;
 			} else
diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 962a1c4aa18..aa9f1e4f4fe 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -258,11 +258,10 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
 	}
 }
 
-Graphics::ManagedSurface &RenderManager::getVidSurface(Common::Rect &dstRect) {
-	Common::Rect _dstRect = dstRect;
-	_dstRect.translate(_workingArea.left, _workingArea.top);  //Convert to screen coordinates
-	_vidManagedSurface.create(_screen, _dstRect);
-	debug(1, "Obtaining managed video surface at %d,%d,%d,%d", _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
+Graphics::ManagedSurface &RenderManager::getVidSurface(Common::Rect dstRect) {
+	dstRect.translate(_workingArea.left, _workingArea.top);  //Convert to screen coordinates
+	_vidManagedSurface.create(_screen, dstRect);
+	debug(1, "Obtaining managed video surface at %d,%d,%d,%d", dstRect.left, dstRect.top, dstRect.right, dstRect.bottom);
 	return _vidManagedSurface;
 }
 
@@ -507,9 +506,8 @@ void RenderManager::scaleBuffer(const void *src, void *dst, uint32 srcWidth, uin
 
 //ORIGINAL FUNCTION
 //*
-void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect, Graphics::Surface &dst, int _x, int _y) {
+void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, Common::Rect srcRect, Graphics::Surface &dst, int _x, int _y) {
 	debug(9, "blitSurfaceToSurface");
-	Common::Rect srcRect = _srcRect;
 	Common::Point dstPos = Common::Point(_x, _y);
 	//Default to using whole source surface
 	if (srcRect.isEmpty())
@@ -580,8 +578,8 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Com
 
 //SIMPLIFIED FUNCTION
 //TODO - find bug that breaks panorama rotation.  Suspect problem with negative arguments of some sort.
-void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect , Graphics::Surface &dst, int _x, int _y) {
-    Common::Rect srcRect = _srcRect;
+void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, Common::Rect srcRect , Graphics::Surface &dst, int _x, int _y) {
+    Common::Rect srcRect = srcRect;
     Common::Point dstPos = Common::Point(_x,_y);
     //Default to using whole source surface
     if (srcRect.isEmpty())
@@ -615,9 +613,8 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Com
 }
 //*/
 
-void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect , Graphics::Surface &dst, int _x, int _y, uint32 colorkey) {
+void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, Common::Rect srcRect , Graphics::Surface &dst, int _x, int _y, uint32 colorkey) {
 	debug(9, "blitSurfaceToSurface");
-	Common::Rect srcRect = _srcRect;
 	if (srcRect.isEmpty())
 		srcRect = Common::Rect(src.w, src.h);
 	srcRect.clip(src.w, src.h);
@@ -666,14 +663,14 @@ void RenderManager::blitSurfaceToBkg(const Graphics::Surface &src, int x, int y,
 		_backgroundDirtyRect.extend(dirty);
 }
 
-void RenderManager::blitSurfaceToBkgScaled(const Graphics::Surface &src, const Common::Rect &_dstRect, int32 colorkey) {
-	if (src.w == _dstRect.width() && src.h == _dstRect.height()) {
-		blitSurfaceToBkg(src, _dstRect.left, _dstRect.top, colorkey);
+void RenderManager::blitSurfaceToBkgScaled(const Graphics::Surface &src, const Common::Rect &dstRect, int32 colorkey) {
+	if (src.w == dstRect.width() && src.h == dstRect.height()) {
+		blitSurfaceToBkg(src, dstRect.left, dstRect.top, colorkey);
 	} else {
 		Graphics::Surface *tmp = new Graphics::Surface;
-		tmp->create(_dstRect.width(), _dstRect.height(), src.format);
-		scaleBuffer(src.getPixels(), tmp->getPixels(), src.w, src.h, src.format.bytesPerPixel, _dstRect.width(), _dstRect.height());
-		blitSurfaceToBkg(*tmp, _dstRect.left, _dstRect.top, colorkey);
+		tmp->create(dstRect.width(), dstRect.height(), src.format);
+		scaleBuffer(src.getPixels(), tmp->getPixels(), src.w, src.h, src.format.bytesPerPixel, dstRect.width(), dstRect.height());
+		blitSurfaceToBkg(*tmp, dstRect.left, dstRect.top, colorkey);
 		tmp->free();
 		delete tmp;
 	}
@@ -1045,18 +1042,18 @@ void RenderManager::bkgFill(uint8 r, uint8 g, uint8 b) {
 
 
 void RenderManager::updateRotation() {
-	int16 _velocity = _engine->getMouseVelocity() + _engine->getKeyboardVelocity();
+	int16 velocity = _engine->getMouseVelocity() + _engine->getKeyboardVelocity();
 	ScriptManager *scriptManager = _engine->getScriptManager();
 
 	if (_doubleFPS || !_frameLimiter.isEnabled()) //Assuming 60fps when in Vsync mode.
-		_velocity /= 2;
+		velocity /= 2;
 
-	if (_velocity) {
+	if (velocity) {
 		switch (_renderTable.getRenderState()) {
 		case RenderTable::PANORAMA: {
 			int16 startPosition = scriptManager->getStateValue(StateKey_ViewPos);
 
-			int16 newPosition = startPosition + (_renderTable.getPanoramaReverse() ? -_velocity : _velocity);
+			int16 newPosition = startPosition + (_renderTable.getPanoramaReverse() ? -velocity : velocity);
 
 			int16 zeroPoint = _renderTable.getPanoramaZeroPoint();
 			if (startPosition >= zeroPoint && newPosition < zeroPoint)
@@ -1077,7 +1074,7 @@ void RenderManager::updateRotation() {
 		case RenderTable::TILT: {
 			int16 startPosition = scriptManager->getStateValue(StateKey_ViewPos);
 
-			int16 newPosition = startPosition + _velocity;
+			int16 newPosition = startPosition + velocity;
 
 			int16 screenHeight = getBkgSize().y;
 			int16 tiltGap = (int16)_renderTable.getTiltGap();
@@ -1189,13 +1186,13 @@ void RenderManager::rotateTo(int16 _toPos, int16 _time) {
 }
 
 void RenderManager::upscaleRect(Common::Rect &rect) {
-	Common::Rect _HDscreen = _widescreen ? _HDscreenAreaWide : _HDscreenArea;
-	Common::Rect _SDscreen = _widescreen ? _layout.workingArea : _layout.screenArea;
-	_SDscreen.moveTo(0, 0);
-	rect.top = rect.top * _HDscreen.height() / _SDscreen.height();
-	rect.left = rect.left * _HDscreen.width() / _SDscreen.width();
-	rect.bottom = rect.bottom * _HDscreen.height() / _SDscreen.height();
-	rect.right = rect.right * _HDscreen.width() / _SDscreen.width();
+	Common::Rect HDscreen = _widescreen ? _HDscreenAreaWide : _HDscreenArea;
+	Common::Rect SDscreen = _widescreen ? _layout.workingArea : _layout.screenArea;
+	SDscreen.moveTo(0, 0);
+	rect.top = rect.top * HDscreen.height() / SDscreen.height();
+	rect.left = rect.left * HDscreen.width() / SDscreen.width();
+	rect.bottom = rect.bottom * HDscreen.height() / SDscreen.height();
+	rect.right = rect.right * HDscreen.width() / SDscreen.width();
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index ca0135972b5..6b0e833a494 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -172,7 +172,7 @@ public:
 	 */
 	bool renderSceneToScreen(bool immediate = false, bool overlayOnly = false, bool preStream = false);
 
-	Graphics::ManagedSurface &getVidSurface(Common::Rect &dstRect);  //dstRect is defined relative to working area origin
+	Graphics::ManagedSurface &getVidSurface(Common::Rect dstRect);  //dstRect is defined relative to working area origin
 
 	Common::Rect getMenuArea() {
 		return _menuArea;
@@ -263,20 +263,20 @@ public:
 	 * Blit from one surface to another surface
 	 *
 	 * @param src       Source surface
-	 * @param _srcRect  Rectangle defining area of source surface to blit; if this rectangle is empty, entire source surface is blitted
+	 * @param srcRect  Rectangle defining area of source surface to blit; if this rectangle is empty, entire source surface is blitted
 	 * @param dst       Destination surface
 	 * @param x         Destination surface x coordinate
 	 * @param y         Destination surface y coordinate
 	 */
 
-	void blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect, Graphics::Surface &dst, int _x, int _y);
-	void blitSurfaceToSurface(const Graphics::Surface &src, const Common::Rect &_srcRect, Graphics::Surface &dst, int _x, int _y, uint32 colorkey);
+	void blitSurfaceToSurface(const Graphics::Surface &src, Common::Rect srcRect, Graphics::Surface &dst, int _x, int _y);
+	void blitSurfaceToSurface(const Graphics::Surface &src, Common::Rect srcRect, Graphics::Surface &dst, int _x, int _y, uint32 colorkey);
 
 	// Blitting surface-to-background methods
 	void blitSurfaceToBkg(const Graphics::Surface &src, int x, int y, int32 colorkey = -1);
 
 	// Blitting surface-to-background methods with scale
-	void blitSurfaceToBkgScaled(const Graphics::Surface &src, const Common::Rect &_dstRect, int32 colorkey = -1);
+	void blitSurfaceToBkgScaled(const Graphics::Surface &src, const Common::Rect &dstRect, int32 colorkey = -1);
 
 	/**
 	 * Blit from source surface to menu area
diff --git a/engines/zvision/video/video.cpp b/engines/zvision/video/video.cpp
index f82254a03b9..f06913ac165 100644
--- a/engines/zvision/video/video.cpp
+++ b/engines/zvision/video/video.cpp
@@ -83,39 +83,37 @@ Video::VideoDecoder *ZVision::loadAnimation(const Common::Path &fileName) {
  * @param srcRect   Rectangle within video frame, defined relative to frame origin, to blit to output.  Only used for removing baked-in letterboxing in ZGI DVD HD videos
  */
 
-void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, bool skippable, uint16 sub, const Common::Rect &srcRect) {
-	Common::Rect _dstRect = dstRect;
-	Common::Rect _srcRect = srcRect;
-	Common::Rect _frameArea = Common::Rect(vid.getWidth(), vid.getHeight());
-	Common::Rect _workingArea = _renderManager->getWorkingArea();
+void ZVision::playVideo(Video::VideoDecoder &vid, Common::Rect dstRect, bool skippable, uint16 sub, Common::Rect srcRect) {
+	Common::Rect frameArea = Common::Rect(vid.getWidth(), vid.getHeight());
+	Common::Rect workingArea = _renderManager->getWorkingArea();
 	// If dstRect is empty, no specific scaling was requested. However, we may choose to do scaling anyway
 	bool scaled = false;
-	_workingArea.moveTo(0, 0); //Set local origin system in this scope to origin of working area
+	workingArea.moveTo(0, 0); //Set local origin system in this scope to origin of working area
 
-	debug(1, "Playing video, source %d,%d,%d,%d, at destination %d,%d,%d,%d", _srcRect.left, _srcRect.top, _srcRect.right, _srcRect.bottom, _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
+	debug(1, "Playing video, source %d,%d,%d,%d, at destination %d,%d,%d,%d", srcRect.left, srcRect.top, srcRect.right, srcRect.bottom, dstRect.left, dstRect.top, dstRect.right, dstRect.bottom);
 
-	if (_dstRect.isEmpty())
-		_dstRect = _frameArea;
-	_dstRect.clip(_workingArea);
+	if (dstRect.isEmpty())
+		dstRect = frameArea;
+	dstRect.clip(workingArea);
 
-	debug(2, "Clipped dstRect = %d,%d,%d,%d", _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
+	debug(2, "Clipped dstRect = %d,%d,%d,%d", dstRect.left, dstRect.top, dstRect.right, dstRect.bottom);
 
-	if (_srcRect.isEmpty())
-		_srcRect = _frameArea;
+	if (srcRect.isEmpty())
+		srcRect = frameArea;
 	else
-		_srcRect.clip(_frameArea);
+		srcRect.clip(frameArea);
 
-	debug(2, "Clipped srcRect = %d,%d,%d,%d", _srcRect.left, _srcRect.top, _srcRect.right, _srcRect.bottom);
+	debug(2, "Clipped srcRect = %d,%d,%d,%d", srcRect.left, srcRect.top, srcRect.right, srcRect.bottom);
 
-	Graphics::ManagedSurface &outSurface = _renderManager->getVidSurface(_dstRect);
-	_dstRect.moveTo(0, 0);
-	_dstRect.clip(Common::Rect(outSurface.w, outSurface.h));
+	Graphics::ManagedSurface &outSurface = _renderManager->getVidSurface(dstRect);
+	dstRect.moveTo(0, 0);
+	dstRect.clip(Common::Rect(outSurface.w, outSurface.h));
 
-	debug(2, "dstRect clipped with outSurface = %d,%d,%d,%d", _dstRect.left, _dstRect.top, _dstRect.right, _dstRect.bottom);
+	debug(2, "dstRect clipped with outSurface = %d,%d,%d,%d", dstRect.left, dstRect.top, dstRect.right, dstRect.bottom);
 
-	debug(1, "Final size %d x %d, at working window coordinates %d, %d", _srcRect.width(), _srcRect.height(), _dstRect.left, _dstRect.top);
-	if (_srcRect.width() != _dstRect.width() || _srcRect.height() != _dstRect.height()) {
-		debug(1, "Video will be scaled from %dx%d to %dx%d", _srcRect.width(), _srcRect.height(), _dstRect.width(), _dstRect.height());
+	debug(1, "Final size %d x %d, at working window coordinates %d, %d", srcRect.width(), srcRect.height(), dstRect.left, dstRect.top);
+	if (srcRect.width() != dstRect.width() || srcRect.height() != dstRect.height()) {
+		debug(1, "Video will be scaled from %dx%d to %dx%d", srcRect.width(), srcRect.height(), dstRect.width(), dstRect.height());
 		scaled = true;
 	}
 
@@ -159,11 +157,11 @@ void ZVision::playVideo(Video::VideoDecoder &vid, const Common::Rect &dstRect, b
 			if (frame) {
 				_renderManager->renderSceneToScreen(true, true, true); //Redraw text area to clean background of subtitles for videos that don't fill entire working area, e.g, Nemesis sarcophagi
 				if (scaled) {
-					debug(8, "Scaled blit from area %d x %d to video output surface at output surface position %d, %d", _srcRect.width(), _srcRect.height(), _dstRect.left, _dstRect.top);
-					outSurface.blitFrom(*frame, _srcRect, _dstRect);
+					debug(8, "Scaled blit from area %d x %d to video output surface at output surface position %d, %d", srcRect.width(), srcRect.height(), dstRect.left, dstRect.top);
+					outSurface.blitFrom(*frame, srcRect, dstRect);
 				} else {
-					debug(8, "Simple blit from area %d x %d to video output surface at output surface position %d, %d", _srcRect.width(), _srcRect.height(), _dstRect.left, _dstRect.top);
-					outSurface.simpleBlitFrom(*frame, _srcRect, _dstRect.origin());
+					debug(8, "Simple blit from area %d x %d to video output surface at output surface position %d, %d", srcRect.width(), srcRect.height(), dstRect.left, dstRect.top);
+					outSurface.simpleBlitFrom(*frame, srcRect, dstRect.origin());
 				}
 				_subtitleManager->process(0);
 			}
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index 9ed9d9e6bd2..32fc54ef491 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -268,7 +268,7 @@ public:
 	 * @param srcRect         What subset of video to blit to destRect (In video frame coords)  //TODO implement
 	 * @param skippable       If true, the video can be skipped at any time using [Spacebar]
 	 */
-	void playVideo(Video::VideoDecoder &videoDecoder, const Common::Rect &destRect = Common::Rect(0, 0, 0, 0), bool skippable = true, uint16 sub = 0, const Common::Rect &srcRect = Common::Rect(0, 0, 0, 0));
+	void playVideo(Video::VideoDecoder &videoDecoder, Common::Rect destRect = Common::Rect(0, 0, 0, 0), bool skippable = true, uint16 sub = 0, Common::Rect srcRect = Common::Rect(0, 0, 0, 0));
 	Video::VideoDecoder *loadAnimation(const Common::Path &fileName);
 
 	void setRenderDelay(uint);


Commit: 822474fad4838dfbac6c5ad5462763b3c3a990eb
    https://github.com/scummvm/scummvm/commit/822474fad4838dfbac6c5ad5462763b3c3a990eb
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:00+02:00

Commit Message:
ZVISION: Removed spurious semicolons for code review.

Changed paths:
    engines/zvision/graphics/render_table.h
    engines/zvision/scripting/effects/music_effect.h


diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index bcbd2b058fa..fabd0403f64 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -40,7 +40,7 @@ public:
 
 //  bool _printDebug = false;
 
-	FilterPixel() {};
+	FilterPixel() {}
 //  FilterPixel(float x, float y, bool highQuality=false, bool printDebug=false) {
 	FilterPixel(float x, float y, bool highQuality = false) {
 		_Src.left = int16(floor(x));
@@ -72,16 +72,16 @@ public:
 			        debug(5,"\tNearest neighbour, _xDir: 0x%X, _yDir: 0x%X", _xDir, _yDir);
 			*/
 		}
-	};
-	~FilterPixel() {};
+	}
+	~FilterPixel() {}
 	inline void flipH() {
 		_Src.left = -_Src.left;
 		_Src.right = -_Src.right;
-	};
+	}
 	inline void flipV() {
 		_Src.top = -_Src.top;
 		_Src.bottom = -_Src.bottom;
-	};
+	}
 };
 
 class RenderTable {
@@ -119,11 +119,11 @@ private:
 		r = color & 0x001f;
 		g = color & 0x03e0;
 		b = color & 0x7c00;
-	};
+	}
 	inline uint16 mergeColor(uint32 &r, uint32 &g, uint32 &b) const {
 		//NB Red uses the lowest bits in RGB555 and so doesn't need its fractional bits masked away after averaging
 		return r | (g & 0x03e0) | (b & 0x7c00);
-	};
+	}
 
 
 	struct {
diff --git a/engines/zvision/scripting/effects/music_effect.h b/engines/zvision/scripting/effects/music_effect.h
index 5bb4fc067f5..18439919eee 100644
--- a/engines/zvision/scripting/effects/music_effect.h
+++ b/engines/zvision/scripting/effects/music_effect.h
@@ -51,7 +51,7 @@ public:
 	virtual void setVolume(uint8 volume) = 0;
 	uint8 getVolume() {
 		return _volume;
-	};
+	}
 	virtual void setFade(int32 time, uint8 target) = 0;
 	virtual void setBalance(int8 balance);  //NB Overrides effects of setDirection()
 	void setDirection(Math::Angle azimuth, uint8 magnitude = 255);  //NB Overrides effects of setBalance()


Commit: 0aa33df1246734de59b3eded8a70855f6009ce54
    https://github.com/scummvm/scummvm/commit/0aa33df1246734de59b3eded8a70855f6009ce54
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:00+02:00

Commit Message:
GRAPHICS: Code formatting compliance.

Changed paths:
    graphics/framelimiter.h


diff --git a/graphics/framelimiter.h b/graphics/framelimiter.h
index 589ef76122e..96bd29be2c5 100644
--- a/graphics/framelimiter.h
+++ b/graphics/framelimiter.h
@@ -66,7 +66,7 @@ public:
 	 */
 	uint getLastFrameDuration() const {
 		return _frameDuration;
-	};
+	}
 	/**
 	 * Return duration of last screen update
 	 * If Vsync is inactive, this value will just be the duration of the redraw process itself;
@@ -74,14 +74,14 @@ public:
 	 */
 	uint getLastDrawDuration() const {
 		return _drawDuration;
-	};
+	}
 	/**
 	 * Return duration of last game logic loop
 	 * Specifically, this is the time from when startFrame() was last called to when delayBeforeSwap() was last called
 	 */
 	uint getLastLoopDuration() const {
 		return _loopDuration;
-	};
+	}
 	/**
 	 * If true, framelimiter is active and applying _system->delayMillis(delay) to maintain the specified FPS, if valid.
 	 * If false, framelimiter is inactive, either because supplied FPS was invalid or because Vsync is active.
@@ -89,7 +89,7 @@ public:
 	 */
 	bool isEnabled() const {
 		return _enabled;
-	};
+	}
 
 private:
 	OSystem *_system;


Commit: 5d8be174465d6c1251300b0dce5b01c5d7cca8f9
    https://github.com/scummvm/scummvm/commit/5d8be174465d6c1251300b0dce5b01c5d7cca8f9
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:00+02:00

Commit Message:
ZVISION: Code formatting compliance.

Changed paths:
    engines/zvision/common/focus_list.h
    engines/zvision/scripting/actions.cpp


diff --git a/engines/zvision/common/focus_list.h b/engines/zvision/common/focus_list.h
index 6e9b48e236c..11cfb829ff9 100644
--- a/engines/zvision/common/focus_list.h
+++ b/engines/zvision/common/focus_list.h
@@ -33,8 +33,8 @@ namespace ZVision {
  * When an element has current focus, it is reshuffled to the top of the pile.
  * When redrawing, start with last (bottom) element of list and finish with first (top)
  * Used to: 
- *	ensure scrolling menus are drawn in the order in which they last had mouse focus.
- * 	ensure most recently updated subtitle is drawn atop all others.
+ *	- ensure scrolling menus are drawn in the order in which they last had mouse focus.
+ * 	- ensure most recently updated subtitle is drawn atop all others.
  */
 
 template<class T>
@@ -42,10 +42,10 @@ class FocusList : public Common::Array<T> {
 private:
 	typedef uint size_type;
 public:
-/**
- * Move unique entry to front of list; add to list if not already present.
- * Sequence of all remaining members remains unchanged.
- */
+	/**
+	 * Move unique entry to front of list; add to list if not already present.
+	 * Sequence of all remaining members remains unchanged.
+	 */
 	void set(const T currentFocus) {
 		if (!this->size())
 			this->push_back(currentFocus);
@@ -66,10 +66,10 @@ public:
 		}
 	}
 
-/**
- * Remove unique entry, if present.
- * Sequence of all remaining members remains unchanged.
- */
+	/**
+	 * Remove unique entry, if present.
+	 * Sequence of all remaining members remains unchanged.
+	 */
 	void remove(const T value) {
 		if (this->size()) {
 			Common::Array<T> buffer;
diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index 4b42ed81ea7..0b2e096a18d 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -770,23 +770,23 @@ ActionPlayPreloadAnimation::ActionPlayPreloadAnimation(ZVision *engine, int32 sl
 	// Original script gives wrong coordinates & frames
 	if (engine->getGameId() == GID_NEMESIS)
 		switch (_slotKey) {
-			case 1282:
-				_x1 = 146;
-				_y1 = 142;
-				_x2 = 298;
-				_y2 = 236;
-				_startFrame = 16;
-				_endFrame = 31;
-				break;
-			case 1289:
-				_x1 = 146;
-				_y1 = 142;
-				_x2 = 298;
-				_y2 = 236;
-				_endFrame = 15;
-				break;
-			default:
-				break;
+		case 1282:
+			_x1 = 146;
+			_y1 = 142;
+			_x2 = 298;
+			_y2 = 236;
+			_startFrame = 16;
+			_endFrame = 31;
+			break;
+		case 1289:
+			_x1 = 146;
+			_y1 = 142;
+			_x2 = 298;
+			_y2 = 236;
+			_endFrame = 15;
+			break;
+		default:
+			break;
 		}
 }
 


Commit: 2cf3ddd0bc1822abf9c6836c87f5669c59d8178b
    https://github.com/scummvm/scummvm/commit/2cf3ddd0bc1822abf9c6836c87f5669c59d8178b
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:00+02:00

Commit Message:
ZVISION: Bugfix & const reference suggestions from code review.

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/graphics/render_table.h


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index aa9f1e4f4fe..62176d1f422 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -219,8 +219,8 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
 			_outputSurface = inputSurface;
 			outWndDirtyRect = _backgroundSurfaceDirtyRect;
 			break;
-			debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
 		}
+		debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
 		debug(5, "Rendering working area");
 		_workingManagedSurface.simpleBlitFrom(*_outputSurface); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
 		debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index 6b0e833a494..6c475e0ae26 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -174,10 +174,10 @@ public:
 
 	Graphics::ManagedSurface &getVidSurface(Common::Rect dstRect);  //dstRect is defined relative to working area origin
 
-	Common::Rect getMenuArea() {
+	const Common::Rect getMenuArea() {
 		return _menuArea;
 	}
-	Common::Rect getWorkingArea() {
+	const Common::Rect getWorkingArea() {
 		return _workingArea;
 	}
 
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index fabd0403f64..b1cba26df41 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -152,7 +152,7 @@ public:
 //	void mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 destWidth, const Common::Rect &subRect);
 	void mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf, bool filter = false);
 	template <typename I>
-	Common::String pixelToBinary(I &pixel, bool splitColors = true) {
+	Common::String pixelToBinary(const I &pixel, bool splitColors = true) {
 		uint8 bits = sizeof(pixel) << 3;
 		Common::String str("0b");
 		I spaceMask = 0;


Commit: e8765be27f84c27bccf50ac16e9f95e66927a9d3
    https://github.com/scummvm/scummvm/commit/e8765be27f84c27bccf50ac16e9f95e66927a9d3
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:00+02:00

Commit Message:
ZVISION: Removed unfinished rework of blitSurfaceToSurface() into local side branch.

Changed paths:
    engines/zvision/graphics/render_manager.cpp


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 62176d1f422..3346672b163 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -504,8 +504,6 @@ void RenderManager::scaleBuffer(const void *src, void *dst, uint32 srcWidth, uin
 	}
 }
 
-//ORIGINAL FUNCTION
-//*
 void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, Common::Rect srcRect, Graphics::Surface &dst, int _x, int _y) {
 	debug(9, "blitSurfaceToSurface");
 	Common::Point dstPos = Common::Point(_x, _y);
@@ -515,13 +513,6 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, Common::R
 	//Clip source rectangle to within bounds of source buffer
 	srcRect.clip(src.w, src.h);
 
-	//CODE IDENTICAL TO HERE
-
-	//BUG TEST CODE
-	//Common::Point dstPos2 = dstPos;
-	//Common::Rect srcRect2 = srcRect;
-	//Common::Rect::getBlitRect(dstPos2, srcRect2, Common::Rect(dst.w,dst.h));
-
 	//Generate destination rectangle
 	Common::Rect dstRect = Common::Rect(dst.w, dst.h);
 	//Translate destination rectangle to its position relative to source rectangle
@@ -529,24 +520,6 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, Common::R
 	//clip source rectangle to within bounds of offset destination rectangle
 	srcRect.clip(dstRect);
 
-	//BUG TEST
-	/*
-	if(srcRect.left != srcRect2.left) {
-	   debug("srcRect.left = %i, srcRect2.left = %i", srcRect.left, srcRect2.left);
-	}
-	if(srcRect.top != srcRect2.top) {
-	   debug("srcRect.top = %i, srcRect2.top = %i", srcRect.top, srcRect2.top);
-	}
-	if(srcRect.right != srcRect2.right) {
-	   debug("srcRect.right = %i, srcRect2.right = %i", srcRect.right, srcRect2.right);
-	}
-	if(srcRect.bottom != srcRect2.bottom) {
-	   debug("srcRect.bottom = %i, srcRect2.bottom = %i", srcRect.bottom, srcRect2.bottom);
-	}
-	*/
-
-	//CODE IDENTICAL FROM HERE
-
 	//Abort if nothing to blit
 	if (!srcRect.isEmpty()) {
 		//Convert pixel format of source to match destination
@@ -560,9 +533,6 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, Common::R
 		if (dstPos.y < 0)
 			dstPos.y = 0;
 
-		//BUG TEST
-		//assert(dstPos == dstPos2);
-
 		//If _x & _y lie within destination surface
 		if (dstPos.x < dst.w && dstPos.y < dst.h) {
 			//Get pointer for destination buffer blit rectangle origin
@@ -572,46 +542,7 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, Common::R
 		srcAdapted->free();
 		delete srcAdapted;
 	}
-
-}
-/*/
-
-//SIMPLIFIED FUNCTION
-//TODO - find bug that breaks panorama rotation.  Suspect problem with negative arguments of some sort.
-void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, Common::Rect srcRect , Graphics::Surface &dst, int _x, int _y) {
-    Common::Rect srcRect = srcRect;
-    Common::Point dstPos = Common::Point(_x,_y);
-    //Default to using whole source surface
-    if (srcRect.isEmpty())
-        srcRect = Common::Rect(src.w, src.h);
-  //Ensure source rectangle does not read beyond bounds of source surface
-    srcRect.clip(src.w, src.h);
-
-    //CODE IDENTICAL TO HERE
-
-    //Ensure source rectangle does not write beyond bounds of destination surface & is valid
-      //NB alters dstPos & srcRect!
-    Common::Rect::getBlitRect(dstPos, srcRect, Common::Rect(dst.w,dst.h));
-
-  //CODE IDENTICAL FROM HERE
-
-    //Abort if nothing to blit
-    if(!srcRect.isEmpty()) {
-    //Convert pixel format of source to match destination
-      Graphics::Surface *srcAdapted = src.convertTo(dst.format);
-      //Get pointer for source buffer blit rectangle origin
-      const byte *srcBuffer = (const byte *)srcAdapted->getBasePtr(srcRect.left, srcRect.top);
-    //If _x & _y lie within destination surface
-    if (dstPos.x < dst.w && dstPos.y < dst.h) {
-      //Get pointer for destination buffer blit rectangle origin
-        byte *dstBuffer = (byte *)dst.getBasePtr(dstPos.x, dstPos.y);
-        Graphics::copyBlit(dstBuffer,srcBuffer,dst.pitch,srcAdapted->pitch,srcRect.width(),srcRect.height(),srcAdapted->format.bytesPerPixel);
-    }
-      srcAdapted->free();
-      delete srcAdapted;
-  }
 }
-//*/
 
 void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, Common::Rect srcRect , Graphics::Surface &dst, int _x, int _y, uint32 colorkey) {
 	debug(9, "blitSurfaceToSurface");


Commit: 303b7d5713fef254dc1166e5b9ec52e49b70fbd9
    https://github.com/scummvm/scummvm/commit/303b7d5713fef254dc1166e5b9ec52e49b70fbd9
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:00+02:00

Commit Message:
ZVISION: Code formatting compliance.
Remove commented-out code from ZGI death screen restart, no longer needed.

Changed paths:
    engines/zvision/file/save_manager.cpp
    engines/zvision/graphics/cursors/cursor.cpp
    engines/zvision/graphics/graphics_effect.h
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_table.cpp


diff --git a/engines/zvision/file/save_manager.cpp b/engines/zvision/file/save_manager.cpp
index 1681715b238..c0290766ad9 100644
--- a/engines/zvision/file/save_manager.cpp
+++ b/engines/zvision/file/save_manager.cpp
@@ -131,20 +131,8 @@ void SaveManager::writeSaveGameHeader(Common::OutSaveFile *file, const Common::S
 Common::Error SaveManager::loadGame(int slot) {
 	Common::SeekableReadStream *saveFile = NULL;
 	if (slot < 0) {
-		//Restart game, used by ZGI death screen only
-		/*
-		        saveFile = _engine->getSearchManager()->openFile("r.svr");
-		        if (!saveFile) {
-		            Common::File *restoreFile = new Common::File();
-		            if (!restoreFile->open("r.svr")) {
-		                delete restoreFile;
-		                return Common::kPathDoesNotExist;
-		            }
-		            saveFile = restoreFile;
-		        }
-		/*/
+		// Restart game, used by ZGI death screen only
 		_engine->getScriptManager()->initialize(true);
-//*/
 		return Common::kNoError;
 	} else {
 		saveFile = getSlotFile(slot);
@@ -159,8 +147,8 @@ Common::Error SaveManager::loadGame(int slot) {
 		scriptManager->deserialize(saveFile);
 		delete saveFile;
 		if (_engine->getGameId() == GID_NEMESIS)  {
-			//Zork Nemesis has no in-game option to select panorama quality or animation options
-			//We set them here to ensure loaded games don't override current game configuration
+			// Zork Nemesis has no in-game option to select panorama quality or animation options
+			// We set them here to ensure loaded games don't override current game configuration
 			scriptManager->setStateValue(StateKey_HighQuality, ConfMan.getBool("highquality"));
 			scriptManager->setStateValue(StateKey_NoTurnAnim, ConfMan.getBool("noanimwhileturning"));
 			if (scriptManager->getCurrentLocation() == "tv2f") {
diff --git a/engines/zvision/graphics/cursors/cursor.cpp b/engines/zvision/graphics/cursors/cursor.cpp
index da9c2902e71..49f83ae2700 100644
--- a/engines/zvision/graphics/cursors/cursor.cpp
+++ b/engines/zvision/graphics/cursors/cursor.cpp
@@ -60,11 +60,11 @@ ZorkCursor::ZorkCursor(ZVision *engine, const Common::Path &fileName)
 	uint32 bytesRead = file.read(_surface.getPixels(), dataSize);
 	assert(bytesRead == dataSize);
 
-	#ifndef SCUMM_LITTLE_ENDIAN
+#ifndef SCUMM_LITTLE_ENDIAN
 	int16 *buffer = (int16 *)_surface.getPixels();
 	for (uint32 i = 0; i < dataSize / 2; ++i)
 		buffer[i] = FROM_LE_16(buffer[i]);
-	#endif
+#endif
 }
 
 ZorkCursor::ZorkCursor(const ZorkCursor &other) {
diff --git a/engines/zvision/graphics/graphics_effect.h b/engines/zvision/graphics/graphics_effect.h
index e060b9a9028..2f0edfb529b 100644
--- a/engines/zvision/graphics/graphics_effect.h
+++ b/engines/zvision/graphics/graphics_effect.h
@@ -48,13 +48,13 @@ public:
 		return _region;
 	}
 
-	//If true, effect is applied to the current background image prior to panoramic warping
-	//If false, effect is applied to the effects buffer, which corresponds directly to the working window
+	// If true, effect is applied to the current background image prior to panoramic warping
+	// If false, effect is applied to the effects buffer, which corresponds directly to the working window
 	bool isPort() {
 		return _ported;
 	}
 
-	//Make a copy of supplied surface, draw effect on it, then return that altered surface
+	// Make a copy of supplied surface, draw effect on it, then return that altered surface
 	virtual const Graphics::Surface *draw(const Graphics::Surface &srcSubRect) {
 		return &_surface;
 	}
diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 3346672b163..510207b41d5 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -58,20 +58,20 @@ RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const G
 	  _widescreen(widescreen),
 	  _frameLimiter(engine->_system, doubleFPS ? 60 : 30) {
 	debug(1, "creating render manager");
-	//Define graphics modes & screen subarea geometry
+	// Define graphics modes & screen subarea geometry
 	Graphics::ModeList modes;
 	_textOffset = _layout.workingArea.origin() - _layout.textArea.origin();
 	modes.push_back(Graphics::Mode(_screenArea.width(), _screenArea.height()));
-	#if defined(USE_MPEG2) && defined(USE_A52)
+#if defined(USE_MPEG2) && defined(USE_A52)
 	if (_engine->getGameId() == GID_GRANDINQUISITOR && (_engine->getFeatures() & ADGF_DVD)) {
 		if (_widescreen)
 			modes.push_back(Graphics::Mode(_HDscreenAreaWide.width(), _HDscreenAreaWide.height()));
 		else
 			modes.push_back(Graphics::Mode(_HDscreenArea.width(), _HDscreenArea.height()));
 	}
-	#endif
+#endif
 	initGraphicsModes(modes);
-	//Create backbuffers
+	// Create backbuffers
 	_backgroundSurface.create(_workingArea.width(), _workingArea.height(), _pixelFormat);
 	_effectSurface.create(_workingArea.width(), _workingArea.height(), _pixelFormat);
 	_warpedSceneSurface.create(_workingArea.width(), _workingArea.height(), _pixelFormat);
@@ -112,8 +112,8 @@ void RenderManager::initialize(bool hiRes) {
 		_textLetterbox.moveTo(_textArea.origin());
 	}
 
-	//Screen
-	#if defined(USE_MPEG2) && defined(USE_A52)
+	// Screen
+#if defined(USE_MPEG2) && defined(USE_A52)
 	if (_hiRes) {
 		debug(1, "Switching to high resolution");
 		upscaleRect(_screenArea);
@@ -121,14 +121,14 @@ void RenderManager::initialize(bool hiRes) {
 		upscaleRect(_textArea);
 	} else
 		debug(1, "Switching to standard resolution");
-	#endif
+#endif
 	_screen.create(_screenArea.width(), _screenArea.height(), _pixelFormat);
 	_screen.setTransparentColor(-1);
 	_screen.clear();
 
 	debug(1, "_workingAreaCenter = %d,%d", _workingAreaCenter.x, _workingAreaCenter.y);
 
-	//Managed screen subsurfaces
+	// Managed screen subsurfaces
 	_workingManagedSurface.create(_screen, _workingArea);
 	_menuManagedSurface.create(_screen, _menuArea);
 	_textManagedSurface.create(_screen, _textArea);
@@ -136,7 +136,7 @@ void RenderManager::initialize(bool hiRes) {
 	debug(2, "working area: %d,%d,%d,%d", _workingArea.left, _workingArea.top, _workingArea.bottom, _workingArea.right);
 	debug(2, "text area: %d,%d,%d,%d", _textArea.left, _textArea.top, _textArea.bottom, _textArea.right);
 
-	//Menu & text area dirty rectangles
+	// Menu & text area dirty rectangles
 	_menuOverlay = _menuArea.findIntersectingRect(_workingArea);
 	if (!_menuOverlay.isEmpty() && _menuArea.left >= _workingArea.left && _menuArea.right <= _workingArea.right)
 		_menuLetterbox = Common::Rect(_menuArea.left, _menuArea.top, _menuArea.right, _workingArea.top);
@@ -153,12 +153,12 @@ void RenderManager::initialize(bool hiRes) {
 	debug(2, "menu overlay area: %d,%d,%d,%d", _menuOverlay.left, _menuOverlay.top, _menuOverlay.bottom, _menuOverlay.right);
 
 	debug(2, "Clearing backbuffers");
-	//Clear backbuffer surfaces
+	// Clear backbuffer surfaces
 	clearMenuSurface(true);
 	clearTextSurface(true);
 	debug(2, "Backbuffers cleared");
 
-	//Set hardware/window resolution
+	// Set hardware/window resolution
 	debug(1, "_screen.w = %d, _screen.h = %d", _screen.w, _screen.h);
 	initGraphics(_screen.w, _screen.h, &_engine->_screenPixelFormat);
 	_frameLimiter.initialize();
@@ -171,7 +171,7 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
 	if (!overlayOnly) {
 		Graphics::Surface *inputSurface = &_backgroundSurface;
 		Common::Rect outWndDirtyRect;
-		//Apply graphical effects to temporary effects buffer and/or directly to current background image, as appropriate
+		// Apply graphical effects to temporary effects buffer and/or directly to current background image, as appropriate
 		if (!_effects.empty()) {
 			debug(6, "Rendering effects");
 			bool copied = false;
@@ -196,15 +196,15 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
 					blitSurfaceToSurface(*post, empty, _effectSurface, screenSpaceLocation.left, screenSpaceLocation.top);
 					debug(1, "windowRect %d,%d,%d,%d, screenSpaceLocation %d,%d,%d,%d", windowRect.left, windowRect.top, windowRect.bottom, windowRect.right, screenSpaceLocation.left, screenSpaceLocation.top, screenSpaceLocation.bottom, screenSpaceLocation.right);
 					screenSpaceLocation.clip(windowRect);
-					if (_backgroundSurfaceDirtyRect .isEmpty())
+					if (_backgroundSurfaceDirtyRect.isEmpty())
 						_backgroundSurfaceDirtyRect = screenSpaceLocation;
 					else
 						_backgroundSurfaceDirtyRect.extend(screenSpaceLocation);
 				}
 			}
-			debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
+			debug(5, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
 		}
-		//Apply panorama/tilt warp to background image
+		// Apply panorama/tilt warp to background image
 		switch (_renderTable.getRenderState()) {
 		case RenderTable::PANORAMA:
 		case RenderTable::TILT:
@@ -220,27 +220,27 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
 			outWndDirtyRect = _backgroundSurfaceDirtyRect;
 			break;
 		}
-		debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
+		debug(5, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
 		debug(5, "Rendering working area");
-		_workingManagedSurface.simpleBlitFrom(*_outputSurface); //TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
-		debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
+		_workingManagedSurface.simpleBlitFrom(*_outputSurface); // TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
+		debug(5, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
 	}
 	if (preStream) {
 		debug(5, "Pre-rendering text area for video stream");
-		_workingManagedSurface.simpleBlitFrom(*_outputSurface, _textOverlay, _textOverlay.origin()); //Prevents subtitle visual corruption when streaming videos that don't fully overlap them, e.g. Nemesis sarcophagi
+		_workingManagedSurface.simpleBlitFrom(*_outputSurface, _textOverlay, _textOverlay.origin()); // Prevents subtitle visual corruption when streaming videos that don't fully overlap them, e.g. Nemesis sarcophagi
 		return false;
 	} else {
 		debug(5, "Rendering menu");
 		_menuManagedSurface.transBlitFrom(_menuSurface, -1);
-		debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
+		debug(5, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
 		debug(5, "Rendering text");
 		_textManagedSurface.transBlitFrom(_textSurface, -1);
-		debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
+		debug(5, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
 		if (immediate) {
 			_frameLimiter.startFrame();
 			debug(5, "Updating screen, immediate");
 			_screen.update();
-			debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
+			debug(5, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
 			debug(10, "~renderSceneToScreen, immediate");
 			return true;
 		} else if (_engine->canRender()) {
@@ -248,7 +248,7 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
 			_frameLimiter.startFrame();
 			debug(5, "Updating screen, frame limited");
 			_screen.update();
-			debug(5, "\tNett render time %d ms", _system->getMillis() - startTime);
+			debug(5, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
 			debug(10, "~renderSceneToScreen, frame limited");
 			return true;
 		} else {
@@ -259,7 +259,7 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
 }
 
 Graphics::ManagedSurface &RenderManager::getVidSurface(Common::Rect dstRect) {
-	dstRect.translate(_workingArea.left, _workingArea.top);  //Convert to screen coordinates
+	dstRect.translate(_workingArea.left, _workingArea.top);  // Convert to screen coordinates
 	_vidManagedSurface.create(_screen, dstRect);
 	debug(1, "Obtaining managed video surface at %d,%d,%d,%d", dstRect.left, dstRect.top, dstRect.right, dstRect.bottom);
 	return _vidManagedSurface;
@@ -507,35 +507,35 @@ void RenderManager::scaleBuffer(const void *src, void *dst, uint32 srcWidth, uin
 void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, Common::Rect srcRect, Graphics::Surface &dst, int _x, int _y) {
 	debug(9, "blitSurfaceToSurface");
 	Common::Point dstPos = Common::Point(_x, _y);
-	//Default to using whole source surface
+	// Default to using whole source surface
 	if (srcRect.isEmpty())
 		srcRect = Common::Rect(src.w, src.h);
-	//Clip source rectangle to within bounds of source buffer
+	// Clip source rectangle to within bounds of source buffer
 	srcRect.clip(src.w, src.h);
 
-	//Generate destination rectangle
+	// Generate destination rectangle
 	Common::Rect dstRect = Common::Rect(dst.w, dst.h);
-	//Translate destination rectangle to its position relative to source rectangle
+	// Translate destination rectangle to its position relative to source rectangle
 	dstRect.translate(srcRect.left - _x, srcRect.top - _y);
-	//clip source rectangle to within bounds of offset destination rectangle
+	// clip source rectangle to within bounds of offset destination rectangle
 	srcRect.clip(dstRect);
 
-	//Abort if nothing to blit
+	// Abort if nothing to blit
 	if (!srcRect.isEmpty()) {
-		//Convert pixel format of source to match destination
+		// Convert pixel format of source to match destination
 		Graphics::Surface *srcAdapted = src.convertTo(dst.format);
-		//Get pointer for source buffer blit rectangle origin
+		// Get pointer for source buffer blit rectangle origin
 		const byte *srcBuffer = (const byte *)srcAdapted->getBasePtr(srcRect.left, srcRect.top);
 
-		//Default to blitting into origin of target surface if negative valued
+		// Default to blitting into origin of target surface if negative valued
 		if (dstPos.x < 0)
 			dstPos.x = 0;
 		if (dstPos.y < 0)
 			dstPos.y = 0;
 
-		//If _x & _y lie within destination surface
+		// If _x & _y lie within destination surface
 		if (dstPos.x < dst.w && dstPos.y < dst.h) {
-			//Get pointer for destination buffer blit rectangle origin
+			// Get pointer for destination buffer blit rectangle origin
 			byte *dstBuffer = (byte *)dst.getBasePtr(dstPos.x, dstPos.y);
 			Graphics::copyBlit(dstBuffer, srcBuffer, dst.pitch, srcAdapted->pitch, srcRect.width(), srcRect.height(), srcAdapted->format.bytesPerPixel);
 		}
@@ -552,7 +552,7 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, Common::R
 	Common::Rect dstRect = Common::Rect(-_x + srcRect.left , -_y + srcRect.top, -_x + srcRect.left + dst.w, -_y + srcRect.top + dst.h);
 	srcRect.clip(dstRect);
 
-	//Abort if nothing to blit
+	// Abort if nothing to blit
 	if (srcRect.isEmpty() || !srcRect.isValidRect())
 		return;
 
@@ -622,7 +622,7 @@ void RenderManager::clearMenuSurface(bool force, int32 colorkey) {
 	if (force)
 		_menuSurfaceDirtyRect = Common::Rect(_menuArea.width(), _menuArea.height());
 	if (!_menuSurfaceDirtyRect.isEmpty()) {
-		//Convert to local menuArea coordinates
+		// Convert to local menuArea coordinates
 		Common::Rect letterbox = _menuLetterbox;
 		Common::Rect overlay = _menuOverlay;
 		letterbox.translate(-_menuArea.left, -_menuArea.top);
@@ -633,7 +633,7 @@ void RenderManager::clearMenuSurface(bool force, int32 colorkey) {
 		Common::Rect _menuOverlayDirty = _menuSurfaceDirtyRect.findIntersectingRect(overlay);
 		if (!_menuOverlayDirty.isEmpty()) {
 			_menuSurface.fillRect(_menuOverlayDirty, colorkey);
-			//TODO - mark working window dirty here so that it will redraw & blank overlaid residue on next frame
+			// TODO - mark working window dirty here so that it will redraw & blank overlaid residue on next frame
 		}
 		_menuSurfaceDirtyRect = Common::Rect(0, 0);
 	}
@@ -654,7 +654,7 @@ void RenderManager::clearTextSurface(bool force, int32 colorkey) {
 	if (force)
 		_textSurfaceDirtyRect = Common::Rect(_textArea.width(), _textArea.height());
 	if (!_textSurfaceDirtyRect.isEmpty()) {
-		//Convert to local textArea coordinates
+		// Convert to local textArea coordinates
 		Common::Rect letterbox = _textLetterbox;
 		Common::Rect overlay = _textOverlay;
 		letterbox.translate(-_textArea.left, -_textArea.top);
@@ -665,7 +665,7 @@ void RenderManager::clearTextSurface(bool force, int32 colorkey) {
 		Common::Rect _textOverlayDirty = _textSurfaceDirtyRect.findIntersectingRect(overlay);
 		if (!_textOverlayDirty.isEmpty()) {
 			_textSurface.fillRect(_textOverlayDirty, colorkey);
-			//TODO - mark working window dirty here so that it will redraw & blank overlaid residue on next frame
+			// TODO - mark working window dirty here so that it will redraw & blank overlaid residue on next frame
 		}
 		_textSurfaceDirtyRect = Common::Rect(0, 0);
 	}
@@ -964,19 +964,19 @@ void RenderManager::markDirty() {
 	_backgroundDirtyRect = Common::Rect(_backgroundWidth, _backgroundHeight);
 }
 
-//*
+// *
 void RenderManager::bkgFill(uint8 r, uint8 g, uint8 b) {
 	_currentBackgroundImage.fillRect(Common::Rect(_currentBackgroundImage.w, _currentBackgroundImage.h), _currentBackgroundImage.format.RGBToColor(r, g, b));
 	markDirty();
 }
-//*/
+// */
 
 
 void RenderManager::updateRotation() {
 	int16 velocity = _engine->getMouseVelocity() + _engine->getKeyboardVelocity();
 	ScriptManager *scriptManager = _engine->getScriptManager();
 
-	if (_doubleFPS || !_frameLimiter.isEnabled()) //Assuming 60fps when in Vsync mode.
+	if (_doubleFPS || !_frameLimiter.isEnabled()) // Assuming 60fps when in Vsync mode.
 		velocity /= 2;
 
 	if (velocity) {
diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index bb23e8d8fce..08d9b9dbe3b 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -92,13 +92,14 @@ const Common::Point RenderTable::convertWarpedCoordToFlatCoord(const Common::Poi
 	return newPoint;
 }
 
+//Disused at present; potentially useful for future rendering efficient improvements.
 /*/
 void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 destWidth, const Common::Rect &subRect) {
     uint32 destOffset = 0;
   uint32 sourceXIndex = 0;
   uint32 sourceYIndex = 0;
   if(highQuality) {
-    //TODO - convert to high quality pixel filtering
+    // TODO - convert to high quality pixel filtering
       for (int16 y = subRect.top; y < subRect.bottom; ++y) {
           uint32 sourceOffset = y * _numColumns;
           for (int16 x = subRect.left; x < subRect.right; ++x) {
@@ -127,7 +128,7 @@ void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 d
       }
   }
 }
-//*/
+// */
 
 void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf, bool highQuality) {
 	_destOffset = 0;
@@ -140,7 +141,7 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 	}
 	uint32 mutationTime = _system->getMillis();
 	if (_highQuality) {
-		//Apply bilinear interpolation
+		// Apply bilinear interpolation
 		FilterPixel _curP;
 		for (int16 y = 0; y < srcBuf->h; ++y) {
 			_sourceOffset = y * _numColumns;
@@ -165,11 +166,11 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 				debug(2,"\t_fX: %f, _fY: %f", _curP._fX, _curP._fY);
 				debug(2,"\tYT: %d, YB: %d, XL: %d XR: %d", _srcIndexYT, _srcIndexYB, _srcIndexXL, _srcIndexXR);
 				}
-				//*/
+				// */
 			}
 		}
 	} else {
-		//Apply nearest-neighbour interpolation
+		// Apply nearest-neighbour interpolation
 		for (int16 y = 0; y < srcBuf->h; ++y) {
 			_sourceOffset = y * _numColumns;
 			for (int16 x = 0; x < srcBuf->w; ++x) {
@@ -213,9 +214,9 @@ void RenderTable::generateLookupTable(bool tilt) {
 	uint x = 0;
 	uint y = 0;
 	auto outerLoop = [&](uint & polarCoord, float & halfPolarSize, float & scale) {
-		//polarCoord is the coordinate of the working window pixel parallel to the direction of camera rotation
-		//halfPolarSize is the distance from the central axis to the outermost working window pixel in the direction of camera rotation
-		//alpha represents the angle in the direction of camera rotation between the view axis and the centre of a pixel at the given polar coordinate
+		// polarCoord is the coordinate of the working window pixel parallel to the direction of camera rotation
+		// halfPolarSize is the distance from the central axis to the outermost working window pixel in the direction of camera rotation
+		// alpha represents the angle in the direction of camera rotation between the view axis and the centre of a pixel at the given polar coordinate
 		alpha = atan(((float)polarCoord - halfPolarSize) / cylinderRadius);
 		// To map the polar coordinate to the cylinder surface coordinates, we just need to calculate the arc length
 		// We also scale it by linearScale
@@ -236,10 +237,10 @@ void RenderTable::generateLookupTable(bool tilt) {
 		    }
 		*/
 		// Only store the (x,y) offsets instead of the absolute positions
-//		_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality, _printDebug);
+// 		_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality, _printDebug);
 		_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality);
-		//Transformation is both horizontally and vertically symmetrical about the camera axis,
-		//We can thus save on trigonometric calculations by computing one quarter of the transformation matrix and then mirroring it in both X & Y:
+		// Transformation is both horizontally and vertically symmetrical about the camera axis,
+		// We can thus save on trigonometric calculations by computing one quarter of the transformation matrix and then mirroring it in both X & Y:
 		_internalBuffer[indexBL] = _internalBuffer[indexTL];
 		_internalBuffer[indexBL].flipV();
 		_internalBuffer[indexTR] = _internalBuffer[indexTL];


Commit: 59ecad7841df98a6354aff9f4993471456922ed8
    https://github.com/scummvm/scummvm/commit/59ecad7841df98a6354aff9f4993471456922ed8
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:00+02:00

Commit Message:
ZVISION: Code formatting compliance & obsolete code removal.

Changed paths:
    engines/zvision/core/console.cpp
    engines/zvision/core/events.cpp


diff --git a/engines/zvision/core/console.cpp b/engines/zvision/core/console.cpp
index 18c290c718a..11dc7a729b1 100644
--- a/engines/zvision/core/console.cpp
+++ b/engines/zvision/core/console.cpp
@@ -140,10 +140,10 @@ bool Console::cmdRawToWav(int argc, const char **argv) {
 	output.writeUint32LE(file.size() * 2);
 	int16 *buffer = new int16[file.size()];
 	audioStream->readBuffer(buffer, file.size());
-	#ifndef SCUMM_LITTLE_ENDIAN
+#ifndef SCUMM_LITTLE_ENDIAN
 	for (int i = 0; i < file.size(); ++i)
 		buffer[i] = TO_LE_16(buffer[i]);
-	#endif
+#endif
 	output.write(buffer, file.size() * 2);
 
 	delete[] buffer;
diff --git a/engines/zvision/core/events.cpp b/engines/zvision/core/events.cpp
index ff5705353ff..863754652f7 100644
--- a/engines/zvision/core/events.cpp
+++ b/engines/zvision/core/events.cpp
@@ -218,25 +218,21 @@ void ZVision::processEvents() {
 				break;
 
 			case kZVisionActionSave:
-				//if (_menu->getEnable() & kMenubarSave)
 				if (_menu->getEnable(kMainMenuSave))
 					_scriptManager->changeLocation('g', 'j', 's', 'e', 0);
 				break;
 
 			case kZVisionActionRestore:
-				//if (_menu->getEnable() & kMenubarRestore)
 				if (_menu->getEnable(kMainMenuLoad))
 					_scriptManager->changeLocation('g', 'j', 'r', 'e', 0);
 				break;
 
 			case kZVisionActionPreferences:
-				//if (_menu->getEnable() & kMenubarSettings)
 				if (_menu->getEnable(kMainMenuPrefs))
 					_scriptManager->changeLocation('g', 'j', 'p', 'e', 0);
 				break;
 
 			case kZVisionActionQuit:
-				//if (_menu->getEnable() & kMenubarExit)
 				if (_menu->getEnable(kMainMenuExit))
 					ifQuit();
 				break;


Commit: 36f443e77c99c8934c4e215e9dfea77d0a4c5bd5
    https://github.com/scummvm/scummvm/commit/36f443e77c99c8934c4e215e9dfea77d0a4c5bd5
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:00+02:00

Commit Message:
ZVISION: Code formatting compliance.

Changed paths:
    engines/zvision/common/scroller.cpp
    engines/zvision/graphics/render_table.h
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/effects/music_effect.h
    engines/zvision/scripting/effects/syncsound_effect.cpp
    engines/zvision/scripting/menu.cpp
    engines/zvision/scripting/menu.h
    engines/zvision/scripting/scr_file_handling.cpp
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/sound/midi.cpp
    engines/zvision/sound/midi.h
    engines/zvision/sound/volume_manager.cpp
    engines/zvision/sound/volume_manager.h
    engines/zvision/text/subtitle_manager.cpp
    engines/zvision/text/subtitle_manager.h
    engines/zvision/text/text.cpp
    engines/zvision/video/video.cpp
    engines/zvision/zvision.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/common/scroller.cpp b/engines/zvision/common/scroller.cpp
index c242ffb9a62..ccbccc15128 100644
--- a/engines/zvision/common/scroller.cpp
+++ b/engines/zvision/common/scroller.cpp
@@ -66,7 +66,7 @@ bool LinearScroller::update(uint32 deltatime) {
 			_pos = _idlePos;
 		_moving = false;
 	}
-	return (_pos != _prevPos);  //True if redraw necessary
+	return (_pos != _prevPos);  // True if redraw necessary
 }
 
 void LinearScroller::reset() {
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index b1cba26df41..92494d19d06 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -31,17 +31,17 @@ namespace ZVision {
 
 class FilterPixel {
 public:
-	//Bitfields representing sequential direction of contraction
-	bool _xDir = 0; //0 left, 1 right
-	bool _yDir = 0; //0 up, 1 down
-	Common::Rect _Src = Common::Rect(0, 0); //Coordinates of four panorama image pixels around actual working window pixel
+	// Bitfields representing sequential direction of contraction
+	bool _xDir = 0; // 0 left, 1 right
+	bool _yDir = 0; // 0 up, 1 down
+	Common::Rect _Src = Common::Rect(0, 0); // Coordinates of four panorama image pixels around actual working window pixel
 
 	float _fX, _fY, _fTL, _fTR, _fBL, _fBR;
 
-//  bool _printDebug = false;
+// bool _printDebug = false;
 
 	FilterPixel() {}
-//  FilterPixel(float x, float y, bool highQuality=false, bool printDebug=false) {
+// FilterPixel(float x, float y, bool highQuality=false, bool printDebug=false) {
 	FilterPixel(float x, float y, bool highQuality = false) {
 		_Src.left = int16(floor(x));
 		_Src.right = int16(ceil(x));
@@ -64,7 +64,7 @@ public:
 			        debug(5,"_fX: %f, _fY: %f, _fTL:%f, _fTR:%f, _fBL:%f, _fBR:%f", _fX, _fY, _fTL, _fTR, _fBL, _fBR);
 			*/
 		} else {
-			//Nearest neighbour
+			// Nearest neighbour
 			_xDir = (x - _Src.left) > 0.5f;
 			_yDir = (y - _Src.top) > 0.5f;
 			/*
@@ -89,7 +89,7 @@ public:
 	RenderTable(ZVision *engine, uint numRows, uint numColumns, const Graphics::PixelFormat pixelFormat);
 	~RenderTable();
 
-//	Common::Point testPixel = Common::Point(255,0);
+// Common::Point testPixel = Common::Point(255,0);
 public:
 	enum RenderState {
 		PANORAMA,
@@ -100,8 +100,8 @@ public:
 private:
 	ZVision *_engine;
 	OSystem *_system;
-	uint _numRows, _numColumns, _halfRows, _halfColumns; //Working area width, height; half width, half height, in whole pixels
-	float _halfWidth, _halfHeight;  //Centre axis to midpoint of outermost pixel
+	uint _numRows, _numColumns, _halfRows, _halfColumns; // Working area width, height; half width, half height, in whole pixels
+	float _halfWidth, _halfHeight;  // Centre axis to midpoint of outermost pixel
 	FilterPixel *_internalBuffer;
 	RenderState _renderState;
 	bool _highQuality = false;
@@ -115,19 +115,19 @@ private:
 	uint32 _bTL, _bTR, _bBL, _bBR, _bF;
 
 	inline void splitColor(uint16 &color, uint32 &r, uint32 &g, uint32 &b) {
-		//NB Left & right shifting unnecessary for interpolating & recombining, so not bothering in order to save cycles
+		// NB Left & right shifting unnecessary for interpolating & recombining, so not bothering in order to save cycles
 		r = color & 0x001f;
 		g = color & 0x03e0;
 		b = color & 0x7c00;
 	}
 	inline uint16 mergeColor(uint32 &r, uint32 &g, uint32 &b) const {
-		//NB Red uses the lowest bits in RGB555 and so doesn't need its fractional bits masked away after averaging
+		// NB Red uses the lowest bits in RGB555 and so doesn't need its fractional bits masked away after averaging
 		return r | (g & 0x03e0) | (b & 0x7c00);
 	}
 
 
 	struct {
-		float verticalFOV;  //Radians
+		float verticalFOV;  // Radians
 		float linearScale;
 		bool reverse;
 		uint16 zeroPoint;
@@ -135,7 +135,7 @@ private:
 
 	// TODO: See if tilt and panorama need to have separate options
 	struct {
-		float verticalFOV;  //Radians
+		float verticalFOV;  // Radians
 		float linearScale;
 		bool reverse;
 		float gap;
@@ -147,9 +147,9 @@ public:
 	}
 	void setRenderState(RenderState newState);
 
-	const Common::Point convertWarpedCoordToFlatCoord(const Common::Point &point);  //input point in working area coordinates
+	const Common::Point convertWarpedCoordToFlatCoord(const Common::Point &point);  // input point in working area coordinates
 
-//	void mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 destWidth, const Common::Rect &subRect);
+// void mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 destWidth, const Common::Rect &subRect);
 	void mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf, bool filter = false);
 	template <typename I>
 	Common::String pixelToBinary(const I &pixel, bool splitColors = true) {
@@ -167,14 +167,14 @@ public:
 	}
 	void generateRenderTable();
 
-	void setPanoramaFoV(float fov); //Degrees
+	void setPanoramaFoV(float fov); // Degrees
 	void setPanoramaScale(float scale);
 	void setPanoramaReverse(bool reverse);
 	void setPanoramaZeroPoint(uint16 point);
 	uint16 getPanoramaZeroPoint();
 	bool getPanoramaReverse();
 
-	void setTiltFoV(float fov); //Degrees
+	void setTiltFoV(float fov); // Degrees
 	void setTiltScale(float scale);
 	void setTiltReverse(bool reverse);
 
@@ -185,7 +185,7 @@ public:
 private:
 	void generateLookupTable(bool tilt = false);
 	void generatePanoramaLookupTable();
-//	Common::Point generatePanoramaLookupPoint();
+// Common::Point generatePanoramaLookupPoint();
 	void generateTiltLookupTable();
 };
 
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 7e504cce819..190bb2ff621 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -57,10 +57,10 @@ void MusicNodeBASE::setBalance(int8 balance) {
 
 void MusicNodeBASE::updateMixer() {
 	if (_engine->getScriptManager()->getStateValue(StateKey_Qsound) >= 1)
-		_volumeOut = _engine->getVolumeManager()->convert(_volume, _azimuth, _directionality);  //Apply game-specific volume profile and then attenuate according to azimuth
+		_volumeOut = _engine->getVolumeManager()->convert(_volume, _azimuth, _directionality);  // Apply game-specific volume profile and then attenuate according to azimuth
 	else
-//    _volumeOut = _engine->getVolumeManager()->convert(_volume, kVolumeLinear);  //Apply linear volume profile and ignore azimuth
-		_volumeOut = _engine->getVolumeManager()->convert(_volume);  //Apply game-specific volume profile and ignore azimuth
+//    _volumeOut = _engine->getVolumeManager()->convert(_volume, kVolumeLinear);  // Apply linear volume profile and ignore azimuth
+		_volumeOut = _engine->getVolumeManager()->convert(_volume);  // Apply game-specific volume profile and ignore azimuth
 	outputMixer();
 }
 
@@ -112,7 +112,7 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 
 		Common::Path subpath(filename.getParent().appendComponent(subname));
 		if (_engine->getSearchManager()->hasFile(subpath))
-			_sub = _engine->getSubtitleManager()->create(subpath, _handle); //NB automatic subtitle!
+			_sub = _engine->getSubtitleManager()->create(subpath, _handle); // NB automatic subtitle!
 
 		_loaded = true;
 		updateMixer();
@@ -163,11 +163,11 @@ bool MusicNode::process(uint32 deltaTimeInMillis) {
 			if (_volume != _newvol)
 				setVolume(_newvol);
 		}
-		/*  //Redundant with switch to automatic subtitles
+		/*  // Redundant with switch to automatic subtitles
 
 		if (_sub && _engine->getScriptManager()->getStateValue(StateKey_Subtitles) == 1)
 		  _engine->getSubtitleManager()->update(_engine->_mixer->getSoundElapsedTime(_handle) / 100, _sub);
-		//*/
+		// */
 	}
 	return false;
 }
@@ -213,7 +213,7 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 	if (fx && fx->getType() == SCRIPTING_EFFECT_AUDIO) {
 		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
 		if (!_staticScreen)
-			//Original game scripted behaviour
+			// Original game scripted behaviour
 			switch (_engine->getRenderManager()->getRenderTable()->getRenderState()) {
 			case RenderTable::PANORAMA:
 				debug(3, "PanTrackNode in panorama mode");
@@ -223,8 +223,8 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 					_viewPos.setDegrees(360 * scriptManager->getStateValue(StateKey_ViewPos) / _width);
 				} else {
 					warning("Encountered zero background width whilst processing PanTrackNode in panoramic mode!");
-					//_sourcePos.setDegrees(0);
-					//_viewPos.setDegrees(0);
+					// _sourcePos.setDegrees(0);
+					// _viewPos.setDegrees(0);
 				}
 				break;
 			case RenderTable::FLAT:
@@ -235,14 +235,14 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 				_viewPos.setDegrees(0);
 				break;
 			} else {
-			//Used for auxiliary scripts only
+			// Used for auxiliary scripts only
 			_sourcePos.setDegrees(_pos);
 			_viewPos.setDegrees(0);
 		}
 		Math::Angle azimuth;
 		azimuth = _sourcePos - _viewPos;
 		debug(3, "soundPos: %f, _viewPos: %f, azimuth: %f, width %d", _sourcePos.getDegrees(), _viewPos.getDegrees(), azimuth.getDegrees(), _width);
-		//azimuth is sound source position relative to player, clockwise from centre of camera axis to front when viewed top-down
+		// azimuth is sound source position relative to player, clockwise from centre of camera axis to front when viewed top-down
 		mus->setDirection(azimuth, _mag);
 	}
 	return false;
diff --git a/engines/zvision/scripting/effects/music_effect.h b/engines/zvision/scripting/effects/music_effect.h
index 18439919eee..8685c4c56af 100644
--- a/engines/zvision/scripting/effects/music_effect.h
+++ b/engines/zvision/scripting/effects/music_effect.h
@@ -53,8 +53,8 @@ public:
 		return _volume;
 	}
 	virtual void setFade(int32 time, uint8 target) = 0;
-	virtual void setBalance(int8 balance);  //NB Overrides effects of setDirection()
-	void setDirection(Math::Angle azimuth, uint8 magnitude = 255);  //NB Overrides effects of setBalance()
+	virtual void setBalance(int8 balance);  // NB Overrides effects of setDirection()
+	void setDirection(Math::Angle azimuth, uint8 magnitude = 255);  // NB Overrides effects of setBalance()
 protected:
 	void updateMixer();
 	virtual void outputMixer() = 0;
@@ -62,7 +62,7 @@ protected:
 	uint8 _volume = 0;
 	int8 _balance = 0;
 	Math::Angle _azimuth;
-	uint8 _directionality;  //0 = fully ambient, 255 = fully directional
+	uint8 _directionality;  // 0 = fully ambient, 255 = fully directional
 	uint8 _volumeOut = 0;
 };
 
@@ -91,7 +91,7 @@ private:
 	uint8 _fadeStartVol;
 	uint8 _fadeEndVol;
 	uint32 _fadeTime;
-	uint32 _fadeElapsed; //Cumulative time since fade start
+	uint32 _fadeElapsed; // Cumulative time since fade start
 	bool _stereo;
 	Audio::SoundHandle _handle;
 	uint16 _sub;
diff --git a/engines/zvision/scripting/effects/syncsound_effect.cpp b/engines/zvision/scripting/effects/syncsound_effect.cpp
index b9cecbf8e19..62b2efdf950 100644
--- a/engines/zvision/scripting/effects/syncsound_effect.cpp
+++ b/engines/zvision/scripting/effects/syncsound_effect.cpp
@@ -59,7 +59,7 @@ SyncSoundNode::SyncSoundNode(ZVision *engine, uint32 key, Common::Path &filename
 
 	Common::Path subpath(filename.getParent().appendComponent(subname));
 	if (_engine->getSearchManager()->hasFile(subpath))
-		_sub = _engine->getSubtitleManager()->create(subpath, _handle); //NB automatic subtitle!
+		_sub = _engine->getSubtitleManager()->create(subpath, _handle); // NB automatic subtitle!
 }
 
 SyncSoundNode::~SyncSoundNode() {
@@ -75,10 +75,10 @@ bool SyncSoundNode::process(uint32 deltaTimeInMillis) {
 
 		if (_engine->getScriptManager()->getSideFX(_syncto) == NULL)
 			return stop();
-		/*  //Redundant with switch to automatic subtitles
+		/*  // Redundant with switch to automatic subtitles
 		  if (_sub && _engine->getScriptManager()->getStateValue(StateKey_Subtitles) == 1)
 		      _engine->getSubtitleManager()->update(_engine->_mixer->getSoundElapsedTime(_handle) / 100, _sub);
-		//*/
+		// */
 	}
 	return false;
 }
diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index 574d0cbc077..29bb27ab7c9 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -42,14 +42,14 @@ MenuManager::MenuManager(ZVision *engine, const Common::Rect menuArea, const Men
 
 	_enableFlags.set_size(6);
 	for (int8 i = 0; i < 4; i++) {
-		//Generate button hotspot areas
+		// Generate button hotspot areas
 		_menuHotspots[i] = Common::Rect(_params.wxButs[i][1], _menuArea.top, _params.wxButs[i][1] + _params.wxButs[i][0], _menuArea.bottom);
-		//Initialise button animation frames
+		// Initialise button animation frames
 		_mainFrames[i] = _params.idleFrame;
 	}
 	for (int i = 0; i < 4; i++)
 		_buttonAnim[i] = new LinearScroller(_params.activeFrame, _params.idleFrame, _params.buttonPeriod);
-	setFocus(kFocusNone); //Ensure focus list is initialised
+	setFocus(kFocusNone); // Ensure focus list is initialised
 	_mainArea = Common::Rect(_params.wMain, _hMainMenu);
 	_mainArea.moveTo(_menuOrigin + _mainScroller._pos);
 }
@@ -61,7 +61,7 @@ MenuManager::~MenuManager() {
 }
 
 void MenuManager::setEnable(uint16 flags) {
-	static const uint16 flagMasks[6] = {0x8, 0x4, 0x2, 0x1, 0x100, 0x200}; //Enum order: save,restore,prefs,quit,items,magic
+	static const uint16 flagMasks[6] = {0x8, 0x4, 0x2, 0x1, 0x100, 0x200}; // Enum order: save,restore,prefs,quit,items,magic
 	_menuBarFlag = flags;
 	for (uint i = 0; i <= 5; i++) {
 		if (_menuBarFlag & flagMasks[i])
@@ -75,7 +75,7 @@ void MenuManager::onMouseUp(const Common::Point &Pos) {
 	if (_menuFocus.front() == kFocusMain) {
 		_mouseOnItem = mouseOverMain(Pos);
 		if (_mouseOnItem == _mainClicked)
-			//Activate clicked action from main menu
+			// Activate clicked action from main menu
 			switch (_mouseOnItem) {
 			case kMainMenuSave:
 				_engine->getScriptManager()->changeLocation('g', 'j', 's', 'e', 0);
@@ -108,7 +108,7 @@ void MenuManager::onMouseUp(const Common::Point &Pos) {
 void MenuManager::onMouseDown(const Common::Point &Pos) {
 	if (_menuFocus.front() == kFocusMain) {
 		_mouseOnItem = mouseOverMain(Pos);
-		//Show clicked graphic
+		// Show clicked graphic
 		if ((_mouseOnItem >= 0) && (_mouseOnItem < 4))
 			if (_enableFlags.get(_mouseOnItem)) {
 				_mainClicked = _mouseOnItem;
@@ -129,20 +129,20 @@ void MenuManager::onMouseMove(const Common::Point &Pos) {
 
 	switch (_menuFocus.front()) {
 	case kFocusMain:
-		//Inform game scripting engine that mouse is in main menu
+		// Inform game scripting engine that mouse is in main menu
 		if (_engine->getScriptManager()->getStateValue(StateKey_MenuState) != 2)
 			_engine->getScriptManager()->setStateValue(StateKey_MenuState, 2);
 		_mouseOnItem = mouseOverMain(Pos);
 		break;
 	case kFocusNone:
-		//Inform game scripting engine that mouse is not in any menu
+		// Inform game scripting engine that mouse is not in any menu
 		if (_engine->getScriptManager()->getStateValue(StateKey_MenuState) != 0)
 			_engine->getScriptManager()->setStateValue(StateKey_MenuState, 0);
 		_mouseOnItem = -1;
 		break;
 	}
 	_mainScroller.setActive(_menuFocus.front() == kFocusMain);
-	//Update button animation status
+	// Update button animation status
 	for (int i = 0; i < 4; i++)
 		if (_menuFocus[0] == kFocusMain && _mouseOnItem == i)
 			_buttonAnim[i]->setActive(true);
@@ -153,8 +153,8 @@ void MenuManager::onMouseMove(const Common::Point &Pos) {
 }
 
 int MenuManager::mouseOverMain(const Common::Point &Pos) {
-	//Common::Rect mainHotspot(28,_hSideMenu);
-	//mainHotspot.moveTo(mainOrigin + _mainScroller._pos);
+	// Common::Rect mainHotspot(28,_hSideMenu);
+	// mainHotspot.moveTo(mainOrigin + _mainScroller._pos);
 	for (int8 i = 0; i < 4; i++) {
 		if (_enableFlags.get(i) && _menuHotspots[i].contains(Pos))
 			return i;
@@ -169,7 +169,7 @@ void MenuManager::process(uint32 deltatime) {
 			_menuHotspots[i].moveTo(_menuOrigin + Common::Point(_params.wxButs[i][1], _mainScroller._pos.y));
 		_redraw = true;
 	}
-	//Update button highlight animation frame
+	// Update button highlight animation frame
 	for (int i = 0; i < 4; i++)
 		if (_buttonAnim[i]->update(deltatime)) {
 			_mainFrames[i] = _buttonAnim[i]->_pos;
@@ -187,9 +187,9 @@ void MenuNemesis::redrawAll() {
 }
 
 void MenuManager::redrawMain() {
-	//Draw menu background
+	// Draw menu background
 	_engine->getRenderManager()->blitSurfaceToMenu(_mainBack, _mainScroller._pos.x, _mainScroller._pos.y, 0);
-	//Draw buttons
+	// Draw buttons
 	if (_menuFocus.front() == kFocusMain)
 		for (int8 i = 0; i < 4; i++) {
 			if (_enableFlags.get(i) && (_mainFrames[i] >= 0)) {
@@ -217,19 +217,19 @@ MenuZGI::MenuZGI(ZVision *engine, const Common::Rect menuArea) :
 	_magicArea = Common::Rect(_magicOrigin + _magicScroller._pos, _wSideMenu, _hSideMenu);
 	_itemsArea = Common::Rect(_itemsOrigin + _itemsScroller._pos, _wSideMenu, _hSideMenu);
 
-	//Buffer main menu background
+	// Buffer main menu background
 	_engine->getRenderManager()->readImageToSurface("gmzau031.tga", _mainBack, false);
 
 	char buf[24];
 	for (int i = 0; i < 4; i++) {
-		//Buffer menu buttons
+		// Buffer menu buttons
 		Common::sprintf_s(buf, "gmzmu%2.2x1.tga", i);
 		_engine->getRenderManager()->readImageToSurface(buf, _mainButtons[i][0], false);
 		Common::sprintf_s(buf, "gmznu%2.2x1.tga", i);
 		_engine->getRenderManager()->readImageToSurface(buf, _mainButtons[i][1], false);
 	}
 	for (int i = 1; i < 4; i++) {
-		//Buffer full menu backgrounds
+		// Buffer full menu backgrounds
 		Common::sprintf_s(buf, "gmzau%2.2x1.tga", i);
 		_engine->getRenderManager()->readImageToSurface(buf, _menuBack[i - 1], false);
 	}
@@ -243,7 +243,7 @@ MenuZGI::MenuZGI(ZVision *engine, const Common::Rect menuArea) :
 		_magic[i][1] = NULL;
 		_magicId[i] = 0;
 	}
-	//Initialise focus sequence
+	// Initialise focus sequence
 	setFocus(kFocusMain);
 	setFocus(kFocusMagic);
 	setFocus(kFocusItems);
@@ -286,7 +286,7 @@ bool MenuZGI::inMenu(const Common::Point &Pos) {
 
 void MenuZGI::onMouseUp(const Common::Point &Pos) {
 	if (inMenu(Pos))
-		//_redraw = true;
+		// _redraw = true;
 		switch (_menuFocus.front()) {
 		case kFocusItems:
 			if (_enableFlags.get(kItemsMenu)) {
@@ -342,7 +342,7 @@ void MenuZGI::onMouseMove(const Common::Point &Pos) {
 		_itemsScroller.reset();
 	}
 
-	//Set focus to topmost layer of menus that mouse is currently over
+	// Set focus to topmost layer of menus that mouse is currently over
 	for (uint8 i = 0; i < _menuFocus.size(); i++) {
 		switch (_menuFocus[i]) {
 		case kFocusItems:
@@ -420,7 +420,7 @@ int MenuZGI::mouseOverItem(const Common::Point &Pos, int itemCount) {
 int MenuZGI::mouseOverMagic(const Common::Point &Pos) {
 	Common::Rect magicHotspot(28, _hSideMenu);
 	magicHotspot.moveTo(_magicOrigin + _magicScroller._pos);
-	magicHotspot.translate(28, 0); //Offset from end of menu
+	magicHotspot.translate(28, 0); // Offset from end of menu
 	for (int i = 0; i < 12; i++) {
 		if (magicHotspot.contains(Pos))
 			return i;
@@ -555,12 +555,12 @@ void MenuZGI::redrawItems() {
 MenuNemesis::MenuNemesis(ZVision *engine, const Common::Rect menuArea) :
 	MenuManager(engine, menuArea, nemesisParams) {
 
-	//Buffer menu background image
+	// Buffer menu background image
 	_engine->getRenderManager()->readImageToSurface("bar.tga", _mainBack, false);
 
 	char buf[24];
 	for (int i = 0; i < 4; i++)
-		//Buffer menu buttons
+		// Buffer menu buttons
 		for (int j = 0; j < 6; j++) {
 			Common::sprintf_s(buf, "butfrm%d%d.tga", i + 1, j);
 			_engine->getRenderManager()->readImageToSurface(buf, _mainButtons[i][j], false);
@@ -580,8 +580,8 @@ bool MenuNemesis::inMenu(const Common::Point &Pos) {
 }
 
 void MenuNemesis::onMouseMove(const Common::Point &Pos) {
-	//Trigger main menu scrolldown to get mouse over main trigger area
-	//Set focus to topmost layer of menus that mouse is currently over
+	// Trigger main menu scrolldown to get mouse over main trigger area
+	// Set focus to topmost layer of menus that mouse is currently over
 	if (_mainArea.contains(Pos) || _menuTriggerArea.contains(Pos))
 		setFocus(kFocusMain);
 	else
diff --git a/engines/zvision/scripting/menu.h b/engines/zvision/scripting/menu.h
index 6ab6c120efe..b7d8a0588c3 100644
--- a/engines/zvision/scripting/menu.h
+++ b/engines/zvision/scripting/menu.h
@@ -44,19 +44,19 @@ enum {
 };
 
 struct MenuParams {
-	int16 wxButs[4][2];   //Widths & X positions of main menu buttons; {Save, Restore, Prefs, Quit}
-	int16 wMain;  //Width of main menu background
-	int8 idleFrame; //Frame to display of unselected main menu button
-	int8 activeFrame; //Frame to display of selected main menu button when mouse is down
-	int8 clickedFrame; //Frame to display of selected main menu button when mouse is down
-	Common::Point activePos;  //Fully scrolled main menu position, relative to origin of menu area
-	Common::Point idlePos;  //Fully retracted main menu position, relative to origin of menu area
-	int16 period; //Duration of main menu scrolldown
-	int16 triggerHeight;  //Height of menu trigger area when inactive
-	int16 buttonPeriod; //Duration of main menu button animation
+	int16 wxButs[4][2];   // Widths & X positions of main menu buttons; {Save, Restore, Prefs, Quit}
+	int16 wMain;  // Width of main menu background
+	int8 idleFrame; // Frame to display of unselected main menu button
+	int8 activeFrame; // Frame to display of selected main menu button when mouse is down
+	int8 clickedFrame; // Frame to display of selected main menu button when mouse is down
+	Common::Point activePos;  // Fully scrolled main menu position, relative to origin of menu area
+	Common::Point idlePos;  // Fully retracted main menu position, relative to origin of menu area
+	int16 period; // Duration of main menu scrolldown
+	int16 triggerHeight;  // Height of menu trigger area when inactive
+	int16 buttonPeriod; // Duration of main menu button animation
 };
 
-//NB - menu area is same width as working window.
+// NB - menu area is same width as working window.
 
 static const MenuParams nemesisParams {
 	{ {120, -1}, {144, 120}, {128, 264}, {120, 392} },
@@ -97,10 +97,10 @@ public:
 	};
 	virtual bool inMenu(const Common::Point &Pos) {
 		return false;
-	}; //For widescreen mod; used to suspend panning, tilting & scripting triggers when the mouse is within the working window but also in the menu.
+	}; // For widescreen mod; used to suspend panning, tilting & scripting triggers when the mouse is within the working window but also in the menu.
 
-	void mainMouseDown(const Common::Point &Pos); //Show clicked graphic under selected button
-	bool mainMouseMove(const Common::Point &Pos); //return true if selected button has changed
+	void mainMouseDown(const Common::Point &Pos); // Show clicked graphic under selected button
+	bool mainMouseMove(const Common::Point &Pos); // return true if selected button has changed
 
 	void setEnable(uint16 flags);
 	uint16 getEnable() {
@@ -133,10 +133,10 @@ protected:
 	Common::BitArray _enableFlags;
 	Common::Rect _mainArea;
 	Common::Rect _menuHotspots[4];
-	int8 _mainFrames[4]; //Frame to display of each main menu button; first row is currently displayed, 2nd row is backbuffer for idle animations
+	int8 _mainFrames[4]; // Frame to display of each main menu button; first row is currently displayed, 2nd row is backbuffer for idle animations
 	Scroller _mainScroller;
-	FocusList<int8> _menuFocus;  //Order in which menus have most recently had focus; determines current mouse focus & order in which to redraw them.
-	bool _clean = false; //Whether or not to blank
+	FocusList<int8> _menuFocus;  // Order in which menus have most recently had focus; determines current mouse focus & order in which to redraw them.
+	bool _clean = false; // Whether or not to blank
 	LinearScroller *_buttonAnim[4];
 };
 
@@ -144,7 +144,7 @@ class MenuZGI: public MenuManager {
 public:
 	MenuZGI(ZVision *engine, Common::Rect menuArea);
 	~MenuZGI() override;
-	void onMouseMove(const Common::Point &Pos) override;  //NB Pos is in screen coordinates
+	void onMouseMove(const Common::Point &Pos) override;  // NB Pos is in screen coordinates
 	void onMouseUp(const Common::Point &Pos) override;
 	void process(uint32 deltaTimeInMillis) override;
 	bool inMenu(const Common::Point &Pos) override;
diff --git a/engines/zvision/scripting/scr_file_handling.cpp b/engines/zvision/scripting/scr_file_handling.cpp
index dd5b6a56040..3c3786868bf 100644
--- a/engines/zvision/scripting/scr_file_handling.cpp
+++ b/engines/zvision/scripting/scr_file_handling.cpp
@@ -81,7 +81,7 @@ void ScriptManager::parseScrFile(const Common::Path &fileName, ScriptScope &scop
 	else {
 		debug(1, "Parsing primary script file");
 		parse(mainFile);
-		//TODO - add config option to disable/enable auxiliary scripting
+		// TODO - add config option to disable/enable auxiliary scripting
 		if (auxFile.exists(auxFilePath)) {
 			debug(1, "Auxiliary script file found");
 			if (auxFile.open(auxFilePath)) {
@@ -103,7 +103,7 @@ void ScriptManager::parsePuzzle(Puzzle *puzzle, Common::SeekableReadStream &stre
 			parseCriteria(stream, puzzle->criteriaList, puzzle->key);
 		} else if (line.matchString("results {", true)) {
 			parseResults(stream, puzzle->resultActions, puzzle->key);
-			//WORKAROUNDS:
+			// WORKAROUNDS:
 			switch (_engine->getGameId()) {
 			case GID_NEMESIS: {
 				// WORKAROUND for a script bug in Zork Nemesis, room ve5e (tuning
@@ -127,10 +127,10 @@ void ScriptManager::parsePuzzle(Puzzle *puzzle, Common::SeekableReadStream &stre
 					// run the player gets stuck in a dark room instead. We have
 					// to add the assignment action to the front, or it won't be
 					// reached because changing the location terminates the script.
-					//
+					// 
 					// Fixing it this way only keeps the bug from happening. It
 					// will not repair old savegames.
-					//
+					// 
 					// Note that the bug only affects the DVD version. The CD
 					// version doesn't have a separate room for the cutscene.
 					if (_engine->getFeatures() & ADGF_DVD)
@@ -182,7 +182,7 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 	// Create a new List to hold the CriteriaEntries
 	criteriaList.push_back(Common::List<Puzzle::CriteriaEntry>());
 
-	//WORKAROUNDS
+	// WORKAROUNDS
 	switch (_engine->getGameId()) {
 	case GID_NEMESIS:
 		// WORKAROUND for a script bug in Zork: Nemesis, room td9e (fist puzzle)
@@ -274,7 +274,7 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 		// than 10 units left, it will get stuck and never time out. We
 		// work around that by changing the condition from "greater than
 		// 10" to "greater than 0 but not 2 (the magic time-out value)".
-		//
+		// 
 		// I have a sneaking suspicion that there may be other timer
 		// glitches like this, but this one makes the game unplayable
 		// and is easy to trigger.
@@ -307,9 +307,9 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 	line.toLowercase();
 
 	// TODO: Re-order the if-then statements in order of highest occurrence
-	//While within results block
+	// While within results block
 	while (!stream.eos() && !line.contains('}')) {
-		//Skip empty lines
+		// Skip empty lines
 		if (line.empty()) {
 			line = stream.readLine();
 			trimCommentsAndWhiteSpace(&line);
@@ -320,7 +320,7 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 		const char *chrs = line.c_str();
 		uint pos;
 		/*/
-		        //Iterate along line until colon encountered
+		        // Iterate along line until colon encountered
 		        for (pos = 0; pos < line.size(); pos++) {
 		            if (chrs[pos] == ':')
 		                break;
@@ -334,19 +334,19 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 			pos = 10;
 		else
 			continue;
-//*/
-		if (pos < line.size()) {  //Stuff left
-			uint startpos = pos + 1;  //first character after colon
-			//Scan for next colon or opening bracket
+// */
+		if (pos < line.size()) {  // Stuff left
+			uint startpos = pos + 1;  // first character after colon
+			// Scan for next colon or opening bracket
 			for (pos = startpos; pos < line.size(); pos++)
 				if (chrs[pos] == ':' || chrs[pos] == '(')
 					break;
 
 			debug(4, "startpos %d, pos %d, line.size %d", startpos, pos, line.size());
-			int32 slot = 11;  //Non-setting default slot
+			int32 slot = 11;  // Non-setting default slot
 			Common::String args = "";
 			Common::String act(chrs + startpos, chrs + pos);
-			//Extract arguments, if any
+			// Extract arguments, if any
 			if (pos < line.size()) {
 
 				startpos = pos + 1;
@@ -355,7 +355,7 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 					for (pos = startpos; pos < line.size(); pos++)
 						if (chrs[pos] == '(')
 							break;
-					//Extract slotkey, if specified
+					// Extract slotkey, if specified
 					Common::String strSlot(chrs + startpos, chrs + pos);
 					slot = atoi(strSlot.c_str());
 
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index fb21868c90d..7c7fcb6c4f7 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -75,11 +75,11 @@ void ScriptManager::initialize(bool restarted) {
 		_referenceTable.clear();
 		switch (_engine->getGameId()) {
 		case GID_GRANDINQUISITOR:
-			//Bypass logo video
+			// Bypass logo video
 			setStateValue(16966, 1);
-			//Ensure post-logo screen redraw is not inhibited in CD version
+			// Ensure post-logo screen redraw is not inhibited in CD version
 			setStateValue(5813, 1);
-			//Bypass additional logo videos in DVD version
+			// Bypass additional logo videos in DVD version
 			setStateValue(19810, 1);
 			setStateValue(19848, 1);
 			break;
@@ -102,7 +102,7 @@ void ScriptManager::update(uint deltaTimeMillis) {
 		// triggered other scripts, so give them all one extra cycle to
 		// run. This fixes some missing scoring in ZGI, and quite
 		// possibly other minor glitches as well.
-		//
+		// 
 		// Another idea would be to change if there are pending scripts
 		// in the exec queues, but that could cause this to hang
 		// indefinitely.
@@ -633,7 +633,7 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 		}
 	}
 
-	//_engine->setRenderDelay(2); //Uncertain if this is necessary; doesn't seem to cause any problems when disabled, but keep an eye on it.
+	// _engine->setRenderDelay(2); // Uncertain if this is necessary; doesn't seem to cause any problems when disabled, but keep an eye on it.
 
 	if (!leavingMenu) {
 		if (!isLoading && !enteringMenu) {
@@ -761,8 +761,8 @@ void ScriptManager::serialize(Common::WriteStream *stream) {
 	stream->writeUint32BE(MKTAG('F', 'L', 'A', 'G'));
 
 	int32 slots = _engine->getGameId() == GID_NEMESIS ? 31000 : 21000;
-	//Original games use key values up to 29500 and 19737, respectively
-	//Values 30001~31000 and 20001~21000 are now set aside for auxiliary scripting to add extra directional audio effects.
+	// Original games use key values up to 29500 and 19737, respectively
+	// Values 30001~31000 and 20001~21000 are now set aside for auxiliary scripting to add extra directional audio effects.
 
 	stream->writeUint32LE(slots * 2);
 
diff --git a/engines/zvision/sound/midi.cpp b/engines/zvision/sound/midi.cpp
index 16f19002d3a..510ffaabd5d 100644
--- a/engines/zvision/sound/midi.cpp
+++ b/engines/zvision/sound/midi.cpp
@@ -81,7 +81,7 @@ void MidiManager::noteOff(uint8 channel) {
 }
 
 int8 MidiManager::getFreeChannel() {
-	uint8 start = _mt32 ? 1 : 0; //MT-32 can be used for MIDI, but does not play anything on MIDI channel 0
+	uint8 start = _mt32 ? 1 : 0; // MT-32 can be used for MIDI, but does not play anything on MIDI channel 0
 	for (uint8 i = start; i < 16; i++)
 		if (!_activeChannels[i].playing)
 			return i;
diff --git a/engines/zvision/sound/midi.h b/engines/zvision/sound/midi.h
index d285824ae44..1d4435723be 100644
--- a/engines/zvision/sound/midi.h
+++ b/engines/zvision/sound/midi.h
@@ -39,7 +39,7 @@ public:
 	void setPan(uint8 channel, int8 pan);
 	void setProgram(uint8 channel, uint8 prog);
 
-	int8 getFreeChannel();  //Negative if none available
+	int8 getFreeChannel();  // Negative if none available
 	bool isAvailable() {
 		return _available;
 	};
diff --git a/engines/zvision/sound/volume_manager.cpp b/engines/zvision/sound/volume_manager.cpp
index 474935b8b78..a2733705967 100644
--- a/engines/zvision/sound/volume_manager.cpp
+++ b/engines/zvision/sound/volume_manager.cpp
@@ -25,7 +25,7 @@
 
 namespace ZVision {
 
-//Power law with exponent 1.5.
+// Power law with exponent 1.5.
 static constexpr uint8 powerLaw[256] = {
   0,  0,  0,  0,  1,  1,  1,  1,  1,  2,  2,  2,  3,  3,  3,  4, 
   4,  4,  5,  5,  6,  6,  6,  7,  7,  8,  8,  9,  9, 10, 10, 11,
@@ -64,7 +64,7 @@ static constexpr uint8 logPower[256] = {
 113,119,126,133,140,148,156,165,174,184,194,205,217,229,241,255
 };
 
-//*/
+// */
 static constexpr uint8 logAmplitude[256] = {
   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  
   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1,  
@@ -104,7 +104,7 @@ static constexpr uint8 logAmplitude[256] = {
  83, 86, 89, 92, 96, 99,103,107,111,115,119,123,128,133,137,143,
 148,153,159,165,171,177,184,191,198,205,212,220,228,237,245,255
 };
-//*/
+// */
 
 /*
 Estimated relative amplitude of a point sound source as it circles the listener's head from front to rear, due to ear pinna shape.
diff --git a/engines/zvision/sound/volume_manager.h b/engines/zvision/sound/volume_manager.h
index eacbd2067c3..24cb4cf867b 100644
--- a/engines/zvision/sound/volume_manager.h
+++ b/engines/zvision/sound/volume_manager.h
@@ -54,7 +54,7 @@ public:
 	uint8 convert(uint8 inputValue, volumeScaling mode, Math::Angle azimuth, uint8 directionality = 255);
 private:
 	ZVision *_engine;
-	uint _scriptScale = 100; //Z-Vision scripts internally use a volume scale of 0-100; ScummVM uses a scale of 0-255.
+	uint _scriptScale = 100; // Z-Vision scripts internally use a volume scale of 0-100; ScummVM uses a scale of 0-255.
 	volumeScaling _mode = kVolumeLinear;
 };
 
diff --git a/engines/zvision/text/subtitle_manager.cpp b/engines/zvision/text/subtitle_manager.cpp
index 4a7dc96e905..3fe225b6456 100644
--- a/engines/zvision/text/subtitle_manager.cpp
+++ b/engines/zvision/text/subtitle_manager.cpp
@@ -41,7 +41,7 @@ SubtitleManager::SubtitleManager(ZVision *engine, const ScreenLayout layout, con
 }
 
 SubtitleManager::~SubtitleManager() {
-	//Delete all subtitles referenced in subslist
+	// Delete all subtitles referenced in subslist
 	for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
 		delete it->_value;
 		_subsList.erase(it);
@@ -51,10 +51,10 @@ SubtitleManager::~SubtitleManager() {
 
 void SubtitleManager::process(int32 deltatime) {
 	for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
-		//Update all automatic subtitles
+		// Update all automatic subtitles
 		if (it->_value->selfUpdate())
 			_redraw = true;
-		//Update all subtitles' respective deletion timers
+		// Update all subtitles' respective deletion timers
 		if (it->_value->process(deltatime)) {
 			debug(4, "Deleting subtitle, subId=%d", it->_key);
 			_subsFocus.remove(it->_key);
@@ -71,9 +71,9 @@ void SubtitleManager::process(int32 deltatime) {
 		}
 	if (_redraw) {
 		debug(4, "Redrawing subtitles");
-		//Blank subtitle buffer
+		// Blank subtitle buffer
 		_renderManager->clearTextSurface();
-		//Render just the most recent subtitle
+		// Render just the most recent subtitle
 		if (_subsFocus.size()) {
 			uint16 curSub = _subsFocus.front();
 			debug(4, "Rendering subtitle %d", curSub);
@@ -81,7 +81,7 @@ void SubtitleManager::process(int32 deltatime) {
 			if (sub->_lineId >= 0) {
 				Graphics::Surface textSurface;
 				textSurface.create(sub->_textArea.width(), sub->_textArea.height(), _engine->_resourcePixelFormat);
-				textSurface.fillRect(Common::Rect(sub->_textArea.width(), sub->_textArea.height()), -1); //TODO Unnecessary operation?  Check later.
+				textSurface.fillRect(Common::Rect(sub->_textArea.width(), sub->_textArea.height()), -1); // TODO Unnecessary operation?  Check later.
 				_engine->getTextRenderer()->drawTextWithWordWrapping(sub->_lines[sub->_lineId].subStr, textSurface, _engine->isWidescreen());
 				_renderManager->blitSurfaceToText(textSurface, sub->_textArea.left, sub->_textArea.top, -1);
 				textSurface.free();
@@ -95,7 +95,7 @@ void SubtitleManager::process(int32 deltatime) {
 void SubtitleManager::update(int32 count, uint16 subid) {
 	if (_subsList.contains(subid))
 		if (_subsList[subid]->update(count)) {
-			//_subsFocus.set(subid);
+			// _subsFocus.set(subid);
 			_redraw = true;
 		}
 }
@@ -251,7 +251,7 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool vob) :
 	Common::File subFile;
 	Common::Point _textOffset = _engine->getSubtitleManager()->getTextOffset();
 	if (_engine->getSearchManager()->openFile(subFile, subname)) {
-		//Parse subtitle parameters from script
+		// Parse subtitle parameters from script
 		while (!subFile.eos()) {
 			Common::String str = subFile.readLine();
 			if (str.lastChar() == '~')
@@ -263,10 +263,10 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool vob) :
 				sscanf(str.c_str(), "%*[^:]:%d %d %d %d", &x1, &y1, &x2, &y2);
 				_textArea = Common::Rect(x1, y1, x2, y2);
 				debug(1, "Original subtitle script rectangle coordinates: l%d, t%d, r%d, b%d", x1, y1, x2, y2);
-				//Original game subtitle scripts appear to define subtitle rectangles relative to origin of working area.
-				//To allow arbitrary aspect ratios, we need to instead place these relative to origin of text area.
-				//This will allow the managed text area to then be arbitrarily placed on the screen to suit different aspect ratios.
-				_textArea.translate(_textOffset.x, _textOffset.y);  //Convert working area coordinates to text area coordinates
+				// Original game subtitle scripts appear to define subtitle rectangles relative to origin of working area.
+				// To allow arbitrary aspect ratios, we need to instead place these relative to origin of text area.
+				// This will allow the managed text area to then be arbitrarily placed on the screen to suit different aspect ratios.
+				_textArea.translate(_textOffset.x, _textOffset.y);  // Convert working area coordinates to text area coordinates
 				debug(1, "Text area coordinates: l%d, t%d, r%d, b%d", _textArea.left, _textArea.top, _textArea.right, _textArea.bottom);
 			} else if (str.matchString("*TextFile*", true)) {
 				char filename[64];
@@ -284,16 +284,16 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool vob) :
 					txtFile.close();
 				}
 			} else {
-				int32 st; //Line start time
-				int32 en; //Line end time
-				int32 sb; //Line number
+				int32 st; // Line start time
+				int32 en; // Line end time
+				int32 sb; // Line number
 				if (sscanf(str.c_str(), "%*[^:]:(%d,%d)=%d", &st, &en, &sb) == 3) {
 					if (sb <= (int32)_lines.size()) {
 						if (vob) {
 							// Convert frame number from 15FPS (AVI) to 29.97FPS (VOB) to synchronise with video
-							//st = st * 2997 / 1500;
-							//en = en * 2997 / 1500;
-							st = st * 2900 / 1500;  //TODO: Subtitles only synchronise correctly at 29fps, but vob files should be 29.97fps; check if video codec is rounding this value down!
+							// st = st * 2997 / 1500;
+							// en = en * 2997 / 1500;
+							st = st * 2900 / 1500;  // TODO: Subtitles only synchronise correctly at 29fps, but vob files should be 29.97fps; check if video codec is rounding this value down!
 							en = en * 2900 / 1500;
 						}
 						_lines[sb].start = st;
@@ -304,7 +304,7 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool vob) :
 		}
 		subFile.close();
 	} else {
-		//TODO - add error message here
+		// TODO - add error message here
 		_toDelete = true;
 	}
 }
@@ -339,24 +339,24 @@ bool Subtitle::process(int32 deltatime) {
 
 bool Subtitle::update(int32 count) {
 	int16 j = -1;
-	//Search all lines to find first line that encompasses current time/framecount, set j to this
+	// Search all lines to find first line that encompasses current time/framecount, set j to this
 	for (uint16 i = (_lineId >= 0 ? _lineId : 0); i < _lines.size(); i++)
 		if (count >= _lines[i].start && count <= _lines[i].stop) {
 			j = i;
 			break;
 		}
 	if (j == -1) {
-		//No line exists for current time/framecount
+		// No line exists for current time/framecount
 		if (_lineId != -1) {
-			//Line is set
-			_lineId = -1; //Unset line
+			// Line is set
+			_lineId = -1; // Unset line
 			_redraw = true;
 		}
 	} else {
-		//Line exists for current time/framecount
+		// Line exists for current time/framecount
 		if (j != _lineId && _lines[j].subStr.size()) {
-			//Set line is not equal to current line & current line is not blank
-			_lineId = j;  //Set line to current
+			// Set line is not equal to current line & current line is not blank
+			_lineId = j;  // Set line to current
 			_redraw = true;
 		}
 	}
diff --git a/engines/zvision/text/subtitle_manager.h b/engines/zvision/text/subtitle_manager.h
index aa6a48b199c..bd74be78f7c 100644
--- a/engines/zvision/text/subtitle_manager.h
+++ b/engines/zvision/text/subtitle_manager.h
@@ -33,20 +33,20 @@ class ZVision;
 class Subtitle {
 	friend class SubtitleManager;
 public:
-	Subtitle(ZVision *engine, const Common::Path &subname, bool vob = false); //For scripted subtitles
-	Subtitle(ZVision *engine, const Common::String &str, const Common::Rect &textArea);  //For other text messages
+	Subtitle(ZVision *engine, const Common::Path &subname, bool vob = false); // For scripted subtitles
+	Subtitle(ZVision *engine, const Common::String &str, const Common::Rect &textArea);  // For other text messages
 	virtual ~Subtitle();
-	bool update(int32 count); //Return true if necessary to redraw
+	bool update(int32 count); // Return true if necessary to redraw
 	virtual bool selfUpdate() {
 		return false;
 	};
 
 protected:
-	virtual bool process(int32 deltatime);  //Return true if to be deleted
+	virtual bool process(int32 deltatime);  // Return true if to be deleted
 	ZVision *_engine;
 	Common::Rect _textArea;
-	//Common::String _txt;
-	int16 _timer; //Always in milliseconds; countdown to deletion
+	// Common::String _txt;
+	int16 _timer; // Always in milliseconds; countdown to deletion
 	bool _toDelete;
 	bool _redraw;
 
@@ -56,23 +56,23 @@ protected:
 		int stop;
 		Common::String subStr;
 	};
-	//NB: start & stop do not always use the same units between different instances of this struct!
-	//Sound effect & music subtitles use milliseconds
-	//Video subtitle timings are specified in video frames at 15fps, i.e. in multiples of 66.6' milliseconds!
-	//AVI videos run at 15fps and can have frames counted directly
-	//DVD videos in VOB format run at 29.97 fps and must be converted to work with the subtitle files, which were made for AVI.
+	// NB: start & stop do not always use the same units between different instances of this struct!
+	// Sound effect & music subtitles use milliseconds
+	// Video subtitle timings are specified in video frames at 15fps, i.e. in multiples of 66.6' milliseconds!
+	// AVI videos run at 15fps and can have frames counted directly
+	// DVD videos in VOB format run at 29.97 fps and must be converted to work with the subtitle files, which were made for AVI.
 
 	Common::Array<Line> _lines;
 };
 
 class AutomaticSubtitle : public Subtitle {
 public:
-	AutomaticSubtitle(ZVision *engine, const Common::Path &subname, Audio::SoundHandle handle);  //For scripted audio subtitles
+	AutomaticSubtitle(ZVision *engine, const Common::Path &subname, Audio::SoundHandle handle);  // For scripted audio subtitles
 	~AutomaticSubtitle() {};
 
 private:
-	bool process(int32 deltatime);  //Return true if to be deleted
-	bool selfUpdate(); //Return true if necessary to redraw
+	bool process(int32 deltatime);  // Return true if to be deleted
+	bool selfUpdate(); // Return true if necessary to redraw
 	Audio::SoundHandle _handle;
 };
 
@@ -85,7 +85,7 @@ private:
 	OSystem *_system;
 	RenderManager *_renderManager;
 	const Graphics::PixelFormat _pixelFormat;
-	const Common::Point _textOffset;  //Position vector of text area origin relative to working window origin
+	const Common::Point _textOffset;  // Position vector of text area origin relative to working window origin
 	const Common::Rect _textArea;
 	bool _redraw;
 	bool _doubleFPS;
@@ -100,10 +100,10 @@ private:
 	FocusList<uint16> _subsFocus;
 
 public:
-	//Update all subtitle objects' deletion timers, delete expired subtitles, & redraw most recent.  Does NOT update any subtitle's count value or displayed string!
-	void process(int32 deltatime);  //deltatime is always milliseconds
-	//Update counter value of referenced subtitle id & set current line to display, if any.
-	void update(int32 count, uint16 subid);  //Count is milliseconds for sound & music; frames for video playback.
+	// Update all subtitle objects' deletion timers, delete expired subtitles, & redraw most recent.  Does NOT update any subtitle's count value or displayed string!
+	void process(int32 deltatime);  // deltatime is always milliseconds
+	// Update counter value of referenced subtitle id & set current line to display, if any.
+	void update(int32 count, uint16 subid);  // Count is milliseconds for sound & music; frames for video playback.
 
 	Common::Point getTextOffset() {
 		return _textOffset;
@@ -111,7 +111,7 @@ public:
 
 	// Create subtitle object and return ID
 	uint16 create(const Common::Path &subname, bool vob = false);
-	uint16 create(const Common::Path &subname, Audio::SoundHandle handle);  //NB this creates an automatic subtitle
+	uint16 create(const Common::Path &subname, Audio::SoundHandle handle);  // NB this creates an automatic subtitle
 	uint16 create(const Common::String &str);
 
 	// Delete subtitle object by ID
diff --git a/engines/zvision/text/text.cpp b/engines/zvision/text/text.cpp
index 40aa80da165..2b4bbff6587 100644
--- a/engines/zvision/text/text.cpp
+++ b/engines/zvision/text/text.cpp
@@ -342,9 +342,9 @@ void TextRenderer::drawTextWithWordWrapping(const Common::String &text, Graphics
 	uint i = 0u;
 	uint stringlen = text.size();
 
-	//Parse entirety of supplied text
+	// Parse entirety of supplied text
 	while (i < stringlen) {
-		//Style tag encountered?
+		// Style tag encountered?
 		if (text[i] == '<') {
 			// Flush the currentWord to the currentSentence
 			currentSentence += currentWord;
diff --git a/engines/zvision/video/video.cpp b/engines/zvision/video/video.cpp
index f06913ac165..122bec40089 100644
--- a/engines/zvision/video/video.cpp
+++ b/engines/zvision/video/video.cpp
@@ -88,7 +88,7 @@ void ZVision::playVideo(Video::VideoDecoder &vid, Common::Rect dstRect, bool ski
 	Common::Rect workingArea = _renderManager->getWorkingArea();
 	// If dstRect is empty, no specific scaling was requested. However, we may choose to do scaling anyway
 	bool scaled = false;
-	workingArea.moveTo(0, 0); //Set local origin system in this scope to origin of working area
+	workingArea.moveTo(0, 0); // Set local origin system in this scope to origin of working area
 
 	debug(1, "Playing video, source %d,%d,%d,%d, at destination %d,%d,%d,%d", srcRect.left, srcRect.top, srcRect.right, srcRect.bottom, dstRect.left, dstRect.top, dstRect.right, dstRect.bottom);
 
@@ -155,7 +155,7 @@ void ZVision::playVideo(Video::VideoDecoder &vid, Common::Rect dstRect, bool ski
 				_subtitleManager->update(vid.getCurFrame(), sub);
 
 			if (frame) {
-				_renderManager->renderSceneToScreen(true, true, true); //Redraw text area to clean background of subtitles for videos that don't fill entire working area, e.g, Nemesis sarcophagi
+				_renderManager->renderSceneToScreen(true, true, true); // Redraw text area to clean background of subtitles for videos that don't fill entire working area, e.g, Nemesis sarcophagi
 				if (scaled) {
 					debug(8, "Scaled blit from area %d x %d to video output surface at output surface position %d, %d", srcRect.width(), srcRect.height(), dstRect.left, dstRect.top);
 					outSurface.blitFrom(*frame, srcRect, dstRect);
@@ -170,7 +170,7 @@ void ZVision::playVideo(Video::VideoDecoder &vid, Common::Rect dstRect, bool ski
 		// Always update the screen so the mouse continues to render & video does not skip
 		_renderManager->renderSceneToScreen(true, true, false);
 
-		_system->delayMillis(vid.getTimeToNextFrame() / 2); //Exponentially decaying delay
+		_system->delayMillis(vid.getTimeToNextFrame() / 2); // Exponentially decaying delay
 	}
 
 	_cutscenesKeymap->setEnabled(false);
@@ -187,7 +187,7 @@ double ZVision::getVobAmplification(Common::String fileName) const {
 	// in the low-res ones. So we artificially boost the volume. This is an
 	// approximation, but I've tried to match the old volumes reasonably
 	// well.
-	//
+	// 
 	// Some of these will cause audio clipping. Hopefully not enough to be
 	// noticeable.
 	double amplification = 0.0;
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index ae6ed4ecb0a..a2ae4cd4fa6 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -180,7 +180,7 @@ void ZVision::saveSettings() {
 }
 
 void ZVision::initialize() {
-	//File Paths
+	// File Paths
 	const Common::FSNode gameDataDir(ConfMan.getPath("path"));
 
 	_searchManager = new SearchManager(ConfMan.getPath("path"), 6);
@@ -204,11 +204,11 @@ void ZVision::initialize() {
 		break;
 	}
 
-	//Graphics
+	// Graphics
 	_widescreen = ConfMan.getBool("widescreen");
 	_doubleFPS = ConfMan.getBool("doublefps");
 
-	//Keymaps
+	// Keymaps
 
 	Common::Keymapper *keymapper = _system->getEventManager()->getKeymapper();
 	_gameKeymap = keymapper->getKeymap(gameKeymapId);
@@ -266,7 +266,7 @@ void ZVision::initialize() {
 
 	// Initialize FPS timer callback
 	getTimerManager()->installTimerProc(&fpsTimerCallback, 1000000, this, "zvisionFPS");
-	//Ensure a new game is launched with correct panorama quality setting
+	// Ensure a new game is launched with correct panorama quality setting
 	_scriptManager->setStateValue(StateKey_HighQuality, ConfMan.getBool("highquality"));
 }
 
@@ -351,15 +351,15 @@ Common::Error ZVision::run() {
 	while (!shouldQuit()) {
 		debug(5, "\nInitiating new game cycle");
 		debug(5, "Timers");
-		//Timers
+		// Timers
 		_clock.update();
 		uint32 deltaTime = _clock.getDeltaTime();
 		debug(5, "Logic");
-		//Process game logic & update backbuffers as necessary
+		// Process game logic & update backbuffers as necessary
 		debug(5, "Cursor");
 		_cursorManager->setItemID(_scriptManager->getStateValue(StateKey_InventoryItem));
 		debug(5, "Events");
-		processEvents();  //NB rotateTo or playVideo event will pause clock & call renderSceneToScreen() directly.
+		processEvents();  // NB rotateTo or playVideo event will pause clock & call renderSceneToScreen() directly.
 		debug(5, "Rotation");
 		_renderManager->updateRotation();
 		debug(5, "Scripts");
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index 32fc54ef491..ac924e9e8e3 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -71,48 +71,48 @@ class MidiManager;
 class VolumeManager;
 
 struct ScreenLayout {
-	Common::Rect screenArea;  //Original screen resolution
-	Common::Rect menuArea;  //Menu display area, relative to original screen
-	Common::Rect workingArea;   //Playfield & video playback area, relative to original screen
-	Common::Rect textArea;  //Subtitle & message area, relative to original screen
+	Common::Rect screenArea;  // Original screen resolution
+	Common::Rect menuArea;  // Menu display area, relative to original screen
+	Common::Rect workingArea;   // Playfield & video playback area, relative to original screen
+	Common::Rect textArea;  // Subtitle & message area, relative to original screen
 };
 
-//NB Footage of original DOS Nemesis engine indicates playfield was centrally placed on screen.
-//Subtitle scripts, however, suggest playfield was higher up, otherwise they run off the bottom of the screen.  Could just be an error in the scripts.
-//TODO Need to make a decision how to handle this.  Should be irrelevant for widescreen mode anyway, & purists will want original appearance for 4:3 ratio.
-//Figures below currently have playfield offset to fit subtitles entirely in lower bar
+// NB Footage of original DOS Nemesis engine indicates playfield was centrally placed on screen.
+// Subtitle scripts, however, suggest playfield was higher up, otherwise they run off the bottom of the screen.  Could just be an error in the scripts.
+// TODO Need to make a decision how to handle this.  Should be irrelevant for widescreen mode anyway, & purists will want original appearance for 4:3 ratio.
+// Figures below currently have playfield offset to fit subtitles entirely in lower bar
 
 /*/
-//Vertically offset values
+// Vertically offset values
 static const ScreenLayout nemesisLayout {
-  Common::Rect(640,480),  //Screen
-  Common::Rect(Common::Point(64,0), 512, 32), //Menu
-  Common::Rect(Common::Point(64,40), 512, 320), //Working; aspect ratio 1.6
-  Common::Rect(Common::Point(64,380), 512, 100) //Text
+  Common::Rect(640,480),  // Screen
+  Common::Rect(Common::Point(64,0), 512, 32), // Menu
+  Common::Rect(Common::Point(64,40), 512, 320), // Working; aspect ratio 1.6
+  Common::Rect(Common::Point(64,380), 512, 100) // Text
 };
 static const ScreenLayout zgiLayout {
-  Common::Rect(640,480),  //Screen
-  Common::Rect(Common::Point(0,0), 640, 32), //Menu
-  Common::Rect(Common::Point(0,40), 640, 344), //Working; aspect ratio 1.86
-  Common::Rect(Common::Point(0,400), 640, 80) //Text
+  Common::Rect(640,480),  // Screen
+  Common::Rect(Common::Point(0,0), 640, 32), // Menu
+  Common::Rect(Common::Point(0,40), 640, 344), // Working; aspect ratio 1.86
+  Common::Rect(Common::Point(0,400), 640, 80) // Text
 };
-//*/
-//*/
-//Central values
+// */
+// */
+// Central values
 static const ScreenLayout nemesisLayout {
-	Common::Rect(640, 480), //Screen
-	Common::Rect(Common::Point(64, 0), 512, 32), //Menu
-	Common::Rect(Common::Point(64, 80), 512, 320), //Working; aspect ratio 1.6
-	Common::Rect(Common::Point(64, 420), 512, 60) //Text
+	Common::Rect(640, 480), // Screen
+	Common::Rect(Common::Point(64, 0), 512, 32), // Menu
+	Common::Rect(Common::Point(64, 80), 512, 320), // Working; aspect ratio 1.6
+	Common::Rect(Common::Point(64, 420), 512, 60) // Text
 };
 
 static const ScreenLayout zgiLayout {
-	Common::Rect(640, 480), //Screen
-	Common::Rect(Common::Point(0, 0), 640, 32), //Menu
-	Common::Rect(Common::Point(0, 68), 640, 344), //Working; aspect ratio 1.86
-	Common::Rect(Common::Point(0, 412), 640, 68) //Text
+	Common::Rect(640, 480), // Screen
+	Common::Rect(Common::Point(0, 0), 640, 32), // Menu
+	Common::Rect(Common::Point(0, 68), 640, 344), // Working; aspect ratio 1.86
+	Common::Rect(Common::Point(0, 412), 640, 68) // Text
 };
-//*/
+// */
 enum {
 
 	ROTATION_SCREEN_EDGE_OFFSET = 60,
@@ -265,7 +265,7 @@ public:
 	 *
 	 * @param videoDecoder    The video to play
 	 * @param destRect        Where to put the video. (In working window coords)
-	 * @param srcRect         What subset of video to blit to destRect (In video frame coords)  //TODO implement
+	 * @param srcRect         What subset of video to blit to destRect (In video frame coords)  // TODO implement
 	 * @param skippable       If true, the video can be skipped at any time using [Spacebar]
 	 */
 	void playVideo(Video::VideoDecoder &videoDecoder, Common::Rect destRect = Common::Rect(0, 0, 0, 0), bool skippable = true, uint16 sub = 0, Common::Rect srcRect = Common::Rect(0, 0, 0, 0));


Commit: 08e9f0c53306b0a96e51925da04901159bfadb90
    https://github.com/scummvm/scummvm/commit/08e9f0c53306b0a96e51925da04901159bfadb90
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:00+02:00

Commit Message:
ZVISION: Code formatting compliance.

Changed paths:
    engines/zvision/graphics/render_table.cpp


diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index 08d9b9dbe3b..70f8d50ff08 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -15,7 +15,7 @@
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ * along with this program.  If not, see <http:// www.gnu.org/licenses/>.
  *
  */
 
@@ -92,7 +92,7 @@ const Common::Point RenderTable::convertWarpedCoordToFlatCoord(const Common::Poi
 	return newPoint;
 }
 
-//Disused at present; potentially useful for future rendering efficient improvements.
+// Disused at present; potentially useful for future rendering efficient improvements.
 /*/
 void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 destWidth, const Common::Rect &subRect) {
     uint32 destOffset = 0;


Commit: c8dca7190b957fa3d96ea67323e9110099a22086
    https://github.com/scummvm/scummvm/commit/c8dca7190b957fa3d96ea67323e9110099a22086
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:00+02:00

Commit Message:
GRAPHICS: Code formatting compliance.

Changed paths:
    graphics/blit/blit.cpp
    graphics/framelimiter.cpp
    graphics/framelimiter.h


diff --git a/graphics/blit/blit.cpp b/graphics/blit/blit.cpp
index 4940e656d69..1b57aeb80a8 100644
--- a/graphics/blit/blit.cpp
+++ b/graphics/blit/blit.cpp
@@ -36,15 +36,15 @@ void copyBlit(byte *dst, const byte *src,
 		return;
 
 	if (dstPitch == srcPitch && ((w * bytesPerPixel) == dstPitch)) {
-	  //Buffers have equal line pitch AND total number of bytes per line matches that pitch
-	  //Therefore we may copy a whole subset of h full-width raster lines in one go.
+	  // Buffers have equal line pitch AND total number of bytes per line matches that pitch
+	  // Therefore we may copy a whole subset of h full-width raster lines in one go.
 		memcpy(dst, src, dstPitch * h);
 	} else {
-	  //Not transferring whole width of either source or destination buffer, therefore must copy line-by-line
+	  // Not transferring whole width of either source or destination buffer, therefore must copy line-by-line
 		for (uint i = 0; i < h; ++i) {
-		  //Copy sublength w of one full buffer raster line
+		  // Copy sublength w of one full buffer raster line
 			memcpy(dst, src, w * bytesPerPixel);
-			//iterate both buffer pointers by respective pitch to horizontally align starting point of next raster line with that of the one just copied
+			// Iterate both buffer pointers by respective pitch, to horizontally align starting point of next raster line with that of the one just copied
 			dst += dstPitch;
 			src += srcPitch;
 		}
diff --git a/graphics/framelimiter.cpp b/graphics/framelimiter.cpp
index a1f9bf610fe..0365098d39d 100644
--- a/graphics/framelimiter.cpp
+++ b/graphics/framelimiter.cpp
@@ -62,18 +62,18 @@ bool FrameLimiter::delayBeforeSwap() {
 	_now = _system->getMillis();
 	_loopDuration = _now - _frameStart;
 	if (_enabled) {
-		//_delay = _frameLimit - _loopDuration;  //Original functionality, will tend to undershoot target framerate slightly due to finite screen.update() time.
-		_delay = _frameLimit - (_now - _drawStart); //Ensure EXACTLY the specified frame duration has elapsed since last screen.update() was called.
+		//_delay = _frameLimit - _loopDuration;  // Original functionality, will tend to undershoot target framerate slightly due to finite screen.update() time.
+		_delay = _frameLimit - (_now - _drawStart); // Ensure that EXACTLY the specified frame duration has elapsed since last screen.update() was called.
 		if (_delay > 0)
 			_system->delayMillis(_delay);
 	}
 	_drawStart = _system->getMillis();
-	return (_delay < 0); //Check if frame is late
+	return (_delay < 0); // Check if frame is late
 }
 
 void FrameLimiter::pause(bool pause) {
 	if (!pause)
-		_frameStart = 0; // Ensure the frame duration value is consistent when resuming
+		_frameStart = 0; // Ensure that the frame duration value is consistent when resuming
 }
 
 } // End of namespace Graphics
diff --git a/graphics/framelimiter.h b/graphics/framelimiter.h
index 96bd29be2c5..91aeab134e5 100644
--- a/graphics/framelimiter.h
+++ b/graphics/framelimiter.h
@@ -96,14 +96,14 @@ private:
 
 	bool _enabled;
 	bool _deferToVsync;
-	uint _frameStart;  //Time at which screen update completed and startFrame() was called; start of next cycle of game logic
-	uint _frameLimit;  //Target frame duration to achieve specified FPS
-	uint _frameDuration; //Duration of previous frame between successive startFrame() calls; total game logic, delay (if any) and screen update time
-	uint _drawStart;  //Time at which delayBeforeSwap() returns
-	uint _drawDuration;  //Measured screen update time
-	uint _loopDuration;  //Duration of last game logic cycle, from when startFrame() was called to when delayBeforeSwap() was called
-	int _delay; //Time to delay before returning from delayBeforeSwap()
-	uint _now; //Current time
+	uint _frameStart;  // Time at which screen update completed and startFrame() was called; start of next cycle of game logic
+	uint _frameLimit;  // Target frame duration to achieve specified FPS
+	uint _frameDuration; // Duration of previous frame between successive startFrame() calls; total game logic, delay (if any) and screen update time
+	uint _drawStart;  // Time at which delayBeforeSwap() returns
+	uint _drawDuration;  // Measured screen update time
+	uint _loopDuration;  // Duration of last game logic cycle, from when startFrame() was called to when delayBeforeSwap() was called
+	int _delay; // Time to delay before returning from delayBeforeSwap()
+	uint _now; // Current time
 };
 
 } // End of namespace Graphics


Commit: e0012a065161fc6f7edfb04e2527f93ee8c50551
    https://github.com/scummvm/scummvm/commit/e0012a065161fc6f7edfb04e2527f93ee8c50551
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:00+02:00

Commit Message:
ZVISION: Code formatting compliance.
Removal of vestigial development code.
Clarification of some comments.

Changed paths:
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/actions.h
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/scr_file_handling.cpp
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/text/subtitle_manager.h
    engines/zvision/zvision.h


diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index 70f8d50ff08..a1aa6c5321e 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -160,13 +160,6 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 				_bF = _curP._fTL * _bTL + _curP._fTR * _bTR + _curP._fBL * _bBL + _curP._fBR * _bBR;
 				destBuffer[_destOffset] = mergeColor(_rF, _gF, _bF);
 				_destOffset++;
-				/*/
-				if(Common::Point(x,y)==testPixel) {
-				debug(2,"\tMutated test pixel %d, %d", x, y);
-				debug(2,"\t_fX: %f, _fY: %f", _curP._fX, _curP._fY);
-				debug(2,"\tYT: %d, YB: %d, XL: %d XR: %d", _srcIndexYT, _srcIndexYB, _srcIndexXL, _srcIndexXR);
-				}
-				// */
 			}
 		}
 	} else {
@@ -229,15 +222,6 @@ void RenderTable::generateLookupTable(bool tilt) {
 		linearCoordInCylinderCoords = halfLinearSize + ((float)linearCoord - halfLinearSize) * cosAlpha;
 		linearOffset = linearCoordInCylinderCoords - linearCoord;
 		polarOffset = polarCoordInCylinderCoords - polarCoord;
-		/*
-		    bool _printDebug = (Common::Point(x,y)==testPixel);
-		    if(_printDebug) {
-		      debug(5,"\tGenerating test pixel %d, %d", x, y);
-		      debug(5,"\tOffsets %f,%f", xOffset, yOffset);
-		    }
-		*/
-		// Only store the (x,y) offsets instead of the absolute positions
-// 		_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality, _printDebug);
 		_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality);
 		// Transformation is both horizontally and vertically symmetrical about the camera axis,
 		// We can thus save on trigonometric calculations by computing one quarter of the transformation matrix and then mirroring it in both X & Y:
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index 92494d19d06..2119f94ac4c 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -37,21 +37,13 @@ public:
 	Common::Rect _Src = Common::Rect(0, 0); // Coordinates of four panorama image pixels around actual working window pixel
 
 	float _fX, _fY, _fTL, _fTR, _fBL, _fBR;
-
-// bool _printDebug = false;
-
+	
 	FilterPixel() {}
-// FilterPixel(float x, float y, bool highQuality=false, bool printDebug=false) {
 	FilterPixel(float x, float y, bool highQuality = false) {
 		_Src.left = int16(floor(x));
 		_Src.right = int16(ceil(x));
 		_Src.top = int16(floor(y));
 		_Src.bottom = int16(ceil(y));
-		/*
-		      _printDebug = printDebug;
-		    if(_printDebug)
-		      debug(5,"\tTarget pixel offset: %f, %f", x, y);
-		*/
 		if (highQuality) {
 			_fX = x - (float)_Src.left;
 			_fY = y - (float)_Src.top;
@@ -59,18 +51,10 @@ public:
 			_fTR = _fX * (1 - _fY);
 			_fBL = (1 - _fX) * _fY;
 			_fBR = _fX * _fY;
-			/*
-			      if(_printDebug)
-			        debug(5,"_fX: %f, _fY: %f, _fTL:%f, _fTR:%f, _fBL:%f, _fBR:%f", _fX, _fY, _fTL, _fTR, _fBL, _fBR);
-			*/
 		} else {
 			// Nearest neighbour
 			_xDir = (x - _Src.left) > 0.5f;
 			_yDir = (y - _Src.top) > 0.5f;
-			/*
-			      if(_printDebug)
-			        debug(5,"\tNearest neighbour, _xDir: 0x%X, _yDir: 0x%X", _xDir, _yDir);
-			*/
 		}
 	}
 	~FilterPixel() {}
@@ -133,7 +117,6 @@ private:
 		uint16 zeroPoint;
 	} _panoramaOptions;
 
-	// TODO: See if tilt and panorama need to have separate options
 	struct {
 		float verticalFOV;  // Radians
 		float linearScale;
@@ -185,7 +168,6 @@ public:
 private:
 	void generateLookupTable(bool tilt = false);
 	void generatePanoramaLookupTable();
-// Common::Point generatePanoramaLookupPoint();
 	void generateTiltLookupTable();
 };
 
diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index 0b2e096a18d..3b0ec073e74 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -53,9 +53,9 @@ ResultAction::ResultAction(ZVision *engine, int32 slotKey) :
 	_scriptManager(engine->getScriptManager()) {
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionAdd
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionAdd::ActionAdd(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -76,9 +76,9 @@ bool ActionAdd::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionAssign
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionAssign::ActionAssign(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -100,11 +100,11 @@ bool ActionAssign::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionAttenuate
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
-//TODO - the effects of this seem permanent until the musicnode is deleted; check if they should only be applied on a per-cycle basis!
+// TODO: the effects of this seem permanent until the music node is deleted; check if they should only be applied on a per-cycle basis!
 
 ActionAttenuate::ActionAttenuate(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -122,14 +122,15 @@ bool ActionAttenuate::execute() {
 	ScriptingEffect *fx = _scriptManager->getSideFX(_key);
 	if (fx && fx->getType() == ScriptingEffect::SCRIPTING_EFFECT_AUDIO) {
 		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
-		mus->setVolume((10000 - abs(_attenuation)) / 100);  //TODO - verify that this is working correctly.
+		mus->setVolume((10000 - abs(_attenuation)) / 100);  // TODO - verify that this is working correctly
+		// Given that the scripts specify this effect in negative values of several, thousand, it is possible the original system may have multiplied by a factor defined in milli-decibels or similar.  Further investigation & comparison with the audio output in various locations from the original executables could shed more light on this.
 	}
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionChangeLocation
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionChangeLocation::ActionChangeLocation(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -148,9 +149,9 @@ bool ActionChangeLocation::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionCrossfade
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionCrossfade::ActionCrossfade(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -195,9 +196,9 @@ bool ActionCrossfade::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionCursor
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionCursor::ActionCursor(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -227,9 +228,9 @@ bool ActionCursor::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionDelayRender
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionDelayRender::ActionDelayRender(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -246,9 +247,9 @@ bool ActionDelayRender::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionDisableControl
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionDisableControl::ActionDisableControl(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -262,9 +263,9 @@ bool ActionDisableControl::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionDisplayMessage
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionDisplayMessage::ActionDisplayMessage(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -283,9 +284,9 @@ bool ActionDisplayMessage::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionDissolve
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionDissolve::ActionDissolve(ZVision *engine) :
 	ResultAction(engine, 0) {
@@ -296,13 +297,13 @@ bool ActionDissolve::execute() {
 	debug(3, "Executing action: Dissolve");
 	// Cause black screen flick
 	// Not ideal.  Original engine used a softer dissolve effect; simply turning the screen black is jarring, so disabled for now.
-	//_engine->getRenderManager()->bkgFill(0, 0, 0); //TODO - reimplement this?
+	// _engine->getRenderManager()->bkgFill(0, 0, 0); // TODO - reimplement this?
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionDistort - only used by Zork: Nemesis for the "treatment" puzzle in the Sanitarium (aj30)
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionDistort::ActionDistort(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -330,9 +331,9 @@ bool ActionDistort::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionEnableControl
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionEnableControl::ActionEnableControl(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -346,9 +347,9 @@ bool ActionEnableControl::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionFlushMouseEvents
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionFlushMouseEvents::ActionFlushMouseEvents(ZVision *engine, int32 slotKey) :
 	ResultAction(engine, slotKey) {
@@ -360,9 +361,9 @@ bool ActionFlushMouseEvents::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionInventory
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionInventory::ActionInventory(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -412,9 +413,9 @@ bool ActionInventory::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionKill - only used by ZGI
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionKill::ActionKill(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -454,9 +455,9 @@ bool ActionKill::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionMenuBarEnable
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionMenuBarEnable::ActionMenuBarEnable(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -470,9 +471,9 @@ bool ActionMenuBarEnable::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionMusic
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionMusic::ActionMusic(ZVision *engine, int32 slotKey, const Common::String &line, bool global) :
 	ResultAction(engine, slotKey),
@@ -523,8 +524,8 @@ ActionMusic::ActionMusic(ZVision *engine, int32 slotKey, const Common::String &l
 	if (engine->getGameId() == GID_NEMESIS && _slotKey == 14822 && _scriptManager->getStateValue(_slotKey) == 2)
 		_scriptManager->setStateValue(_slotKey, 0);
 
-	//Ensure MusicNodes that were active when game was saved are recreated when it is loaded.
-	//Certain game scripts can become locked-up if this is not the case.
+	// Ensure MusicNodes that were active when game was saved are recreated when it is loaded.
+	// Certain game scripts can become locked-up if this is not the case.
 	if (_engine->getScriptManager()->getStateValue(_slotKey) == 1)
 		if (!_scriptManager->getSideFX(_slotKey)) {
 			debug(1, "Recreating missing musicnode, slotkey %d", _slotKey);
@@ -562,9 +563,9 @@ bool ActionMusic::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionPanTrack
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionPanTrack::ActionPanTrack(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey),
@@ -574,10 +575,10 @@ ActionPanTrack::ActionPanTrack(ZVision *engine, int32 slotKey, const Common::Str
 	_resetMixerOnDelete(false),
 	_staticScreen(false),
 	_musicSlot(0) {
-	uint mag = 255;  //Original game scripts do not specify this, but require it to be 255 to work correctly.
-	uint resetMusicNode = 1;  //Original game scripts do not specify this, but require it to be true to work correctly.
-	uint resetMixerOnDelete = 0;  //Original game scripts do not specify this, but require it to be false to work correctly.
-	uint staticScreen = 0;  //Original game scripts do not specify this, but require it to be false to work correctly.
+	uint mag = 255;  // Original game scripts do not specify this, but require it to be 255 to work correctly.
+	uint resetMusicNode = 1;  // Original game scripts do not specify this, but require it to be true to work correctly.
+	uint resetMixerOnDelete = 0;  // Original game scripts do not specify this, but require it to be false to work correctly.
+	uint staticScreen = 0;  // Original game scripts do not specify this, but require it to be false to work correctly.
 	sscanf(line.c_str(), "%u %d %u %u %u %u", &_musicSlot, &_pos, &mag, &resetMusicNode, &resetMixerOnDelete, &staticScreen);
 	_resetMusicNode = resetMusicNode > 0;
 	_resetMixerOnDelete = resetMixerOnDelete > 0;
@@ -586,7 +587,7 @@ ActionPanTrack::ActionPanTrack(ZVision *engine, int32 slotKey, const Common::Str
 	if (_resetMusicNode) {
 		if (_scriptManager->getStateValue(_musicSlot) != 2) {
 			debug(3, "Forcing musicSlot %d to 2", _musicSlot);
-			_scriptManager->setStateValue(_musicSlot, 2); //Not all original game pan_track scripts trigger correctly unless this is set!
+			_scriptManager->setStateValue(_musicSlot, 2); // Not all original game pan_track scripts trigger correctly unless this is set!
 		} else
 			debug(3, "musicSlot %d already set to 2", _musicSlot);
 	} else
@@ -609,9 +610,9 @@ bool ActionPanTrack::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionPreferences
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionPreferences::ActionPreferences(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -630,9 +631,9 @@ bool ActionPreferences::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionPreloadAnimation
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionPreloadAnimation::ActionPreloadAnimation(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -669,9 +670,9 @@ bool ActionPreloadAnimation::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionUnloadAnimation
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionUnloadAnimation::ActionUnloadAnimation(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -689,9 +690,9 @@ bool ActionUnloadAnimation::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionPlayAnimation
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionPlayAnimation::ActionPlayAnimation(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -747,9 +748,9 @@ bool ActionPlayAnimation::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionPlayPreloadAnimation
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionPlayPreloadAnimation::ActionPlayPreloadAnimation(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -799,9 +800,9 @@ bool ActionPlayPreloadAnimation::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionQuit
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 bool ActionQuit::execute() {
 	_engine->quitGame();
@@ -809,9 +810,9 @@ bool ActionQuit::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionRegion - only used by Zork: Nemesis
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionRegion::ActionRegion(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -890,9 +891,9 @@ bool ActionRegion::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionRandom
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionRandom::ActionRandom(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -912,9 +913,9 @@ bool ActionRandom::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionRestoreGame
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionRestoreGame::ActionRestoreGame(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -928,9 +929,9 @@ bool ActionRestoreGame::execute() {
 	return false;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionRotateTo
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionRotateTo::ActionRotateTo(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -946,9 +947,9 @@ bool ActionRotateTo::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionSetPartialScreen
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionSetPartialScreen::ActionSetPartialScreen(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -986,9 +987,9 @@ bool ActionSetPartialScreen::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionSetScreen
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionSetScreen::ActionSetScreen(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -1004,9 +1005,9 @@ bool ActionSetScreen::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionStop
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionStop::ActionStop(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -1020,9 +1021,9 @@ bool ActionStop::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionStreamVideo
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionStreamVideo::ActionStreamVideo(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -1033,7 +1034,7 @@ ActionStreamVideo::ActionStreamVideo(ZVision *engine, int32 slotKey, const Commo
 	_flags = 0;
 
 	char fileName[25];
-	uint skipline = 0;    //skipline - render video with skip every second line, not skippable.
+	uint skipline = 0;    // skipline - render video with skip every second line, not skippable.
 
 	sscanf(line.c_str(), "%24s %u %u %u %u %u %u", fileName, &_x1, &_y1, &_x2, &_y2, &_flags, &skipline);
 
@@ -1084,8 +1085,8 @@ bool ActionStreamVideo::execute() {
 	if (switchToHires) {
 		_engine->getRenderManager()->initialize(true);
 		srcRect = Common::Rect(Common::Point(0, 69), 720, 344);
-		//ZGI hi-res video resolution = 720x480, with baked-in letterboxing around content at 720x344 (origin 0,69), interestingly conforming to playfield vertical resolution of 344
-		destRect = _engine->getRenderManager()->getWorkingArea(); //Game scripts only give destRect for normal resolution; we must manually override them for HD videos
+		// ZGI hi-res video resolution = 720x480, with baked-in letterboxing around content at 720x344 (origin 0,69), interestingly conforming to playfield vertical resolution of 344
+		destRect = _engine->getRenderManager()->getWorkingArea(); // Game scripts only give destRect for normal resolution; we must manually override them for HD videos
 		destRect.moveTo(0, 0);
 	}
 
@@ -1095,7 +1096,7 @@ bool ActionStreamVideo::execute() {
 	// as yourself or as the two-headed beast) it does not. Since the
 	// cutscene plays music, there may be two pieces of music playing
 	// simultaneously during the ride.
-	//
+	// 
 	// Rather than mucking about with killing and restarting the sound,
 	// simply pause the ScummVM mixer during the ride.
 
@@ -1117,15 +1118,15 @@ bool ActionStreamVideo::execute() {
 
 	_engine->getCursorManager()->showMouse(true);
 	_engine->getSubtitleManager()->destroy(sub);
-	_engine->setRenderDelay(2); //Necessary for avoiding redraw of previous scene between sequential videos (eg totemization sequence in ZGI) & when changing location right after a video (e.g. opening temple door in Nemesis)
+	_engine->setRenderDelay(2); // Necessary for avoiding redraw of previous scene between sequential videos (eg totemization sequence in ZGI) & when changing location right after a video (e.g. opening temple door in Nemesis)
 	debug(3, "Completed executing video stream");
 
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionSyncSound
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionSyncSound::ActionSyncSound(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -1152,9 +1153,9 @@ bool ActionSyncSound::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionTimer
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionTimer::ActionTimer(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -1176,9 +1177,9 @@ bool ActionTimer::execute() {
 	return true;
 }
 
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 // ActionTtyText
-//////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////// 
 
 ActionTtyText::ActionTtyText(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
diff --git a/engines/zvision/scripting/actions.h b/engines/zvision/scripting/actions.h
index d23ef2023ac..948fb3ddc9f 100644
--- a/engines/zvision/scripting/actions.h
+++ b/engines/zvision/scripting/actions.h
@@ -239,17 +239,17 @@ public:
 	bool execute() override;
 
 private:
-	int32 _pos; //Sound source position; NB in panoramas (all original game scripts), this is specified as the X background coordinate; otherwise it is specified in azimuth degrees.
-	uint8  _mag; //Magnitude of effect (not used by original game scripts); 255 for fully directional sound, 0 for fully ambient
-	bool _resetMusicNode; //If true (default, original game scripts have no concept of this), associated music slot value is reset to a value of 2 upon creation of this object;
+	int32 _pos; // Sound source position; NB in panoramas (all original game scripts), this is specified as the X background coordinate; otherwise it is specified in azimuth degrees.
+	uint8  _mag; // Magnitude of effect (not used by original game scripts); 255 for fully directional sound, 0 for fully ambient
+	bool _resetMusicNode; // If true (default, original game scripts have no concept of this), associated music slot value is reset to a value of 2 upon creation of this object;
 	/*
 	* this seems necessary to ensure all original game pan-track effects load correctly, though it is still unclear exactly what the original intent of these values was.
 	* So far, best guess for music slotkey values is: 0 = has never been loaded, 1 = loaded and actively playing now, 2 = has loaded & played & then subsequently been killed.
 	* Since there is literally nothing in the game scripts that sets some of these values to 2, and certain pan_tracks require it to be 2 for the puzzle that creates them to trigger,
 	* the original game engine code must have set these values to 2 manually somehow upon conditions being met to allow a pan_track to be created?
 	*/
-	bool _staticScreen; //Used by auxiliary scripts to apply directionality to audio in static screens; not used in original game scripts.
-	bool _resetMixerOnDelete; //Unnecessary and should be set false for original scripts; useful in some cases in extra scripts to avoid brief volume spikes on location changes
+	bool _staticScreen; // Used by auxiliary scripts to apply directionality to audio in static screens; not used in original game scripts.
+	bool _resetMixerOnDelete; // Unnecessary and should be set false for original scripts; useful in some cases in extra scripts to avoid brief volume spikes on location changes
 	uint32 _musicSlot;
 };
 
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 190bb2ff621..0b744af26d1 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -59,7 +59,6 @@ void MusicNodeBASE::updateMixer() {
 	if (_engine->getScriptManager()->getStateValue(StateKey_Qsound) >= 1)
 		_volumeOut = _engine->getVolumeManager()->convert(_volume, _azimuth, _directionality);  // Apply game-specific volume profile and then attenuate according to azimuth
 	else
-//    _volumeOut = _engine->getVolumeManager()->convert(_volume, kVolumeLinear);  // Apply linear volume profile and ignore azimuth
 		_volumeOut = _engine->getVolumeManager()->convert(_volume);  // Apply game-specific volume profile and ignore azimuth
 	outputMixer();
 }
@@ -163,11 +162,6 @@ bool MusicNode::process(uint32 deltaTimeInMillis) {
 			if (_volume != _newvol)
 				setVolume(_newvol);
 		}
-		/*  // Redundant with switch to automatic subtitles
-
-		if (_sub && _engine->getScriptManager()->getStateValue(StateKey_Subtitles) == 1)
-		  _engine->getSubtitleManager()->update(_engine->_mixer->getSoundElapsedTime(_handle) / 100, _sub);
-		// */
 	}
 	return false;
 }
@@ -223,8 +217,6 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 					_viewPos.setDegrees(360 * scriptManager->getStateValue(StateKey_ViewPos) / _width);
 				} else {
 					warning("Encountered zero background width whilst processing PanTrackNode in panoramic mode!");
-					// _sourcePos.setDegrees(0);
-					// _viewPos.setDegrees(0);
 				}
 				break;
 			case RenderTable::FLAT:
diff --git a/engines/zvision/scripting/scr_file_handling.cpp b/engines/zvision/scripting/scr_file_handling.cpp
index 3c3786868bf..80836abf94f 100644
--- a/engines/zvision/scripting/scr_file_handling.cpp
+++ b/engines/zvision/scripting/scr_file_handling.cpp
@@ -319,13 +319,6 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 		debug(4, "Result line: %s", line.c_str());
 		const char *chrs = line.c_str();
 		uint pos;
-		/*/
-		        // Iterate along line until colon encountered
-		        for (pos = 0; pos < line.size(); pos++) {
-		            if (chrs[pos] == ':')
-		                break;
-		        }
-		/*/
 		if (line.matchString("action:*", true))
 			pos = 6;
 		else if (line.matchString("event:*", true))
@@ -334,7 +327,6 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 			pos = 10;
 		else
 			continue;
-// */
 		if (pos < line.size()) {  // Stuff left
 			uint startpos = pos + 1;  // first character after colon
 			// Scan for next colon or opening bracket
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index 7c7fcb6c4f7..76f9f7be7d4 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -633,7 +633,7 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 		}
 	}
 
-	// _engine->setRenderDelay(2); // Uncertain if this is necessary; doesn't seem to cause any problems when disabled, but keep an eye on it.
+	// _engine->setRenderDelay(2); // TODO: Uncertain if this is necessary; doesn't seem to cause any problems when disabled, but keep an eye on it.
 
 	if (!leavingMenu) {
 		if (!isLoading && !enteringMenu) {
diff --git a/engines/zvision/text/subtitle_manager.h b/engines/zvision/text/subtitle_manager.h
index bd74be78f7c..28c4cea5b1d 100644
--- a/engines/zvision/text/subtitle_manager.h
+++ b/engines/zvision/text/subtitle_manager.h
@@ -45,7 +45,6 @@ protected:
 	virtual bool process(int32 deltatime);  // Return true if to be deleted
 	ZVision *_engine;
 	Common::Rect _textArea;
-	// Common::String _txt;
 	int16 _timer; // Always in milliseconds; countdown to deletion
 	bool _toDelete;
 	bool _redraw;
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index ac924e9e8e3..bce27cf0471 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -78,27 +78,9 @@ struct ScreenLayout {
 };
 
 // NB Footage of original DOS Nemesis engine indicates playfield was centrally placed on screen.
-// Subtitle scripts, however, suggest playfield was higher up, otherwise they run off the bottom of the screen.  Could just be an error in the scripts.
-// TODO Need to make a decision how to handle this.  Should be irrelevant for widescreen mode anyway, & purists will want original appearance for 4:3 ratio.
-// Figures below currently have playfield offset to fit subtitles entirely in lower bar
+// Subtitle scripts, however, suggest playfield was higher up, otherwise they run off the bottom of the screen.  
+// This could just be an error in the scripts or an artefact of the original game's development, so we will continue to use as-released central placement.
 
-/*/
-// Vertically offset values
-static const ScreenLayout nemesisLayout {
-  Common::Rect(640,480),  // Screen
-  Common::Rect(Common::Point(64,0), 512, 32), // Menu
-  Common::Rect(Common::Point(64,40), 512, 320), // Working; aspect ratio 1.6
-  Common::Rect(Common::Point(64,380), 512, 100) // Text
-};
-static const ScreenLayout zgiLayout {
-  Common::Rect(640,480),  // Screen
-  Common::Rect(Common::Point(0,0), 640, 32), // Menu
-  Common::Rect(Common::Point(0,40), 640, 344), // Working; aspect ratio 1.86
-  Common::Rect(Common::Point(0,400), 640, 80) // Text
-};
-// */
-// */
-// Central values
 static const ScreenLayout nemesisLayout {
 	Common::Rect(640, 480), // Screen
 	Common::Rect(Common::Point(64, 0), 512, 32), // Menu
@@ -112,7 +94,7 @@ static const ScreenLayout zgiLayout {
 	Common::Rect(Common::Point(0, 68), 640, 344), // Working; aspect ratio 1.86
 	Common::Rect(Common::Point(0, 412), 640, 68) // Text
 };
-// */
+
 enum {
 
 	ROTATION_SCREEN_EDGE_OFFSET = 60,


Commit: ac6df2120f4bf386979f8ae97c89e9e2eaa516f0
    https://github.com/scummvm/scummvm/commit/ac6df2120f4bf386979f8ae97c89e9e2eaa516f0
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:01+02:00

Commit Message:
ZVISION: Code formatting compliance.

Changed paths:
    engines/zvision/scripting/actions.h


diff --git a/engines/zvision/scripting/actions.h b/engines/zvision/scripting/actions.h
index 948fb3ddc9f..437d052cfff 100644
--- a/engines/zvision/scripting/actions.h
+++ b/engines/zvision/scripting/actions.h
@@ -242,7 +242,7 @@ private:
 	int32 _pos; // Sound source position; NB in panoramas (all original game scripts), this is specified as the X background coordinate; otherwise it is specified in azimuth degrees.
 	uint8  _mag; // Magnitude of effect (not used by original game scripts); 255 for fully directional sound, 0 for fully ambient
 	bool _resetMusicNode; // If true (default, original game scripts have no concept of this), associated music slot value is reset to a value of 2 upon creation of this object;
-	/*
+/*
 	* this seems necessary to ensure all original game pan-track effects load correctly, though it is still unclear exactly what the original intent of these values was.
 	* So far, best guess for music slotkey values is: 0 = has never been loaded, 1 = loaded and actively playing now, 2 = has loaded & played & then subsequently been killed.
 	* Since there is literally nothing in the game scripts that sets some of these values to 2, and certain pan_tracks require it to be 2 for the puzzle that creates them to trigger,


Commit: f3eb569358c4e2df899dc8ac912b578a8f54aaf0
    https://github.com/scummvm/scummvm/commit/f3eb569358c4e2df899dc8ac912b578a8f54aaf0
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:01+02:00

Commit Message:
GRAPHICS: Remove automatic pixelformat conversion from Screen; unnecessary.

Changed paths:
    graphics/screen.cpp


diff --git a/graphics/screen.cpp b/graphics/screen.cpp
index 653373eed9e..be81655b064 100644
--- a/graphics/screen.cpp
+++ b/graphics/screen.cpp
@@ -43,27 +43,12 @@ void Screen::update() {
 	mergeDirtyRects();
 
 	// Loop through copying dirty areas to the physical screen
-	PixelFormat outputFormat = g_system->getScreenFormat();
 	Common::List<Common::Rect>::iterator i;
-	if (outputFormat == format) {
-		for (i = _dirtyRects.begin(); i != _dirtyRects.end(); ++i) {
-			const Common::Rect &r = *i;
-			const byte *srcP = (const byte *)getBasePtr(r.left, r.top);
-			g_system->copyRectToScreen(srcP, pitch, r.left, r.top,
-			                           r.width(), r.height());
-		}
-	} else {
-		Graphics::Surface outSurface;
-		for (i = _dirtyRects.begin(); i != _dirtyRects.end(); ++i) {
-			const Common::Rect &r = *i;
-			const byte *srcP = (const byte *)getBasePtr(r.left, r.top);
-			outSurface.create(r.width(), r.height(), format);
-			outSurface.copyRectToSurface(srcP, pitch, 0, 0, r.width(), r.height());
-			outSurface.convertToInPlace(outputFormat);
-			g_system->copyRectToScreen(outSurface.getBasePtr(0, 0), outSurface.pitch, r.left, r.top,
-			                           r.width(), r.height());
-		}
-		outSurface.free();
+	for (i = _dirtyRects.begin(); i != _dirtyRects.end(); ++i) {
+		const Common::Rect &r = *i;
+		const byte *srcP = (const byte *)getBasePtr(r.left, r.top);
+		g_system->copyRectToScreen(srcP, pitch, r.left, r.top,
+			r.width(), r.height());
 	}
 
 	// Signal the physical screen to update


Commit: aa2b080ba59fed03efb850c9d16d903ff09347be
    https://github.com/scummvm/scummvm/commit/aa2b080ba59fed03efb850c9d16d903ff09347be
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:01+02:00

Commit Message:
ZVISION: Amend RenderManager to use unmodified form of Graphics::Screen.

Changed paths:
    engines/zvision/graphics/render_manager.cpp


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 510207b41d5..39e8a70de78 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -122,7 +122,7 @@ void RenderManager::initialize(bool hiRes) {
 	} else
 		debug(1, "Switching to standard resolution");
 #endif
-	_screen.create(_screenArea.width(), _screenArea.height(), _pixelFormat);
+	_screen.create(_screenArea.width(), _screenArea.height(), _engine->_screenPixelFormat);
 	_screen.setTransparentColor(-1);
 	_screen.clear();
 


Commit: 106b4fc0dd66a68a545627b084c7920f20a05d53
    https://github.com/scummvm/scummvm/commit/106b4fc0dd66a68a545627b084c7920f20a05d53
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:01+02:00

Commit Message:
ZVISION: Fix segfault in hi-res video playback arising from previous commit.

Changed paths:
    engines/zvision/graphics/render_manager.cpp


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 39e8a70de78..a0a61db2c8d 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -225,7 +225,7 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
 		_workingManagedSurface.simpleBlitFrom(*_outputSurface); // TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
 		debug(5, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
 	}
-	if (preStream) {
+	if (preStream && !_hiRes) {
 		debug(5, "Pre-rendering text area for video stream");
 		_workingManagedSurface.simpleBlitFrom(*_outputSurface, _textOverlay, _textOverlay.origin()); // Prevents subtitle visual corruption when streaming videos that don't fully overlap them, e.g. Nemesis sarcophagi
 		return false;


Commit: a0a77c552eb110eb1254b2800491e4a1315b6e60
    https://github.com/scummvm/scummvm/commit/a0a77c552eb110eb1254b2800491e4a1315b6e60
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:01+02:00

Commit Message:
ZVISION: Unnecessary member variables made local to member functions.

Changed paths:
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h


diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index a1aa6c5321e..e25dde7858a 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -82,12 +82,12 @@ const Common::Point RenderTable::convertWarpedCoordToFlatCoord(const Common::Poi
 		int16 y = CLIP<int16>(point.y, 0, (int16)_numRows);
 		return Common::Point(x, y);
 	}
-
-	_index = point.y * _numColumns + point.x;
+	
+	uint32 index = point.y * _numColumns + point.x;
 
 	Common::Point newPoint(point);
-	newPoint.x += (_internalBuffer[_index]._xDir ? _internalBuffer[_index]._Src.right : _internalBuffer[_index]._Src.left);
-	newPoint.y += (_internalBuffer[_index]._yDir ? _internalBuffer[_index]._Src.bottom : _internalBuffer[_index]._Src.top);
+	newPoint.x += (_internalBuffer[index]._xDir ? _internalBuffer[index]._Src.right : _internalBuffer[index]._Src.left);
+	newPoint.y += (_internalBuffer[index]._yDir ? _internalBuffer[index]._Src.bottom : _internalBuffer[index]._Src.top);
 
 	return newPoint;
 }
@@ -131,7 +131,9 @@ void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 d
 // */
 
 void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf, bool highQuality) {
-	_destOffset = 0;
+	uint32 destOffset = 0;
+	uint32 sourceOffset = 0;
+	uint32 srcIndexXL, srcIndexYT;
 
 	uint16 *sourceBuffer = (uint16 *)srcBuf->getPixels();
 	uint16 *destBuffer = (uint16 *)dstBuf->getPixels();
@@ -140,39 +142,45 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 		generateRenderTable();
 	}
 	uint32 mutationTime = _system->getMillis();
+
 	if (_highQuality) {
 		// Apply bilinear interpolation
-		FilterPixel _curP;
+		uint32 srcIndexYB, srcIndexXR;
+		uint32 rTL, rTR, rBL, rBR, rF;
+		uint32 gTL, gTR, gBL, gBR, gF;
+		uint32 bTL, bTR, bBL, bBR, bF;
+		FilterPixel curP;
 		for (int16 y = 0; y < srcBuf->h; ++y) {
-			_sourceOffset = y * _numColumns;
+			sourceOffset = y * _numColumns;
 			for (int16 x = 0; x < srcBuf->w; ++x) {
-				_curP = _internalBuffer[_sourceOffset + x];
-				_srcIndexYT = y + _curP._Src.top;
-				_srcIndexYB = y + _curP._Src.bottom;
-				_srcIndexXL = x + _curP._Src.left;
-				_srcIndexXR = x + _curP._Src.right;
-				splitColor(sourceBuffer[_srcIndexYT * _numColumns + _srcIndexXL], _rTL, _gTL, _bTL);
-				splitColor(sourceBuffer[_srcIndexYT * _numColumns + _srcIndexXR], _rTR, _gTR, _bTR);
-				splitColor(sourceBuffer[_srcIndexYB * _numColumns + _srcIndexXL], _rBL, _gBL, _bBL);
-				splitColor(sourceBuffer[_srcIndexYB * _numColumns + _srcIndexXR], _rBR, _gBR, _bBR);
-				_rF = _curP._fTL * _rTL + _curP._fTR * _rTR + _curP._fBL * _rBL + _curP._fBR * _rBR;
-				_gF = _curP._fTL * _gTL + _curP._fTR * _gTR + _curP._fBL * _gBL + _curP._fBR * _gBR;
-				_bF = _curP._fTL * _bTL + _curP._fTR * _bTR + _curP._fBL * _bBL + _curP._fBR * _bBR;
-				destBuffer[_destOffset] = mergeColor(_rF, _gF, _bF);
-				_destOffset++;
+				curP = _internalBuffer[sourceOffset + x];
+				srcIndexYT = y + curP._Src.top;
+				srcIndexYB = y + curP._Src.bottom;
+				srcIndexXL = x + curP._Src.left;
+				srcIndexXR = x + curP._Src.right;
+				splitColor(sourceBuffer[srcIndexYT * _numColumns + srcIndexXL], rTL, gTL, bTL);
+				splitColor(sourceBuffer[srcIndexYT * _numColumns + srcIndexXR], rTR, gTR, bTR);
+				splitColor(sourceBuffer[srcIndexYB * _numColumns + srcIndexXL], rBL, gBL, bBL);
+				splitColor(sourceBuffer[srcIndexYB * _numColumns + srcIndexXR], rBR, gBR, bBR);
+				rF = curP._fTL * rTL + curP._fTR * rTR + curP._fBL * rBL + curP._fBR * rBR;
+				gF = curP._fTL * gTL + curP._fTR * gTR + curP._fBL * gBL + curP._fBR * gBR;
+				bF = curP._fTL * bTL + curP._fTR * bTR + curP._fBL * bBL + curP._fBR * bBR;
+				destBuffer[destOffset] = mergeColor(rF, gF, bF);
+				destOffset++;
 			}
 		}
 	} else {
 		// Apply nearest-neighbour interpolation
+		uint32 index;
 		for (int16 y = 0; y < srcBuf->h; ++y) {
-			_sourceOffset = y * _numColumns;
+			sourceOffset = y * _numColumns;
 			for (int16 x = 0; x < srcBuf->w; ++x) {
-				_index = _sourceOffset + x;
+				index = sourceOffset + x;
 				// RenderTable only stores offsets from the original coordinates
-				_srcIndexXL = x + (_internalBuffer[_index]._xDir ? _internalBuffer[_index]._Src.right : _internalBuffer[_index]._Src.left);
-				_srcIndexYT = y + (_internalBuffer[_index]._yDir ? _internalBuffer[_index]._Src.bottom : _internalBuffer[_index]._Src.top);
-				destBuffer[_destOffset] = sourceBuffer[_srcIndexYT * _numColumns + _srcIndexXL];
-				_destOffset++;
+				srcIndexXL = x + (_internalBuffer[index]._xDir ? _internalBuffer[index]._Src.right : _internalBuffer[index]._Src.left);
+				srcIndexYT = y + (_internalBuffer[index]._yDir ? _internalBuffer[index]._Src.bottom : _internalBuffer[index]._Src.top);
+				destBuffer[destOffset] = sourceBuffer[srcIndexYT * _numColumns + srcIndexXL];
+				destOffset++;
 			}
 		}
 	}
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index 2119f94ac4c..4e8f04fd5f9 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -91,13 +91,6 @@ private:
 	bool _highQuality = false;
 	const Graphics::PixelFormat _pixelFormat;
 
-	uint32 _index;
-	uint32 _sourceOffset, _destOffset;
-	uint32 _srcIndexXL, _srcIndexXR, _srcIndexYT, _srcIndexYB;
-	uint32 _rTL, _rTR, _rBL, _rBR, _rF;
-	uint32 _gTL, _gTR, _gBL, _gBR, _gF;
-	uint32 _bTL, _bTR, _bBL, _bBR, _bF;
-
 	inline void splitColor(uint16 &color, uint32 &r, uint32 &g, uint32 &b) {
 		// NB Left & right shifting unnecessary for interpolating & recombining, so not bothering in order to save cycles
 		r = color & 0x001f;


Commit: 92e5216162f91a900cb77cb7494b81d32ceadbc4
    https://github.com/scummvm/scummvm/commit/92e5216162f91a900cb77cb7494b81d32ceadbc4
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:01+02:00

Commit Message:
ZVISION: Volume profile generator functions converted to integer maths for efficiency.

Changed paths:
    engines/zvision/sound/volume_manager.cpp


diff --git a/engines/zvision/sound/volume_manager.cpp b/engines/zvision/sound/volume_manager.cpp
index a2733705967..6ce5b686d3d 100644
--- a/engines/zvision/sound/volume_manager.cpp
+++ b/engines/zvision/sound/volume_manager.cpp
@@ -148,15 +148,17 @@ uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode, Math::Angle a
 	uint8 index = abs(round(azimuth.getDegrees(-180)));
 	uint32 output = convert(inputValue, mode);
 	uint32 directionalOutput = (output * directionalAmplitude[index]) * directionality;
-	directionalOutput /= 255;
-	output *= (255 - directionality);
-	output = (output + directionalOutput) / 255;
+	directionalOutput /= 0xFF;
+	output *= (0xFF - directionality);
+	output = (output + directionalOutput) / 0xFF;
 	debug(4, "Directionally converted output %d", output);
 	return output;
 };
 
 uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode) {
-	uint16 scaledInput = inputValue * 255;
+	if (inputValue > _scriptScale)
+		inputValue = _scriptScale;
+	uint32 scaledInput = inputValue * 0xFF;
 	scaledInput /= _scriptScale;
 	uint8 output = 0;
 	switch (mode) {
@@ -170,13 +172,17 @@ uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode) {
 		output = powerLaw[scaledInput];
 		break;
 	case kVolumeParabolic:
-		output = pow(scaledInput, 2) / 255;
+		scaledInput *= scaledInput;
+		output = scaledInput / 0xFF;
 		break;
 	case kVolumeCubic:
-		output = pow(scaledInput, 3) / pow(255, 2);
+		scaledInput *= scaledInput * scaledInput;
+		output = scaledInput / 0xFE01;
 		break;
 	case kVolumeQuartic:
-		output = pow(scaledInput, 4) / pow(255, 3);
+		scaledInput *= scaledInput;
+		scaledInput *= scaledInput;
+		output = scaledInput / 0xFD02FF;
 		break;
 	case kVolumeLinear:
 	default:


Commit: 3ab20d64dc615843ebfb67f1dc0fc1fc55ae76a3
    https://github.com/scummvm/scummvm/commit/3ab20d64dc615843ebfb67f1dc0fc1fc55ae76a3
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:01+02:00

Commit Message:
ZVISION: Pass arguments by reference instead of value.

Changed paths:
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h
    engines/zvision/sound/volume_manager.cpp
    engines/zvision/sound/volume_manager.h


diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index e25dde7858a..a1f1135ae46 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -29,7 +29,7 @@
 
 namespace ZVision {
 
-RenderTable::RenderTable(ZVision *engine, uint numColumns, uint numRows, const Graphics::PixelFormat pixelFormat)
+RenderTable::RenderTable(ZVision *engine, uint16 numColumns, uint16 numRows, const Graphics::PixelFormat &pixelFormat)
 	: _engine(engine),
 	  _system(engine->_system),
 	  _numRows(numRows),
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index 4e8f04fd5f9..86202eb4005 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -70,7 +70,7 @@ public:
 
 class RenderTable {
 public:
-	RenderTable(ZVision *engine, uint numRows, uint numColumns, const Graphics::PixelFormat pixelFormat);
+	RenderTable(ZVision *engine, uint16 numRows, uint16 numColumns, const Graphics::PixelFormat &pixelFormat);
 	~RenderTable();
 
 // Common::Point testPixel = Common::Point(255,0);
@@ -84,7 +84,7 @@ public:
 private:
 	ZVision *_engine;
 	OSystem *_system;
-	uint _numRows, _numColumns, _halfRows, _halfColumns; // Working area width, height; half width, half height, in whole pixels
+	uint16 _numRows, _numColumns, _halfRows, _halfColumns; // Working area width, height; half width, half height, in whole pixels
 	float _halfWidth, _halfHeight;  // Centre axis to midpoint of outermost pixel
 	FilterPixel *_internalBuffer;
 	RenderState _renderState;
diff --git a/engines/zvision/sound/volume_manager.cpp b/engines/zvision/sound/volume_manager.cpp
index 6ce5b686d3d..a18dc555eed 100644
--- a/engines/zvision/sound/volume_manager.cpp
+++ b/engines/zvision/sound/volume_manager.cpp
@@ -144,7 +144,7 @@ uint8 VolumeManager::convert(uint8 inputValue, Math::Angle azimuth, uint8 direct
 	return convert(inputValue, _mode, azimuth, directionality);
 };
 
-uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode, Math::Angle azimuth, uint8 directionality) {
+uint8 VolumeManager::convert(uint8 inputValue, volumeScaling &mode, Math::Angle azimuth, uint8 directionality) {
 	uint8 index = abs(round(azimuth.getDegrees(-180)));
 	uint32 output = convert(inputValue, mode);
 	uint32 directionalOutput = (output * directionalAmplitude[index]) * directionality;
@@ -155,7 +155,7 @@ uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode, Math::Angle a
 	return output;
 };
 
-uint8 VolumeManager::convert(uint8 inputValue, volumeScaling mode) {
+uint8 VolumeManager::convert(uint8 inputValue, volumeScaling &mode) {
 	if (inputValue > _scriptScale)
 		inputValue = _scriptScale;
 	uint32 scaledInput = inputValue * 0xFF;
diff --git a/engines/zvision/sound/volume_manager.h b/engines/zvision/sound/volume_manager.h
index 24cb4cf867b..6d08042df07 100644
--- a/engines/zvision/sound/volume_manager.h
+++ b/engines/zvision/sound/volume_manager.h
@@ -49,9 +49,9 @@ public:
 		_mode = mode;
 	};
 	uint8 convert(uint8 inputValue);
-	uint8 convert(uint8 inputValue, volumeScaling mode);
+	uint8 convert(uint8 inputValue, volumeScaling &mode);
 	uint8 convert(uint8 inputValue, Math::Angle azimuth, uint8 directionality = 255);
-	uint8 convert(uint8 inputValue, volumeScaling mode, Math::Angle azimuth, uint8 directionality = 255);
+	uint8 convert(uint8 inputValue, volumeScaling &mode, Math::Angle azimuth, uint8 directionality = 255);
 private:
 	ZVision *_engine;
 	uint _scriptScale = 100; // Z-Vision scripts internally use a volume scale of 0-100; ScummVM uses a scale of 0-255.


Commit: ce745721ffd3b918a663a8530a9b121852d3bd2a
    https://github.com/scummvm/scummvm/commit/ce745721ffd3b918a663a8530a9b121852d3bd2a
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:01+02:00

Commit Message:
ZVISION: Cleaner MT-32 detection.

Changed paths:
    engines/zvision/sound/midi.cpp


diff --git a/engines/zvision/sound/midi.cpp b/engines/zvision/sound/midi.cpp
index 510ffaabd5d..6006bbfd2b9 100644
--- a/engines/zvision/sound/midi.cpp
+++ b/engines/zvision/sound/midi.cpp
@@ -37,7 +37,7 @@ MidiManager::MidiManager() {
 	} else {
 		Common::String driverName = MidiDriver::getDeviceString(dev, MidiDriver::DeviceStringType::kDriverName);
 		Common::String deviceName = MidiDriver::getDeviceString(dev, MidiDriver::DeviceStringType::kDeviceName);
-		_mt32 = driverName.contains("MT-32");
+		_mt32 = MidiDriver::getMusicType(dev) == MT_MT32;
 		debug(1, "MIDI opened, driver type: %s, device name: %s", driverName.c_str(), deviceName.c_str());
 		_available = true;
 		_maxChannels = _driver->MIDI_CHANNEL_COUNT;


Commit: dd73308c6a6a7ac9781b72c8721d48c345dcb9f2
    https://github.com/scummvm/scummvm/commit/dd73308c6a6a7ac9781b72c8721d48c345dcb9f2
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:01+02:00

Commit Message:
ZVISION: Remove obsolete code.

Changed paths:
    engines/zvision/scripting/effects/syncsound_effect.cpp


diff --git a/engines/zvision/scripting/effects/syncsound_effect.cpp b/engines/zvision/scripting/effects/syncsound_effect.cpp
index 62b2efdf950..2db53852b21 100644
--- a/engines/zvision/scripting/effects/syncsound_effect.cpp
+++ b/engines/zvision/scripting/effects/syncsound_effect.cpp
@@ -75,10 +75,6 @@ bool SyncSoundNode::process(uint32 deltaTimeInMillis) {
 
 		if (_engine->getScriptManager()->getSideFX(_syncto) == NULL)
 			return stop();
-		/*  // Redundant with switch to automatic subtitles
-		  if (_sub && _engine->getScriptManager()->getStateValue(StateKey_Subtitles) == 1)
-		      _engine->getSubtitleManager()->update(_engine->_mixer->getSoundElapsedTime(_handle) / 100, _sub);
-		// */
 	}
 	return false;
 }


Commit: 388d40b70189e4ad7db17468417e9d51010e8ef6
    https://github.com/scummvm/scummvm/commit/388d40b70189e4ad7db17468417e9d51010e8ef6
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:01+02:00

Commit Message:
ZVISION: Code formatting compliance.

Changed paths:
    engines/zvision/scripting/scr_file_handling.cpp


diff --git a/engines/zvision/scripting/scr_file_handling.cpp b/engines/zvision/scripting/scr_file_handling.cpp
index 80836abf94f..dbf7005195c 100644
--- a/engines/zvision/scripting/scr_file_handling.cpp
+++ b/engines/zvision/scripting/scr_file_handling.cpp
@@ -105,7 +105,7 @@ void ScriptManager::parsePuzzle(Puzzle *puzzle, Common::SeekableReadStream &stre
 			parseResults(stream, puzzle->resultActions, puzzle->key);
 			// WORKAROUNDS:
 			switch (_engine->getGameId()) {
-			case GID_NEMESIS: {
+			case GID_NEMESIS:
 				// WORKAROUND for a script bug in Zork Nemesis, room ve5e (tuning
 				// fork box closeup). If the player leaves the screen while the
 				// box is open, puzzle 19398 shows the animation where the box
@@ -114,9 +114,8 @@ void ScriptManager::parsePuzzle(Puzzle *puzzle, Common::SeekableReadStream &stre
 				// Fixes bug #6803.
 				if (puzzle->key == 19398)
 					puzzle->resultActions.push_back(new ActionAssign(_engine, 11, "19397, 0"));
-			}
-			break;
-			case GID_GRANDINQUISITOR: {
+				break;
+			case GID_GRANDINQUISITOR:
 				switch (puzzle->key) {
 				case 10836:
 					// WORKAROUND for bug #10604. If the player is looking at the
@@ -146,8 +145,7 @@ void ScriptManager::parsePuzzle(Puzzle *puzzle, Common::SeekableReadStream &stre
 				default:
 					break;
 				}
-			}
-			break;
+				break;
 			default:
 				break;
 			}


Commit: 36451ff3e425af347d5021626761abb933a59152
    https://github.com/scummvm/scummvm/commit/36451ff3e425af347d5021626761abb933a59152
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:01+02:00

Commit Message:
ZVISION: Fix Nemesis script bug for Monastery rumble sound effect.
Add changingLocation() function to ScriptManager to support this.
Add additional debug message to MusicNode::setVolume() to support this.

Changed paths:
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/scripting/script_manager.h


diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 0b744af26d1..7d76ab0f9fa 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -168,6 +168,7 @@ bool MusicNode::process(uint32 deltaTimeInMillis) {
 
 void MusicNode::setVolume(uint8 newVolume) {
 	if (_loaded) {
+		debug(4, "Changing volume of music node %d from %d to %d", _key, _volume, newVolume);
 		_volume = newVolume;
 		updateMixer();
 	}
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index 76f9f7be7d4..d43a08e5957 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -96,8 +96,12 @@ void ScriptManager::initialize(bool restarted) {
 		_engine->loadSettings();
 }
 
+bool ScriptManager::changingLocation() const {
+	return _currentLocation != _nextLocation;
+}
+
 void ScriptManager::update(uint deltaTimeMillis) {
-	if (_currentLocation != _nextLocation) {
+	if (changingLocation()) {
 		// The location is changing. The script that did that may have
 		// triggered other scripts, so give them all one extra cycle to
 		// run. This fixes some missing scoring in ZGI, and quite
@@ -254,6 +258,25 @@ bool ScriptManager::checkPuzzleCriteria(Puzzle *puzzle, uint counter) {
 	if (counter == 0 && (getStateFlag(puzzle->key) & Puzzle::DO_ME_NOW) == 0) {
 		return true;
 	}
+	
+	// WORKAROUNDS:
+	switch (_engine->getGameId()) {
+	case GID_NEMESIS:
+		switch (puzzle->key) {
+		case 16418:
+			// WORKAROUND for script bug in Zork Nemesis, room mc30 (Monastery Entry)
+			// Rumble sound effect should cease upon changing location to me10 (Hall of Masks),
+			// but this puzzle erroneously restarted it immediately after.
+			if(changingLocation())
+				return true;
+			break;
+		default:
+			break;
+		}
+		break;
+	default:
+		break;
+	}
 
 	bool criteriaMet = false;
 	for (Common::List<Common::List<Puzzle::CriteriaEntry> >::iterator criteriaIter = puzzle->criteriaList.begin(); criteriaIter != puzzle->criteriaList.end(); ++criteriaIter) {
diff --git a/engines/zvision/scripting/script_manager.h b/engines/zvision/scripting/script_manager.h
index ed6496778ef..b8dd5722051 100644
--- a/engines/zvision/scripting/script_manager.h
+++ b/engines/zvision/scripting/script_manager.h
@@ -267,6 +267,8 @@ public:
 	/** Mark next location */
 	void changeLocation(char world, char room, char node, char view, uint32 offset);
 	void changeLocation(const Location &_newLocation);
+	
+	bool changingLocation() const;
 
 	void serialize(Common::WriteStream *stream);
 	void deserialize(Common::SeekableReadStream *stream);


Commit: 0872c53a2708e43f72bc0863e57d0a6cee722760
    https://github.com/scummvm/scummvm/commit/0872c53a2708e43f72bc0863e57d0a6cee722760
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:01+02:00

Commit Message:
ZVISION: Code formatting compliance.

Changed paths:
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/scr_file_handling.cpp
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/video/video.cpp


diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index 3b0ec073e74..bb675f72698 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -53,9 +53,9 @@ ResultAction::ResultAction(ZVision *engine, int32 slotKey) :
 	_scriptManager(engine->getScriptManager()) {
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionAdd
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionAdd::ActionAdd(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -76,9 +76,9 @@ bool ActionAdd::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionAssign
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionAssign::ActionAssign(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -100,9 +100,9 @@ bool ActionAssign::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionAttenuate
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 // TODO: the effects of this seem permanent until the music node is deleted; check if they should only be applied on a per-cycle basis!
 
@@ -128,9 +128,9 @@ bool ActionAttenuate::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionChangeLocation
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionChangeLocation::ActionChangeLocation(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -149,9 +149,9 @@ bool ActionChangeLocation::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionCrossfade
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionCrossfade::ActionCrossfade(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -196,9 +196,9 @@ bool ActionCrossfade::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionCursor
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionCursor::ActionCursor(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -228,9 +228,9 @@ bool ActionCursor::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionDelayRender
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionDelayRender::ActionDelayRender(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -247,9 +247,9 @@ bool ActionDelayRender::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionDisableControl
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionDisableControl::ActionDisableControl(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -263,9 +263,9 @@ bool ActionDisableControl::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionDisplayMessage
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionDisplayMessage::ActionDisplayMessage(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -284,9 +284,9 @@ bool ActionDisplayMessage::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionDissolve
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionDissolve::ActionDissolve(ZVision *engine) :
 	ResultAction(engine, 0) {
@@ -301,9 +301,9 @@ bool ActionDissolve::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionDistort - only used by Zork: Nemesis for the "treatment" puzzle in the Sanitarium (aj30)
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionDistort::ActionDistort(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -331,9 +331,9 @@ bool ActionDistort::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionEnableControl
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionEnableControl::ActionEnableControl(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -347,9 +347,9 @@ bool ActionEnableControl::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionFlushMouseEvents
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionFlushMouseEvents::ActionFlushMouseEvents(ZVision *engine, int32 slotKey) :
 	ResultAction(engine, slotKey) {
@@ -361,9 +361,9 @@ bool ActionFlushMouseEvents::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionInventory
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionInventory::ActionInventory(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -413,9 +413,9 @@ bool ActionInventory::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionKill - only used by ZGI
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionKill::ActionKill(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -455,9 +455,9 @@ bool ActionKill::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionMenuBarEnable
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionMenuBarEnable::ActionMenuBarEnable(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -471,9 +471,9 @@ bool ActionMenuBarEnable::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionMusic
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionMusic::ActionMusic(ZVision *engine, int32 slotKey, const Common::String &line, bool global) :
 	ResultAction(engine, slotKey),
@@ -563,9 +563,9 @@ bool ActionMusic::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionPanTrack
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionPanTrack::ActionPanTrack(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey),
@@ -610,9 +610,9 @@ bool ActionPanTrack::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionPreferences
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionPreferences::ActionPreferences(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -631,9 +631,9 @@ bool ActionPreferences::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionPreloadAnimation
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionPreloadAnimation::ActionPreloadAnimation(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -670,9 +670,9 @@ bool ActionPreloadAnimation::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionUnloadAnimation
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionUnloadAnimation::ActionUnloadAnimation(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -690,9 +690,9 @@ bool ActionUnloadAnimation::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionPlayAnimation
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionPlayAnimation::ActionPlayAnimation(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -748,9 +748,9 @@ bool ActionPlayAnimation::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionPlayPreloadAnimation
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionPlayPreloadAnimation::ActionPlayPreloadAnimation(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -800,9 +800,9 @@ bool ActionPlayPreloadAnimation::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionQuit
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 bool ActionQuit::execute() {
 	_engine->quitGame();
@@ -810,9 +810,9 @@ bool ActionQuit::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionRegion - only used by Zork: Nemesis
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionRegion::ActionRegion(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -891,9 +891,9 @@ bool ActionRegion::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionRandom
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionRandom::ActionRandom(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -913,9 +913,9 @@ bool ActionRandom::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionRestoreGame
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionRestoreGame::ActionRestoreGame(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -929,9 +929,9 @@ bool ActionRestoreGame::execute() {
 	return false;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionRotateTo
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionRotateTo::ActionRotateTo(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -947,9 +947,9 @@ bool ActionRotateTo::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionSetPartialScreen
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionSetPartialScreen::ActionSetPartialScreen(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -987,9 +987,9 @@ bool ActionSetPartialScreen::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionSetScreen
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionSetScreen::ActionSetScreen(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -1005,9 +1005,9 @@ bool ActionSetScreen::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionStop
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionStop::ActionStop(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -1021,9 +1021,9 @@ bool ActionStop::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionStreamVideo
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionStreamVideo::ActionStreamVideo(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -1096,7 +1096,7 @@ bool ActionStreamVideo::execute() {
 	// as yourself or as the two-headed beast) it does not. Since the
 	// cutscene plays music, there may be two pieces of music playing
 	// simultaneously during the ride.
-	// 
+	//
 	// Rather than mucking about with killing and restarting the sound,
 	// simply pause the ScummVM mixer during the ride.
 
@@ -1124,9 +1124,9 @@ bool ActionStreamVideo::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionSyncSound
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionSyncSound::ActionSyncSound(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -1153,9 +1153,9 @@ bool ActionSyncSound::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionTimer
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionTimer::ActionTimer(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
@@ -1177,9 +1177,9 @@ bool ActionTimer::execute() {
 	return true;
 }
 
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 // ActionTtyText
-////////////////////////////////////////////////////////////////////////////// 
+//////////////////////////////////////////////////////////////////////////////
 
 ActionTtyText::ActionTtyText(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
diff --git a/engines/zvision/scripting/scr_file_handling.cpp b/engines/zvision/scripting/scr_file_handling.cpp
index dbf7005195c..fa1a652d122 100644
--- a/engines/zvision/scripting/scr_file_handling.cpp
+++ b/engines/zvision/scripting/scr_file_handling.cpp
@@ -126,10 +126,10 @@ void ScriptManager::parsePuzzle(Puzzle *puzzle, Common::SeekableReadStream &stre
 					// run the player gets stuck in a dark room instead. We have
 					// to add the assignment action to the front, or it won't be
 					// reached because changing the location terminates the script.
-					// 
+					//
 					// Fixing it this way only keeps the bug from happening. It
 					// will not repair old savegames.
-					// 
+					//
 					// Note that the bug only affects the DVD version. The CD
 					// version doesn't have a separate room for the cutscene.
 					if (_engine->getFeatures() & ADGF_DVD)
@@ -272,7 +272,7 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 		// than 10 units left, it will get stuck and never time out. We
 		// work around that by changing the condition from "greater than
 		// 10" to "greater than 0 but not 2 (the magic time-out value)".
-		// 
+		//
 		// I have a sneaking suspicion that there may be other timer
 		// glitches like this, but this one makes the game unplayable
 		// and is easy to trigger.
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index d43a08e5957..3ff937d6d8c 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -106,7 +106,7 @@ void ScriptManager::update(uint deltaTimeMillis) {
 		// triggered other scripts, so give them all one extra cycle to
 		// run. This fixes some missing scoring in ZGI, and quite
 		// possibly other minor glitches as well.
-		// 
+		//
 		// Another idea would be to change if there are pending scripts
 		// in the exec queues, but that could cause this to hang
 		// indefinitely.
diff --git a/engines/zvision/video/video.cpp b/engines/zvision/video/video.cpp
index 122bec40089..07a0a980c2d 100644
--- a/engines/zvision/video/video.cpp
+++ b/engines/zvision/video/video.cpp
@@ -187,7 +187,7 @@ double ZVision::getVobAmplification(Common::String fileName) const {
 	// in the low-res ones. So we artificially boost the volume. This is an
 	// approximation, but I've tried to match the old volumes reasonably
 	// well.
-	// 
+	//
 	// Some of these will cause audio clipping. Hopefully not enough to be
 	// noticeable.
 	double amplification = 0.0;


Commit: 094eb6841878d6b0501aed467bc30296f1fb9894
    https://github.com/scummvm/scummvm/commit/094eb6841878d6b0501aed467bc30296f1fb9894
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:01+02:00

Commit Message:
ZVISION: Code formatting compliance; all #include statements sorted.

Changed paths:
    engines/zvision/core/clock.cpp
    engines/zvision/core/console.cpp
    engines/zvision/core/events.cpp
    engines/zvision/detection.cpp
    engines/zvision/file/lzss_read_stream.cpp
    engines/zvision/file/lzss_read_stream.h
    engines/zvision/file/save_manager.cpp
    engines/zvision/file/save_manager.h
    engines/zvision/file/search_manager.cpp
    engines/zvision/file/search_manager.h
    engines/zvision/file/zfs_archive.cpp
    engines/zvision/graphics/cursors/cursor.cpp
    engines/zvision/graphics/cursors/cursor_manager.cpp
    engines/zvision/graphics/cursors/cursor_manager.h
    engines/zvision/graphics/effects/fog.cpp
    engines/zvision/graphics/effects/light.cpp
    engines/zvision/graphics/effects/wave.cpp
    engines/zvision/graphics/graphics_effect.h
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h
    engines/zvision/metaengine.cpp
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/actions.h
    engines/zvision/scripting/control.cpp
    engines/zvision/scripting/controls/fist_control.cpp
    engines/zvision/scripting/controls/fist_control.h
    engines/zvision/scripting/controls/hotmov_control.cpp
    engines/zvision/scripting/controls/hotmov_control.h
    engines/zvision/scripting/controls/input_control.cpp
    engines/zvision/scripting/controls/input_control.h
    engines/zvision/scripting/controls/lever_control.cpp
    engines/zvision/scripting/controls/lever_control.h
    engines/zvision/scripting/controls/paint_control.cpp
    engines/zvision/scripting/controls/paint_control.h
    engines/zvision/scripting/controls/push_toggle_control.cpp
    engines/zvision/scripting/controls/push_toggle_control.h
    engines/zvision/scripting/controls/safe_control.cpp
    engines/zvision/scripting/controls/safe_control.h
    engines/zvision/scripting/controls/save_control.cpp
    engines/zvision/scripting/controls/save_control.h
    engines/zvision/scripting/controls/slot_control.cpp
    engines/zvision/scripting/controls/slot_control.h
    engines/zvision/scripting/controls/titler_control.cpp
    engines/zvision/scripting/controls/titler_control.h
    engines/zvision/scripting/effects/animation_effect.cpp
    engines/zvision/scripting/effects/animation_effect.h
    engines/zvision/scripting/effects/distort_effect.cpp
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/effects/music_effect.h
    engines/zvision/scripting/effects/region_effect.cpp
    engines/zvision/scripting/effects/region_effect.h
    engines/zvision/scripting/effects/syncsound_effect.cpp
    engines/zvision/scripting/effects/timer_effect.cpp
    engines/zvision/scripting/effects/ttytext_effect.cpp
    engines/zvision/scripting/effects/ttytext_effect.h
    engines/zvision/scripting/inventory.cpp
    engines/zvision/scripting/menu.h
    engines/zvision/scripting/puzzle.h
    engines/zvision/scripting/scr_file_handling.cpp
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/scripting/script_manager.h
    engines/zvision/sound/midi.cpp
    engines/zvision/sound/volume_manager.cpp
    engines/zvision/sound/zork_raw.cpp
    engines/zvision/text/string_manager.cpp
    engines/zvision/text/subtitle_manager.cpp
    engines/zvision/text/subtitle_manager.h
    engines/zvision/text/text.cpp
    engines/zvision/text/text.h
    engines/zvision/text/truetype_font.cpp
    engines/zvision/video/rlf_decoder.cpp
    engines/zvision/video/rlf_decoder.h
    engines/zvision/video/video.cpp
    engines/zvision/video/zork_avi_decoder.cpp
    engines/zvision/zvision.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/core/clock.cpp b/engines/zvision/core/clock.cpp
index ca6d8c9f6ae..35c37b2b813 100644
--- a/engines/zvision/core/clock.cpp
+++ b/engines/zvision/core/clock.cpp
@@ -20,10 +20,8 @@
  */
 
 #include "common/scummsys.h"
-
-#include "zvision/core/clock.h"
-
 #include "common/system.h"
+#include "zvision/core/clock.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/core/console.cpp b/engines/zvision/core/console.cpp
index 11dc7a729b1..a2a3af22675 100644
--- a/engines/zvision/core/console.cpp
+++ b/engines/zvision/core/console.cpp
@@ -18,26 +18,21 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
  */
-
+ 
+#include "audio/mixer.h"
+#include "common/bufferedstream.h"
+#include "common/file.h"
 #include "common/scummsys.h"
-
-#include "zvision/core/console.h"
-
+#include "common/system.h"
+#include "gui/debugger.h"
 #include "zvision/zvision.h"
-#include "zvision/scripting/script_manager.h"
+#include "zvision/core/console.h"
 #include "zvision/graphics/render_manager.h"
+#include "zvision/graphics/cursors/cursor.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/sound/zork_raw.h"
 #include "zvision/text/string_manager.h"
 #include "zvision/video/zork_avi_decoder.h"
-#include "zvision/sound/zork_raw.h"
-#include "zvision/graphics/cursors/cursor.h"
-
-#include "common/system.h"
-#include "common/file.h"
-#include "common/bufferedstream.h"
-
-#include "gui/debugger.h"
-
-#include "audio/mixer.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/core/events.cpp b/engines/zvision/core/events.cpp
index 863754652f7..b409626f72b 100644
--- a/engines/zvision/core/events.cpp
+++ b/engines/zvision/core/events.cpp
@@ -19,25 +19,21 @@
  *
  */
 
+#include "audio/mixer.h"
+#include "common/events.h"
 #include "common/scummsys.h"
-
+#include "common/system.h"
+#include "common/rational.h"
+#include "engines/util.h"
 #include "zvision/zvision.h"
-
 #include "zvision/core/console.h"
 #include "zvision/graphics/cursors/cursor_manager.h"
 #include "zvision/graphics/render_manager.h"
-#include "zvision/text/subtitle_manager.h"
 #include "zvision/scripting/script_manager.h"
 #include "zvision/scripting/menu.h"
 #include "zvision/sound/zork_raw.h"
 #include "zvision/text/string_manager.h"
-
-#include "common/events.h"
-#include "common/system.h"
-#include "common/rational.h"
-#include "audio/mixer.h"
-
-#include "engines/util.h"
+#include "zvision/text/subtitle_manager.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/detection.cpp b/engines/zvision/detection.cpp
index 7ad6ecd7a9c..89cdf062478 100644
--- a/engines/zvision/detection.cpp
+++ b/engines/zvision/detection.cpp
@@ -19,14 +19,10 @@
  *
  */
 
-#include "common/scummsys.h"
-
 #include "base/plugins.h"
-
-#include "engines/advancedDetector.h"
-
+#include "common/scummsys.h"
 #include "common/str-array.h"
-
+#include "engines/advancedDetector.h"
 #include "zvision/detection.h"
 #include "zvision/detection_tables.h"
 
diff --git a/engines/zvision/file/lzss_read_stream.cpp b/engines/zvision/file/lzss_read_stream.cpp
index bfbd9680fc0..4aeb9eea84e 100644
--- a/engines/zvision/file/lzss_read_stream.cpp
+++ b/engines/zvision/file/lzss_read_stream.cpp
@@ -20,7 +20,6 @@
  */
 
 #include "common/scummsys.h"
-
 #include "zvision/file/lzss_read_stream.h"
 
 namespace ZVision {
diff --git a/engines/zvision/file/lzss_read_stream.h b/engines/zvision/file/lzss_read_stream.h
index d533a268075..9da8bd83000 100644
--- a/engines/zvision/file/lzss_read_stream.h
+++ b/engines/zvision/file/lzss_read_stream.h
@@ -22,8 +22,8 @@
 #ifndef ZVISION_LZSS_STREAM_H
 #define ZVISION_LZSS_STREAM_H
 
-#include "common/stream.h"
 #include "common/array.h"
+#include "common/stream.h"
 
 namespace Common {
 class SeekableReadStream;
diff --git a/engines/zvision/file/save_manager.cpp b/engines/zvision/file/save_manager.cpp
index c0290766ad9..9555cf3afd4 100644
--- a/engines/zvision/file/save_manager.cpp
+++ b/engines/zvision/file/save_manager.cpp
@@ -19,23 +19,20 @@
  *
  */
 
-#include "common/scummsys.h"
-
-#include "zvision/zvision.h"
-#include "zvision/file/save_manager.h"
-#include "zvision/scripting/script_manager.h"
-#include "zvision/graphics/render_manager.h"
 
+#include "common/config-manager.h"
+#include "common/scummsys.h"
 #include "common/system.h"
 #include "common/translation.h"
-
 #include "graphics/surface.h"
 #include "graphics/thumbnail.h"
-
 #include "gui/message.h"
 #include "gui/saveload.h"
+#include "zvision/zvision.h"
+#include "zvision/file/save_manager.h"
+#include "zvision/graphics/render_manager.h"
+#include "zvision/scripting/script_manager.h"
 
-#include "common/config-manager.h"
 namespace ZVision {
 
 const uint32 SaveManager::SAVEGAME_ID = MKTAG('Z', 'E', 'N', 'G');
diff --git a/engines/zvision/file/save_manager.h b/engines/zvision/file/save_manager.h
index aa2fe83801c..feba9017879 100644
--- a/engines/zvision/file/save_manager.h
+++ b/engines/zvision/file/save_manager.h
@@ -22,8 +22,8 @@
 #ifndef ZVISION_SAVE_MANAGER_H
 #define ZVISION_SAVE_MANAGER_H
 
-#include "common/savefile.h"
 #include "common/memstream.h"
+#include "common/savefile.h"
 
 namespace Common {
 class String;
diff --git a/engines/zvision/file/search_manager.cpp b/engines/zvision/file/search_manager.cpp
index 6fc7376a921..61ea272bda2 100644
--- a/engines/zvision/file/search_manager.cpp
+++ b/engines/zvision/file/search_manager.cpp
@@ -22,7 +22,6 @@
 #include "common/debug.h"
 #include "common/fs.h"
 #include "common/stream.h"
-
 #include "zvision/file/search_manager.h"
 #include "zvision/file/zfs_archive.h"
 
diff --git a/engines/zvision/file/search_manager.h b/engines/zvision/file/search_manager.h
index 928ad8eff38..122ff7b1988 100644
--- a/engines/zvision/file/search_manager.h
+++ b/engines/zvision/file/search_manager.h
@@ -22,12 +22,12 @@
 #ifndef ZVISION_SEARCH_MANAGER_H
 #define ZVISION_SEARCH_MANAGER_H
 
-#include "common/str.h"
-#include "common/hash-str.h"
-#include "common/hashmap.h"
 #include "common/archive.h"
 #include "common/file.h"
+#include "common/hashmap.h"
+#include "common/hash-str.h"
 #include "common/list.h"
+#include "common/str.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/file/zfs_archive.cpp b/engines/zvision/file/zfs_archive.cpp
index 1803fb59cd7..0921a881113 100644
--- a/engines/zvision/file/zfs_archive.cpp
+++ b/engines/zvision/file/zfs_archive.cpp
@@ -19,11 +19,10 @@
  *
  */
 
-#include "common/scummsys.h"
-#include "common/memstream.h"
 #include "common/debug.h"
 #include "common/file.h"
-
+#include "common/memstream.h"
+#include "common/scummsys.h"
 #include "zvision/file/zfs_archive.h"
 
 namespace ZVision {
diff --git a/engines/zvision/graphics/cursors/cursor.cpp b/engines/zvision/graphics/cursors/cursor.cpp
index 49f83ae2700..1030dfd01d6 100644
--- a/engines/zvision/graphics/cursors/cursor.cpp
+++ b/engines/zvision/graphics/cursors/cursor.cpp
@@ -19,12 +19,10 @@
  *
  */
 
+#include "common/file.h"
 #include "common/scummsys.h"
-
-#include "zvision/graphics/cursors/cursor.h"
-
 #include "common/str.h"
-#include "common/file.h"
+#include "zvision/graphics/cursors/cursor.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/graphics/cursors/cursor_manager.cpp b/engines/zvision/graphics/cursors/cursor_manager.cpp
index 62a9ec1c781..1c593c2baf0 100644
--- a/engines/zvision/graphics/cursors/cursor_manager.cpp
+++ b/engines/zvision/graphics/cursors/cursor_manager.cpp
@@ -20,15 +20,11 @@
  */
 
 #include "common/scummsys.h"
-
-#include "zvision/graphics/cursors/cursor_manager.h"
-
-#include "zvision/zvision.h"
-
 #include "common/system.h"
-
-#include "graphics/pixelformat.h"
 #include "graphics/cursorman.h"
+#include "graphics/pixelformat.h"
+#include "zvision/zvision.h"
+#include "zvision/graphics/cursors/cursor_manager.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/graphics/cursors/cursor_manager.h b/engines/zvision/graphics/cursors/cursor_manager.h
index cf8ec5965a0..a8d25dc89cf 100644
--- a/engines/zvision/graphics/cursors/cursor_manager.h
+++ b/engines/zvision/graphics/cursors/cursor_manager.h
@@ -22,9 +22,8 @@
 #ifndef ZVISION_CURSOR_MANAGER_H
 #define ZVISION_CURSOR_MANAGER_H
 
-#include "zvision/graphics/cursors/cursor.h"
-
 #include "common/str.h"
+#include "zvision/graphics/cursors/cursor.h"
 
 namespace Graphics {
 struct PixelFormat;
diff --git a/engines/zvision/graphics/effects/fog.cpp b/engines/zvision/graphics/effects/fog.cpp
index 239abbc12f1..3727621c71f 100644
--- a/engines/zvision/graphics/effects/fog.cpp
+++ b/engines/zvision/graphics/effects/fog.cpp
@@ -20,11 +20,9 @@
  */
 
 #include "common/scummsys.h"
-
-#include "zvision/graphics/effects/fog.h"
-
 #include "zvision/zvision.h"
 #include "zvision/graphics/render_manager.h"
+#include "zvision/graphics/effects/fog.h"
 #include "zvision/scripting/script_manager.h"
 
 namespace ZVision {
diff --git a/engines/zvision/graphics/effects/light.cpp b/engines/zvision/graphics/effects/light.cpp
index 1e77c1d4af7..0e1cabc3c10 100644
--- a/engines/zvision/graphics/effects/light.cpp
+++ b/engines/zvision/graphics/effects/light.cpp
@@ -20,11 +20,9 @@
  */
 
 #include "common/scummsys.h"
-
-#include "zvision/graphics/effects/light.h"
-
 #include "zvision/zvision.h"
 #include "zvision/graphics/render_manager.h"
+#include "zvision/graphics/effects/light.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/graphics/effects/wave.cpp b/engines/zvision/graphics/effects/wave.cpp
index 0eeafd1e0b5..d0907faad6b 100644
--- a/engines/zvision/graphics/effects/wave.cpp
+++ b/engines/zvision/graphics/effects/wave.cpp
@@ -20,11 +20,9 @@
  */
 
 #include "common/scummsys.h"
-
-#include "zvision/graphics/effects/wave.h"
-
 #include "zvision/zvision.h"
 #include "zvision/graphics/render_manager.h"
+#include "zvision/graphics/effects/wave.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/graphics/graphics_effect.h b/engines/zvision/graphics/graphics_effect.h
index 2f0edfb529b..afcc94053eb 100644
--- a/engines/zvision/graphics/graphics_effect.h
+++ b/engines/zvision/graphics/graphics_effect.h
@@ -22,10 +22,9 @@
 #ifndef GRAPHICS_EFFECT_H_INCLUDED
 #define GRAPHICS_EFFECT_H_INCLUDED
 
-#include "common/rect.h"
 #include "common/list.h"
+#include "common/rect.h"
 #include "graphics/surface.h"
-
 #include "zvision/zvision.h"
 
 namespace ZVision {
diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index a0a61db2c8d..dc159741afe 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -19,25 +19,20 @@
  *
  */
 
+#include "common/debug.h"
+#include "common/file.h"
 #include "common/scummsys.h"
-
+#include "common/stream.h"
+#include "common/system.h"
+#include "engines/util.h"
+#include "graphics/blit.h"
+#include "image/tga.h"
 #include "zvision/zvision.h"
+#include "zvision/file/lzss_read_stream.h"
 #include "zvision/graphics/render_manager.h"
 #include "zvision/scripting/script_manager.h"
 #include "zvision/text/text.h"
 
-#include "zvision/file/lzss_read_stream.h"
-
-#include "common/file.h"
-#include "common/system.h"
-#include "common/stream.h"
-
-#include "engines/util.h"
-
-#include "image/tga.h"
-
-#include "graphics/blit.h"
-#include "common/debug.h"
 namespace ZVision {
 
 RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const Graphics::PixelFormat pixelFormat, bool doubleFPS, bool widescreen)
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index 6c475e0ae26..593ef170999 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -22,18 +22,15 @@
 #ifndef ZVISION_RENDER_MANAGER_H
 #define ZVISION_RENDER_MANAGER_H
 
-#include "zvision/graphics/render_table.h"
-#include "zvision/text/truetype_font.h"
-
-#include "common/rect.h"
 #include "common/hashmap.h"
-
-#include "graphics/surface.h"
+#include "common/rect.h"
+#include "graphics/framelimiter.h"
 #include "graphics/managed_surface.h"
 #include "graphics/screen.h"
-#include "graphics/framelimiter.h"
-
+#include "graphics/surface.h"
 #include "zvision/graphics/graphics_effect.h"
+#include "zvision/graphics/render_table.h"
+#include "zvision/text/truetype_font.h"
 
 class OSystem;
 
diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index a1f1135ae46..88aa424b10b 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -19,12 +19,11 @@
  *
  */
 
-#include "zvision/graphics/render_table.h"
-
 #include "common/rect.h"
 #include "common/scummsys.h"
-#include "math/utils.h"
 #include "common/system.h"
+#include "math/utils.h"
+#include "zvision/graphics/render_table.h"
 #include "zvision/scripting/script_manager.h"
 
 namespace ZVision {
@@ -338,7 +337,7 @@ float RenderTable::getAngle() {
 	case PANORAMA:
 		return Math::rad2deg<float>(_panoramaOptions.verticalFOV);
 	default:
-		return 1.0;
+		return 1.0f;
 	}
 }
 
@@ -349,7 +348,7 @@ float RenderTable::getLinscale() {
 	case PANORAMA:
 		return _panoramaOptions.linearScale;
 	default:
-		return 1.0;
+		return 1.0f;
 	}
 }
 
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index 86202eb4005..35a065dddbf 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -22,9 +22,9 @@
 #ifndef ZVISION_RENDER_TABLE_H
 #define ZVISION_RENDER_TABLE_H
 
-#include "zvision/zvision.h"
 #include "common/rect.h"
 #include "graphics/surface.h"
+#include "zvision/zvision.h"
 
 class OSystem;
 namespace ZVision {
diff --git a/engines/zvision/metaengine.cpp b/engines/zvision/metaengine.cpp
index c839d442815..b4e8eef9700 100644
--- a/engines/zvision/metaengine.cpp
+++ b/engines/zvision/metaengine.cpp
@@ -19,22 +19,18 @@
  *
  */
 
-#include "common/scummsys.h"
-
-#include "engines/advancedDetector.h"
-
-#include "zvision/zvision.h"
-#include "zvision/file/save_manager.h"
-#include "zvision/scripting/script_manager.h"
-#include "zvision/detection.h"
-
 #include "backends/keymapper/action.h"
 #include "backends/keymapper/keymapper.h"
 #include "backends/keymapper/standard-actions.h"
-
 #include "common/savefile.h"
+#include "common/scummsys.h"
 #include "common/system.h"
 #include "common/translation.h"
+#include "engines/advancedDetector.h"
+#include "zvision/detection.h"
+#include "zvision/zvision.h"
+#include "zvision/file/save_manager.h"
+#include "zvision/scripting/script_manager.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index bb675f72698..13c726ca321 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -21,28 +21,26 @@
 
 #include "common/scummsys.h"
 #include "video/video_decoder.h"
-
-#include "zvision/scripting/actions.h"
-
 #include "zvision/zvision.h"
-#include "zvision/scripting/script_manager.h"
-#include "zvision/graphics/render_manager.h"
 #include "zvision/file/save_manager.h"
-#include "zvision/scripting/menu.h"
-#include "zvision/scripting/effects/timer_effect.h"
-#include "zvision/scripting/effects/music_effect.h"
-#include "zvision/scripting/effects/syncsound_effect.h"
-#include "zvision/scripting/effects/animation_effect.h"
-#include "zvision/scripting/effects/distort_effect.h"
-#include "zvision/scripting/effects/ttytext_effect.h"
-#include "zvision/scripting/effects/region_effect.h"
-#include "zvision/scripting/controls/titler_control.h"
-#include "zvision/graphics/render_table.h"
 #include "zvision/graphics/graphics_effect.h"
+#include "zvision/graphics/render_manager.h"
+#include "zvision/graphics/render_table.h"
+#include "zvision/graphics/cursors/cursor_manager.h"
 #include "zvision/graphics/effects/fog.h"
 #include "zvision/graphics/effects/light.h"
 #include "zvision/graphics/effects/wave.h"
-#include "zvision/graphics/cursors/cursor_manager.h"
+#include "zvision/scripting/menu.h"
+#include "zvision/scripting/actions.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/scripting/controls/titler_control.h"
+#include "zvision/scripting/effects/animation_effect.h"
+#include "zvision/scripting/effects/distort_effect.h"
+#include "zvision/scripting/effects/music_effect.h"
+#include "zvision/scripting/effects/region_effect.h"
+#include "zvision/scripting/effects/syncsound_effect.h"
+#include "zvision/scripting/effects/timer_effect.h"
+#include "zvision/scripting/effects/ttytext_effect.h"
 #include "zvision/sound/volume_manager.h"
 
 namespace ZVision {
diff --git a/engines/zvision/scripting/actions.h b/engines/zvision/scripting/actions.h
index 437d052cfff..908ed6918b6 100644
--- a/engines/zvision/scripting/actions.h
+++ b/engines/zvision/scripting/actions.h
@@ -23,8 +23,8 @@
 #define ZVISION_ACTIONS_H
 
 #include "common/path.h"
-#include "common/str.h"
 #include "common/rect.h"
+#include "common/str.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/control.cpp b/engines/zvision/scripting/control.cpp
index 08c58e231d2..ea73ddd3ff6 100644
--- a/engines/zvision/scripting/control.cpp
+++ b/engines/zvision/scripting/control.cpp
@@ -19,16 +19,13 @@
  *
  */
 
+#include "common/debug.h"
 #include "common/scummsys.h"
-
-#include "zvision/scripting/control.h"
-#include "zvision/scripting/script_manager.h"
-
+#include "common/stream.h"
 #include "zvision/zvision.h"
 #include "zvision/graphics/render_manager.h"
-
-#include "common/stream.h"
-#include "common/debug.h"
+#include "zvision/scripting/control.h"
+#include "zvision/scripting/script_manager.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/controls/fist_control.cpp b/engines/zvision/scripting/controls/fist_control.cpp
index bfbd3263bd6..d99de8641ec 100644
--- a/engines/zvision/scripting/controls/fist_control.cpp
+++ b/engines/zvision/scripting/controls/fist_control.cpp
@@ -19,20 +19,18 @@
  *
  */
 
+#include "common/file.h"
 #include "common/scummsys.h"
-
-#include "zvision/zvision.h"
-#include "zvision/scripting/script_manager.h"
-#include "zvision/scripting/controls/fist_control.h"
-#include "zvision/graphics/render_manager.h"
-#include "zvision/graphics/cursors/cursor_manager.h"
-#include "zvision/video/rlf_decoder.h"
-
 #include "common/stream.h"
-#include "common/file.h"
 #include "common/system.h"
 #include "graphics/surface.h"
 #include "video/video_decoder.h"
+#include "zvision/zvision.h"
+#include "zvision/graphics/render_manager.h"
+#include "zvision/graphics/cursors/cursor_manager.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/scripting/controls/fist_control.h"
+#include "zvision/video/rlf_decoder.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/controls/fist_control.h b/engines/zvision/scripting/controls/fist_control.h
index 7b7ab780f70..6979d9be38f 100644
--- a/engines/zvision/scripting/controls/fist_control.h
+++ b/engines/zvision/scripting/controls/fist_control.h
@@ -22,10 +22,9 @@
 #ifndef ZVISION_FIST_CONTROL_H
 #define ZVISION_FIST_CONTROL_H
 
-#include "zvision/scripting/control.h"
-
 #include "common/array.h"
 #include "common/rect.h"
+#include "zvision/scripting/control.h"
 
 namespace Video {
 	class VideoDecoder;
diff --git a/engines/zvision/scripting/controls/hotmov_control.cpp b/engines/zvision/scripting/controls/hotmov_control.cpp
index 4b81c89b981..f14c18dd346 100644
--- a/engines/zvision/scripting/controls/hotmov_control.cpp
+++ b/engines/zvision/scripting/controls/hotmov_control.cpp
@@ -19,20 +19,17 @@
  *
  */
 
+#include "common/file.h"
 #include "common/scummsys.h"
-
-#include "zvision/scripting/controls/hotmov_control.h"
-
-#include "zvision/zvision.h"
-#include "zvision/scripting/script_manager.h"
-#include "zvision/graphics/render_manager.h"
-#include "zvision/graphics/cursors/cursor_manager.h"
-
 #include "common/stream.h"
-#include "common/file.h"
 #include "common/system.h"
 #include "graphics/surface.h"
 #include "video/video_decoder.h"
+#include "zvision/zvision.h"
+#include "zvision/graphics/render_manager.h"
+#include "zvision/graphics/cursors/cursor_manager.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/scripting/controls/hotmov_control.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/controls/hotmov_control.h b/engines/zvision/scripting/controls/hotmov_control.h
index cdc6fe85c24..ee2cb235299 100644
--- a/engines/zvision/scripting/controls/hotmov_control.h
+++ b/engines/zvision/scripting/controls/hotmov_control.h
@@ -22,11 +22,10 @@
 #ifndef ZVISION_HOTMOV_CONTROL_H
 #define ZVISION_HOTMOV_CONTROL_H
 
-#include "zvision/scripting/control.h"
-
 #include "common/array.h"
 #include "common/path.h"
 #include "common/rect.h"
+#include "zvision/scripting/control.h"
 
 namespace Video {
 	class VideoDecoder;
diff --git a/engines/zvision/scripting/controls/input_control.cpp b/engines/zvision/scripting/controls/input_control.cpp
index 0228fcc2537..09ac08dd752 100644
--- a/engines/zvision/scripting/controls/input_control.cpp
+++ b/engines/zvision/scripting/controls/input_control.cpp
@@ -19,23 +19,20 @@
  *
  */
 
-#include "common/scummsys.h"
-
-#include "zvision/scripting/controls/input_control.h"
-#include "zvision/graphics/cursors/cursor_manager.h"
-
-#include "zvision/zvision.h"
-#include "zvision/scripting/script_manager.h"
-#include "zvision/text/string_manager.h"
-#include "zvision/graphics/render_manager.h"
-
 #include "backends/keymapper/keymap.h"
-
+#include "common/rect.h"
+#include "common/scummsys.h"
 #include "common/str.h"
 #include "common/stream.h"
 #include "common/system.h"
-#include "common/rect.h"
 #include "video/video_decoder.h"
+#include "zvision/zvision.h"
+#include "zvision/graphics/render_manager.h"
+#include "zvision/graphics/cursors/cursor_manager.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/scripting/controls/input_control.h"
+#include "zvision/text/string_manager.h"
+
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/controls/input_control.h b/engines/zvision/scripting/controls/input_control.h
index b99dd4c0c8b..aa27908c496 100644
--- a/engines/zvision/scripting/controls/input_control.h
+++ b/engines/zvision/scripting/controls/input_control.h
@@ -22,11 +22,10 @@
 #ifndef ZVISION_INPUT_CONTROL_H
 #define ZVISION_INPUT_CONTROL_H
 
+#include "common/rect.h"
 #include "zvision/scripting/control.h"
-#include "zvision/text/text.h"
 #include "zvision/text/string_manager.h"
-
-#include "common/rect.h"
+#include "zvision/text/text.h"
 
 namespace Video {
 	class VideoDecoder;
diff --git a/engines/zvision/scripting/controls/lever_control.cpp b/engines/zvision/scripting/controls/lever_control.cpp
index 802112ddb79..bed9ef55830 100644
--- a/engines/zvision/scripting/controls/lever_control.cpp
+++ b/engines/zvision/scripting/controls/lever_control.cpp
@@ -19,21 +19,18 @@
  *
  */
 
+#include "common/file.h"
 #include "common/scummsys.h"
-
-#include "zvision/scripting/controls/lever_control.h"
-
-#include "zvision/zvision.h"
-#include "zvision/scripting/script_manager.h"
-#include "zvision/graphics/render_manager.h"
-#include "zvision/graphics/cursors/cursor_manager.h"
-
 #include "common/stream.h"
-#include "common/file.h"
-#include "common/tokenizer.h"
 #include "common/system.h"
+#include "common/tokenizer.h"
 #include "graphics/surface.h"
 #include "video/video_decoder.h"
+#include "zvision/zvision.h"
+#include "zvision/graphics/render_manager.h"
+#include "zvision/graphics/cursors/cursor_manager.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/scripting/controls/lever_control.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/controls/lever_control.h b/engines/zvision/scripting/controls/lever_control.h
index 3abb2525866..33a7bca087e 100644
--- a/engines/zvision/scripting/controls/lever_control.h
+++ b/engines/zvision/scripting/controls/lever_control.h
@@ -22,11 +22,10 @@
 #ifndef ZVISION_LEVER_CONTROL_H
 #define ZVISION_LEVER_CONTROL_H
 
-#include "zvision/scripting/control.h"
-
 #include "common/list.h"
 #include "common/path.h"
 #include "common/rect.h"
+#include "zvision/scripting/control.h"
 
 namespace Video {
 	class VideoDecoder;
diff --git a/engines/zvision/scripting/controls/paint_control.cpp b/engines/zvision/scripting/controls/paint_control.cpp
index 2c197704710..55e9f410ef8 100644
--- a/engines/zvision/scripting/controls/paint_control.cpp
+++ b/engines/zvision/scripting/controls/paint_control.cpp
@@ -20,13 +20,11 @@
  */
 
 #include "common/scummsys.h"
-
-#include "zvision/scripting/controls/paint_control.h"
-
 #include "zvision/zvision.h"
-#include "zvision/scripting/script_manager.h"
 #include "zvision/graphics/cursors/cursor_manager.h"
 #include "zvision/graphics/render_manager.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/scripting/controls/paint_control.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/controls/paint_control.h b/engines/zvision/scripting/controls/paint_control.h
index edd6a6d35c0..e02cef0bf9a 100644
--- a/engines/zvision/scripting/controls/paint_control.h
+++ b/engines/zvision/scripting/controls/paint_control.h
@@ -22,12 +22,10 @@
 #ifndef ZVISION_PAINT_CONTROL_H
 #define ZVISION_PAINT_CONTROL_H
 
-#include "zvision/scripting/control.h"
-
-#include "graphics/surface.h"
-
-#include "common/rect.h"
 #include "common/list.h"
+#include "common/rect.h"
+#include "graphics/surface.h"
+#include "zvision/scripting/control.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/controls/push_toggle_control.cpp b/engines/zvision/scripting/controls/push_toggle_control.cpp
index 714a54a53de..acd1cee89b1 100644
--- a/engines/zvision/scripting/controls/push_toggle_control.cpp
+++ b/engines/zvision/scripting/controls/push_toggle_control.cpp
@@ -20,14 +20,11 @@
  */
 
 #include "common/scummsys.h"
-
-#include "zvision/scripting/controls/push_toggle_control.h"
-
+#include "common/stream.h"
 #include "zvision/zvision.h"
-#include "zvision/scripting/script_manager.h"
 #include "zvision/graphics/cursors/cursor_manager.h"
-
-#include "common/stream.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/scripting/controls/push_toggle_control.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/controls/push_toggle_control.h b/engines/zvision/scripting/controls/push_toggle_control.h
index cafd9adb87b..c8259a2bef3 100644
--- a/engines/zvision/scripting/controls/push_toggle_control.h
+++ b/engines/zvision/scripting/controls/push_toggle_control.h
@@ -22,11 +22,10 @@
 #ifndef ZVISION_PUSH_TOGGLE_CONTROL_H
 #define ZVISION_PUSH_TOGGLE_CONTROL_H
 
-#include "zvision/scripting/control.h"
-
-#include "common/rect.h"
-#include "common/events.h"
 #include "common/array.h"
+#include "common/events.h"
+#include "common/rect.h"
+#include "zvision/scripting/control.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/controls/safe_control.cpp b/engines/zvision/scripting/controls/safe_control.cpp
index cb2585144dc..36ede185d4b 100644
--- a/engines/zvision/scripting/controls/safe_control.cpp
+++ b/engines/zvision/scripting/controls/safe_control.cpp
@@ -19,21 +19,18 @@
  *
  */
 
+#include "common/file.h"
 #include "common/scummsys.h"
-
-#include "zvision/scripting/controls/safe_control.h"
-
-#include "zvision/zvision.h"
-#include "zvision/scripting/script_manager.h"
-#include "zvision/graphics/render_manager.h"
-#include "zvision/graphics/cursors/cursor_manager.h"
-
 #include "common/stream.h"
-#include "common/file.h"
-#include "common/tokenizer.h"
 #include "common/system.h"
+#include "common/tokenizer.h"
 #include "graphics/surface.h"
 #include "video/video_decoder.h"
+#include "zvision/zvision.h"
+#include "zvision/graphics/render_manager.h"
+#include "zvision/graphics/cursors/cursor_manager.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/scripting/controls/safe_control.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/controls/safe_control.h b/engines/zvision/scripting/controls/safe_control.h
index 5bf0e51f5c2..1888e6c11fa 100644
--- a/engines/zvision/scripting/controls/safe_control.h
+++ b/engines/zvision/scripting/controls/safe_control.h
@@ -22,10 +22,9 @@
 #ifndef ZVISION_SAFE_CONTROL_H
 #define ZVISION_SAFE_CONTROL_H
 
-#include "zvision/scripting/control.h"
-
 #include "common/list.h"
 #include "common/rect.h"
+#include "zvision/scripting/control.h"
 
 namespace Video {
 	class VideoDecoder;
diff --git a/engines/zvision/scripting/controls/save_control.cpp b/engines/zvision/scripting/controls/save_control.cpp
index 55d7581396d..5d66933c121 100644
--- a/engines/zvision/scripting/controls/save_control.cpp
+++ b/engines/zvision/scripting/controls/save_control.cpp
@@ -20,20 +20,16 @@
  */
 
 #include "common/scummsys.h"
-
-#include "zvision/scripting/controls/input_control.h"
-#include "zvision/scripting/controls/save_control.h"
-
+#include "common/str.h"
+#include "common/stream.h"
 #include "zvision/zvision.h"
+#include "zvision/file/save_manager.h"
 #include "zvision/scripting/script_manager.h"
+#include "zvision/scripting/controls/input_control.h"
+#include "zvision/scripting/controls/save_control.h"
 #include "zvision/text/string_manager.h"
-
-#include "zvision/file/save_manager.h"
 #include "zvision/text/subtitle_manager.h"
 
-#include "common/str.h"
-#include "common/stream.h"
-
 namespace ZVision {
 
 SaveControl::SaveControl(ZVision *engine, uint32 key, Common::SeekableReadStream &stream)
diff --git a/engines/zvision/scripting/controls/save_control.h b/engines/zvision/scripting/controls/save_control.h
index d95fc2ac1af..d6e68868ea0 100644
--- a/engines/zvision/scripting/controls/save_control.h
+++ b/engines/zvision/scripting/controls/save_control.h
@@ -22,9 +22,8 @@
 #ifndef ZVISION_SAVE_CONTROL_H
 #define ZVISION_SAVE_CONTROL_H
 
-#include "zvision/scripting/control.h"
-
 #include "common/list.h"
+#include "zvision/scripting/control.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/controls/slot_control.cpp b/engines/zvision/scripting/controls/slot_control.cpp
index b4b0ce76bfd..db1c5d2cce1 100644
--- a/engines/zvision/scripting/controls/slot_control.cpp
+++ b/engines/zvision/scripting/controls/slot_control.cpp
@@ -20,15 +20,12 @@
  */
 
 #include "common/scummsys.h"
-
-#include "zvision/scripting/controls/slot_control.h"
-
+#include "common/stream.h"
 #include "zvision/zvision.h"
-#include "zvision/scripting/script_manager.h"
 #include "zvision/graphics/cursors/cursor_manager.h"
 #include "zvision/graphics/render_manager.h"
-
-#include "common/stream.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/scripting/controls/slot_control.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/controls/slot_control.h b/engines/zvision/scripting/controls/slot_control.h
index 4b06a294a41..bffa38c4776 100644
--- a/engines/zvision/scripting/controls/slot_control.h
+++ b/engines/zvision/scripting/controls/slot_control.h
@@ -22,12 +22,10 @@
 #ifndef ZVISION_SLOT_CONTROL_H
 #define ZVISION_SLOT_CONTROL_H
 
-#include "zvision/scripting/control.h"
-
-#include "graphics/surface.h"
-
-#include "common/rect.h"
 #include "common/list.h"
+#include "common/rect.h"
+#include "graphics/surface.h"
+#include "zvision/scripting/control.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/controls/titler_control.cpp b/engines/zvision/scripting/controls/titler_control.cpp
index 8871a3f498f..bd20fb91004 100644
--- a/engines/zvision/scripting/controls/titler_control.cpp
+++ b/engines/zvision/scripting/controls/titler_control.cpp
@@ -20,15 +20,12 @@
  */
 
 #include "common/scummsys.h"
-
-#include "zvision/scripting/controls/titler_control.h"
-
+#include "common/stream.h"
 #include "zvision/zvision.h"
-#include "zvision/text/text.h"
-#include "zvision/scripting/script_manager.h"
 #include "zvision/graphics/render_manager.h"
-
-#include "common/stream.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/scripting/controls/titler_control.h"
+#include "zvision/text/text.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/controls/titler_control.h b/engines/zvision/scripting/controls/titler_control.h
index 254dfc0ddf4..5d8926e4a3a 100644
--- a/engines/zvision/scripting/controls/titler_control.h
+++ b/engines/zvision/scripting/controls/titler_control.h
@@ -22,13 +22,11 @@
 #ifndef ZVISION_TITLER_CONTROL_H
 #define ZVISION_TITLER_CONTROL_H
 
-#include "zvision/scripting/control.h"
-
-#include "graphics/surface.h"
-
+#include "common/array.h"
 #include "common/path.h"
 #include "common/rect.h"
-#include "common/array.h"
+#include "graphics/surface.h"
+#include "zvision/scripting/control.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/effects/animation_effect.cpp b/engines/zvision/scripting/effects/animation_effect.cpp
index 928cd4eba72..b3e62896c7c 100644
--- a/engines/zvision/scripting/effects/animation_effect.cpp
+++ b/engines/zvision/scripting/effects/animation_effect.cpp
@@ -20,15 +20,12 @@
  */
 
 #include "common/scummsys.h"
-
-#include "zvision/scripting/effects/animation_effect.h"
-
+#include "graphics/surface.h"
+#include "video/video_decoder.h"
 #include "zvision/zvision.h"
 #include "zvision/graphics/render_manager.h"
 #include "zvision/scripting/script_manager.h"
-
-#include "graphics/surface.h"
-#include "video/video_decoder.h"
+#include "zvision/scripting/effects/animation_effect.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/effects/animation_effect.h b/engines/zvision/scripting/effects/animation_effect.h
index 0124ed82e68..2994ea14a4a 100644
--- a/engines/zvision/scripting/effects/animation_effect.h
+++ b/engines/zvision/scripting/effects/animation_effect.h
@@ -22,10 +22,10 @@
 #ifndef ZVISION_ANIMATION_NODE_H
 #define ZVISION_ANIMATION_NODE_H
 
-#include "zvision/scripting/scripting_effect.h"
+#include "common/list.h"
 #include "common/path.h"
 #include "common/rect.h"
-#include "common/list.h"
+#include "zvision/scripting/scripting_effect.h"
 
 namespace Graphics {
 struct Surface;
diff --git a/engines/zvision/scripting/effects/distort_effect.cpp b/engines/zvision/scripting/effects/distort_effect.cpp
index b89d8e5425b..fbb0eb63018 100644
--- a/engines/zvision/scripting/effects/distort_effect.cpp
+++ b/engines/zvision/scripting/effects/distort_effect.cpp
@@ -20,15 +20,13 @@
  */
 
 #include "common/scummsys.h"
-
-#include "zvision/scripting/effects/distort_effect.h"
-
+#include "common/stream.h"
 #include "zvision/zvision.h"
-#include "zvision/scripting/script_manager.h"
 #include "zvision/graphics/render_manager.h"
 #include "zvision/graphics/render_table.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/scripting/effects/distort_effect.h"
 
-#include "common/stream.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index 7d76ab0f9fa..dbd399b66ab 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -19,23 +19,21 @@
  *
  */
 
+#include "audio/decoders/wave.h"
+#include "common/file.h"
 #include "common/scummsys.h"
-
-#include "zvision/scripting/effects/music_effect.h"
-
+#include "common/stream.h"
+#include "math/utils.h"
+#include "math/angle.h"
 #include "zvision/zvision.h"
-#include "zvision/scripting/script_manager.h"
 #include "zvision/graphics/render_manager.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/scripting/effects/music_effect.h"
 #include "zvision/sound/midi.h"
+#include "zvision/sound/volume_manager.h"
 #include "zvision/sound/zork_raw.h"
 
-#include "zvision/sound/volume_manager.h"
-#include "common/stream.h"
-#include "common/file.h"
-#include "audio/decoders/wave.h"
 
-#include "math/utils.h"
-#include "math/angle.h"
 namespace ZVision {
 
 void MusicNodeBASE::setDirection(Math::Angle azimuth, uint8 magnitude) {
diff --git a/engines/zvision/scripting/effects/music_effect.h b/engines/zvision/scripting/effects/music_effect.h
index 8685c4c56af..dc9d0d14af1 100644
--- a/engines/zvision/scripting/effects/music_effect.h
+++ b/engines/zvision/scripting/effects/music_effect.h
@@ -23,10 +23,10 @@
 #define ZVISION_MUSIC_NODE_H
 
 #include "audio/mixer.h"
+#include "math/angle.h"
 #include "zvision/scripting/scripting_effect.h"
-#include "zvision/text/subtitle_manager.h"
 #include "zvision/sound/volume_manager.h"
-#include "math/angle.h"
+#include "zvision/text/subtitle_manager.h"
 
 namespace Common {
 class String;
diff --git a/engines/zvision/scripting/effects/region_effect.cpp b/engines/zvision/scripting/effects/region_effect.cpp
index df275db713b..ce4acf35423 100644
--- a/engines/zvision/scripting/effects/region_effect.cpp
+++ b/engines/zvision/scripting/effects/region_effect.cpp
@@ -20,12 +20,10 @@
  */
 
 #include "common/scummsys.h"
-
-#include "zvision/scripting/effects/region_effect.h"
-
 #include "zvision/zvision.h"
-#include "zvision/scripting/script_manager.h"
 #include "zvision/graphics/render_manager.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/scripting/effects/region_effect.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/effects/region_effect.h b/engines/zvision/scripting/effects/region_effect.h
index 1743e88a7e8..610d59c6e9b 100644
--- a/engines/zvision/scripting/effects/region_effect.h
+++ b/engines/zvision/scripting/effects/region_effect.h
@@ -23,9 +23,8 @@
 #define ZVISION_REGION_NODE_H
 
 #include "graphics/surface.h"
-
-#include "zvision/scripting/scripting_effect.h"
 #include "zvision/graphics/graphics_effect.h"
+#include "zvision/scripting/scripting_effect.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/effects/syncsound_effect.cpp b/engines/zvision/scripting/effects/syncsound_effect.cpp
index 2db53852b21..67537981fad 100644
--- a/engines/zvision/scripting/effects/syncsound_effect.cpp
+++ b/engines/zvision/scripting/effects/syncsound_effect.cpp
@@ -19,18 +19,16 @@
  *
  */
 
+#include "audio/decoders/wave.h"
+#include "common/file.h"
 #include "common/scummsys.h"
-
-#include "zvision/scripting/effects/syncsound_effect.h"
-
+#include "common/stream.h"
 #include "zvision/zvision.h"
-#include "zvision/scripting/script_manager.h"
 #include "zvision/graphics/render_manager.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/scripting/effects/syncsound_effect.h"
 #include "zvision/sound/zork_raw.h"
 
-#include "common/stream.h"
-#include "common/file.h"
-#include "audio/decoders/wave.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/effects/timer_effect.cpp b/engines/zvision/scripting/effects/timer_effect.cpp
index 44d6dc77f52..028d7250ef6 100644
--- a/engines/zvision/scripting/effects/timer_effect.cpp
+++ b/engines/zvision/scripting/effects/timer_effect.cpp
@@ -20,13 +20,10 @@
  */
 
 #include "common/scummsys.h"
-
-#include "zvision/scripting/effects/timer_effect.h"
-
+#include "common/stream.h"
 #include "zvision/zvision.h"
 #include "zvision/scripting/script_manager.h"
-
-#include "common/stream.h"
+#include "zvision/scripting/effects/timer_effect.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/effects/ttytext_effect.cpp b/engines/zvision/scripting/effects/ttytext_effect.cpp
index eaf21067e96..2829f0652b1 100644
--- a/engines/zvision/scripting/effects/ttytext_effect.cpp
+++ b/engines/zvision/scripting/effects/ttytext_effect.cpp
@@ -19,19 +19,16 @@
  *
  */
 
+#include "common/file.h"
 #include "common/scummsys.h"
-
-#include "zvision/scripting/effects/ttytext_effect.h"
-
+#include "common/stream.h"
+#include "common/unicode-bidi.h"
 #include "zvision/zvision.h"
-#include "zvision/scripting/script_manager.h"
 #include "zvision/graphics/render_manager.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/scripting/effects/ttytext_effect.h"
 #include "zvision/text/text.h"
 
-#include "common/stream.h"
-#include "common/file.h"
-#include "common/unicode-bidi.h"
-
 namespace ZVision {
 
 ttyTextNode::ttyTextNode(ZVision *engine, uint32 key, const Common::Path &file, const Common::Rect &r, int32 delay) :
diff --git a/engines/zvision/scripting/effects/ttytext_effect.h b/engines/zvision/scripting/effects/ttytext_effect.h
index 1a84716682e..add5ef97e07 100644
--- a/engines/zvision/scripting/effects/ttytext_effect.h
+++ b/engines/zvision/scripting/effects/ttytext_effect.h
@@ -24,7 +24,6 @@
 
 #include "common/rect.h"
 #include "graphics/surface.h"
-
 #include "zvision/scripting/scripting_effect.h"
 #include "zvision/text/text.h"
 #include "zvision/text/truetype_font.h"
diff --git a/engines/zvision/scripting/inventory.cpp b/engines/zvision/scripting/inventory.cpp
index 4b74cce3a55..7f6cb0b4049 100644
--- a/engines/zvision/scripting/inventory.cpp
+++ b/engines/zvision/scripting/inventory.cpp
@@ -20,7 +20,6 @@
  */
 
 #include "common/scummsys.h"
-
 #include "zvision/scripting/script_manager.h"
 
 namespace ZVision {
diff --git a/engines/zvision/scripting/menu.h b/engines/zvision/scripting/menu.h
index b7d8a0588c3..194fa84071c 100644
--- a/engines/zvision/scripting/menu.h
+++ b/engines/zvision/scripting/menu.h
@@ -22,15 +22,14 @@
 #ifndef ZVISION_MENU_H
 #define ZVISION_MENU_H
 
-#include "graphics/surface.h"
-#include "common/rect.h"
 #include "common/array.h"
 #include "common/bitarray.h"
-
+#include "common/rect.h"
+#include "graphics/surface.h"
 #include "zvision/zvision.h"
-#include "zvision/scripting/script_manager.h"
-#include "zvision/common/scroller.h"
 #include "zvision/common/focus_list.h"
+#include "zvision/common/scroller.h"
+#include "zvision/scripting/script_manager.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/puzzle.h b/engines/zvision/scripting/puzzle.h
index 095f73c42c3..0f19691b56f 100644
--- a/engines/zvision/scripting/puzzle.h
+++ b/engines/zvision/scripting/puzzle.h
@@ -22,10 +22,9 @@
 #ifndef ZVISION_PUZZLE_H
 #define ZVISION_PUZZLE_H
 
-#include "zvision/scripting/actions.h"
-
 #include "common/list.h"
 #include "common/ptr.h"
+#include "zvision/scripting/actions.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/scripting/scr_file_handling.cpp b/engines/zvision/scripting/scr_file_handling.cpp
index fa1a652d122..21bbeda4689 100644
--- a/engines/zvision/scripting/scr_file_handling.cpp
+++ b/engines/zvision/scripting/scr_file_handling.cpp
@@ -19,29 +19,26 @@
  *
  */
 
+#include "common/file.h"
 #include "common/scummsys.h"
 #include "common/str.h"
-
+#include "common/textconsole.h"
+#include "common/tokenizer.h"
 #include "zvision/zvision.h"
-#include "zvision/scripting/script_manager.h"
-
-#include "zvision/scripting/puzzle.h"
 #include "zvision/scripting/actions.h"
-#include "zvision/scripting/controls/push_toggle_control.h"
-#include "zvision/scripting/controls/lever_control.h"
-#include "zvision/scripting/controls/slot_control.h"
-#include "zvision/scripting/controls/save_control.h"
-#include "zvision/scripting/controls/input_control.h"
-#include "zvision/scripting/controls/safe_control.h"
-#include "zvision/scripting/controls/hotmov_control.h"
+#include "zvision/scripting/puzzle.h"
+#include "zvision/scripting/script_manager.h"
 #include "zvision/scripting/controls/fist_control.h"
+#include "zvision/scripting/controls/hotmov_control.h"
+#include "zvision/scripting/controls/input_control.h"
+#include "zvision/scripting/controls/lever_control.h"
 #include "zvision/scripting/controls/paint_control.h"
+#include "zvision/scripting/controls/push_toggle_control.h"
+#include "zvision/scripting/controls/safe_control.h"
+#include "zvision/scripting/controls/save_control.h"
+#include "zvision/scripting/controls/slot_control.h"
 #include "zvision/scripting/controls/titler_control.h"
 
-#include "common/textconsole.h"
-#include "common/file.h"
-#include "common/tokenizer.h"
-
 namespace ZVision {
 
 void ScriptManager::parseScrFile(const Common::Path &fileName, ScriptScope &scope) {
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index 3ff937d6d8c..41019287c28 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -19,24 +19,21 @@
  *
  */
 
+#include "common/algorithm.h"
+#include "common/config-manager.h"
+#include "common/debug.h"
+#include "common/hashmap.h"
 #include "common/scummsys.h"
-
-#include "zvision/scripting/script_manager.h"
-
+#include "common/stream.h"
 #include "zvision/zvision.h"
+#include "zvision/file/save_manager.h"
 #include "zvision/graphics/render_manager.h"
 #include "zvision/graphics/cursors/cursor_manager.h"
-#include "zvision/file/save_manager.h"
 #include "zvision/scripting/actions.h"
 #include "zvision/scripting/menu.h"
+#include "zvision/scripting/script_manager.h"
 #include "zvision/scripting/effects/timer_effect.h"
 
-#include "common/algorithm.h"
-#include "common/hashmap.h"
-#include "common/debug.h"
-#include "common/stream.h"
-#include "common/config-manager.h"
-
 namespace ZVision {
 
 ScriptManager::ScriptManager(ZVision *engine)
diff --git a/engines/zvision/scripting/script_manager.h b/engines/zvision/scripting/script_manager.h
index b8dd5722051..33cca6d7ae6 100644
--- a/engines/zvision/scripting/script_manager.h
+++ b/engines/zvision/scripting/script_manager.h
@@ -22,13 +22,12 @@
 #ifndef ZVISION_SCRIPT_MANAGER_H
 #define ZVISION_SCRIPT_MANAGER_H
 
-#include "zvision/scripting/puzzle.h"
-#include "zvision/scripting/control.h"
-#include "zvision/scripting/scripting_effect.h"
-
+#include "common/events.h"
 #include "common/hashmap.h"
 #include "common/queue.h"
-#include "common/events.h"
+#include "zvision/scripting/control.h"
+#include "zvision/scripting/puzzle.h"
+#include "zvision/scripting/scripting_effect.h"
 
 namespace Common {
 class String;
diff --git a/engines/zvision/sound/midi.cpp b/engines/zvision/sound/midi.cpp
index 6006bbfd2b9..2729302478d 100644
--- a/engines/zvision/sound/midi.cpp
+++ b/engines/zvision/sound/midi.cpp
@@ -19,12 +19,11 @@
  *
  */
 
+#include "audio/mididrv.h"
+#include "common/debug.h"
 #include "common/scummsys.h"
 #include "common/textconsole.h"
-#include "audio/mididrv.h"
-
 #include "zvision/sound/midi.h"
-#include "common/debug.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/sound/volume_manager.cpp b/engines/zvision/sound/volume_manager.cpp
index a18dc555eed..79d931d1a2c 100644
--- a/engines/zvision/sound/volume_manager.cpp
+++ b/engines/zvision/sound/volume_manager.cpp
@@ -19,9 +19,9 @@
  *
  */
 
-#include "zvision/sound/volume_manager.h"
-#include "zvision/scripting/script_manager.h"
 #include "common/debug.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/sound/volume_manager.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/sound/zork_raw.cpp b/engines/zvision/sound/zork_raw.cpp
index 2f74c964b59..32f9d92752d 100644
--- a/engines/zvision/sound/zork_raw.cpp
+++ b/engines/zvision/sound/zork_raw.cpp
@@ -19,19 +19,18 @@
  *
  */
 
-#include "common/scummsys.h"
+#include "audio/audiostream.h"
+#include "audio/decoders/raw.h"
+#include "common/bufferedstream.h"
 #include "common/file.h"
+#include "common/memstream.h"
+#include "common/scummsys.h"
 #include "common/str.h"
 #include "common/stream.h"
-#include "common/memstream.h"
-#include "common/bufferedstream.h"
-#include "common/util.h"
 #include "common/tokenizer.h"
-#include "audio/audiostream.h"
-#include "audio/decoders/raw.h"
-
-#include "zvision/sound/zork_raw.h"
+#include "common/util.h"
 #include "zvision/zvision.h"
+#include "zvision/sound/zork_raw.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/text/string_manager.cpp b/engines/zvision/text/string_manager.cpp
index e8bb67923db..7019ef458ee 100644
--- a/engines/zvision/text/string_manager.cpp
+++ b/engines/zvision/text/string_manager.cpp
@@ -19,12 +19,11 @@
  *
  */
 
-#include "common/scummsys.h"
+#include "common/debug.h"
 #include "common/file.h"
+#include "common/scummsys.h"
 #include "common/tokenizer.h"
-#include "common/debug.h"
 #include "graphics/fontman.h"
-
 #include "zvision/zvision.h"
 #include "zvision/file/search_manager.h"
 #include "zvision/text/string_manager.h"
diff --git a/engines/zvision/text/subtitle_manager.cpp b/engines/zvision/text/subtitle_manager.cpp
index 3fe225b6456..eb367f2193f 100644
--- a/engines/zvision/text/subtitle_manager.cpp
+++ b/engines/zvision/text/subtitle_manager.cpp
@@ -19,12 +19,12 @@
  *
  */
 
+#include "common/system.h"
+#include "zvision/file/search_manager.h"
 #include "zvision/graphics/render_manager.h"
+#include "zvision/scripting/script_manager.h"
 #include "zvision/text/subtitle_manager.h"
-#include "zvision/file/search_manager.h"
 #include "zvision/text/text.h"
-#include "common/system.h"
-#include "zvision/scripting/script_manager.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/text/subtitle_manager.h b/engines/zvision/text/subtitle_manager.h
index 28c4cea5b1d..579665f57d1 100644
--- a/engines/zvision/text/subtitle_manager.h
+++ b/engines/zvision/text/subtitle_manager.h
@@ -22,9 +22,9 @@
 #ifndef ZVISION_SUBTITLES_H
 #define ZVISION_SUBTITLES_H
 
+#include "audio/mixer.h"
 #include "zvision/zvision.h"
 #include "zvision/common/focus_list.h"
-#include "audio/mixer.h"
 
 namespace ZVision {
 
@@ -39,7 +39,7 @@ public:
 	bool update(int32 count); // Return true if necessary to redraw
 	virtual bool selfUpdate() {
 		return false;
-	};
+	}
 
 protected:
 	virtual bool process(int32 deltatime);  // Return true if to be deleted
@@ -67,7 +67,7 @@ protected:
 class AutomaticSubtitle : public Subtitle {
 public:
 	AutomaticSubtitle(ZVision *engine, const Common::Path &subname, Audio::SoundHandle handle);  // For scripted audio subtitles
-	~AutomaticSubtitle() {};
+	~AutomaticSubtitle() {}
 
 private:
 	bool process(int32 deltatime);  // Return true if to be deleted
diff --git a/engines/zvision/text/text.cpp b/engines/zvision/text/text.cpp
index 2b4bbff6587..3f6368f57c6 100644
--- a/engines/zvision/text/text.cpp
+++ b/engines/zvision/text/text.cpp
@@ -19,20 +19,19 @@
  *
  */
 
-#include "common/scummsys.h"
-#include "common/file.h"
-#include "common/tokenizer.h"
 #include "common/debug.h"
+#include "common/file.h"
 #include "common/rect.h"
+#include "common/scummsys.h"
+#include "common/tokenizer.h"
+#include "graphics/font.h"
 #include "graphics/fontman.h"
 #include "graphics/surface.h"
-#include "graphics/font.h"
 #include "graphics/fonts/ttf.h"
-
-#include "zvision/text/text.h"
 #include "zvision/graphics/render_manager.h"
-#include "zvision/text/truetype_font.h"
 #include "zvision/scripting/script_manager.h"
+#include "zvision/text/text.h"
+#include "zvision/text/truetype_font.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/text/text.h b/engines/zvision/text/text.h
index fd59b7b0a46..a04f694c985 100644
--- a/engines/zvision/text/text.h
+++ b/engines/zvision/text/text.h
@@ -23,8 +23,8 @@
 #ifndef ZVISION_TEXT_H
 #define ZVISION_TEXT_H
 
-#include "zvision/text/truetype_font.h"
 #include "zvision/zvision.h"
+#include "zvision/text/truetype_font.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/text/truetype_font.cpp b/engines/zvision/text/truetype_font.cpp
index 83d9a1422ec..78dfe0488c7 100644
--- a/engines/zvision/text/truetype_font.cpp
+++ b/engines/zvision/text/truetype_font.cpp
@@ -19,18 +19,17 @@
  *
  */
 
-#include "common/scummsys.h"
 #include "common/config-manager.h"
 #include "common/debug.h"
 #include "common/file.h"
+#include "common/scummsys.h"
 #include "common/system.h"
-#include "common/compression/unzip.h"
 #include "common/unicode-bidi.h"
 #include "common/ustr.h"
+#include "common/compression/unzip.h"
 #include "graphics/font.h"
-#include "graphics/fonts/ttf.h"
 #include "graphics/surface.h"
-
+#include "graphics/fonts/ttf.h"
 #include "zvision/zvision.h"
 #include "zvision/graphics/render_manager.h"
 #include "zvision/text/truetype_font.h"
diff --git a/engines/zvision/video/rlf_decoder.cpp b/engines/zvision/video/rlf_decoder.cpp
index 48cbc9073fd..4e9f9444f76 100644
--- a/engines/zvision/video/rlf_decoder.cpp
+++ b/engines/zvision/video/rlf_decoder.cpp
@@ -19,15 +19,13 @@
  *
  */
 
+#include "common/debug.h"
+#include "common/endian.h"
+#include "common/file.h"
 #include "common/scummsys.h"
-
-#include "zvision/video/rlf_decoder.h"
-
 #include "common/str.h"
-#include "common/file.h"
 #include "common/textconsole.h"
-#include "common/debug.h"
-#include "common/endian.h"
+#include "zvision/video/rlf_decoder.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/video/rlf_decoder.h b/engines/zvision/video/rlf_decoder.h
index 27b117f3648..da9bb103c82 100644
--- a/engines/zvision/video/rlf_decoder.h
+++ b/engines/zvision/video/rlf_decoder.h
@@ -23,9 +23,8 @@
 #define ZVISION_RLF_DECODER_H
 
 #include "common/file.h"
-#include "video/video_decoder.h"
-
 #include "graphics/surface.h"
+#include "video/video_decoder.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/video/video.cpp b/engines/zvision/video/video.cpp
index 07a0a980c2d..ff4224c3fbc 100644
--- a/engines/zvision/video/video.cpp
+++ b/engines/zvision/video/video.cpp
@@ -19,17 +19,15 @@
  *
  */
 
+#include "backends/keymapper/keymap.h"
 #include "common/scummsys.h"
 #include "common/system.h"
+#include "engines/util.h"
+#include "graphics/surface.h"
 #include "video/video_decoder.h"
 #if defined(USE_MPEG2) && defined(USE_A52)
 #include "video/mpegps_decoder.h"
 #endif
-#include "engines/util.h"
-#include "graphics/surface.h"
-
-#include "backends/keymapper/keymap.h"
-
 #include "zvision/zvision.h"
 #include "zvision/core/clock.h"
 #include "zvision/graphics/render_manager.h"
diff --git a/engines/zvision/video/zork_avi_decoder.cpp b/engines/zvision/video/zork_avi_decoder.cpp
index 7137ceabdfc..61f23183fd8 100644
--- a/engines/zvision/video/zork_avi_decoder.cpp
+++ b/engines/zvision/video/zork_avi_decoder.cpp
@@ -19,16 +19,12 @@
  *
  */
 
-#include "common/scummsys.h"
-
-#include "zvision/video/zork_avi_decoder.h"
-
-#include "zvision/sound/zork_raw.h"
-
-#include "common/stream.h"
-
 #include "audio/audiostream.h"
 #include "audio/decoders/raw.h"
+#include "common/scummsys.h"
+#include "common/stream.h"
+#include "zvision/sound/zork_raw.h"
+#include "zvision/video/zork_avi_decoder.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index a2ae4cd4fa6..4d776ba8a6e 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -19,40 +19,36 @@
  *
  */
 
-#include "common/scummsys.h"
-
-#include "zvision/zvision.h"
-#include "zvision/core/console.h"
-#include "zvision/scripting/script_manager.h"
-#include "zvision/graphics/render_manager.h"
-#include "zvision/text/subtitle_manager.h"
-#include "zvision/graphics/cursors/cursor_manager.h"
-#include "zvision/file/save_manager.h"
-#include "zvision/text/string_manager.h"
-#include "zvision/scripting/menu.h"
-#include "zvision/file/search_manager.h"
-#include "zvision/text/text.h"
-#include "zvision/text/truetype_font.h"
-#include "zvision/sound/midi.h"
-#include "zvision/sound/volume_manager.h"
-
+#include "audio/mixer.h"
 #include "backends/keymapper/keymap.h"
 #include "backends/keymapper/keymapper.h"
-
 #include "common/config-manager.h"
-#include "common/str.h"
 #include "common/debug.h"
 #include "common/debug-channels.h"
+#include "common/error.h"
+#include "common/file.h"
+#include "common/scummsys.h"
+#include "common/str.h"
+#include "common/system.h"
 #include "common/textconsole.h"
 #include "common/timer.h"
 #include "common/translation.h"
-#include "common/error.h"
-#include "common/system.h"
-#include "common/file.h"
-
-#include "gui/message.h"
 #include "engines/util.h"
-#include "audio/mixer.h"
+#include "gui/message.h"
+#include "zvision/zvision.h"
+#include "zvision/core/console.h"
+#include "zvision/file/save_manager.h"
+#include "zvision/file/search_manager.h"
+#include "zvision/graphics/render_manager.h"
+#include "zvision/graphics/cursors/cursor_manager.h"
+#include "zvision/scripting/menu.h"
+#include "zvision/scripting/script_manager.h"
+#include "zvision/sound/midi.h"
+#include "zvision/sound/volume_manager.h"
+#include "zvision/text/string_manager.h"
+#include "zvision/text/subtitle_manager.h"
+#include "zvision/text/text.h"
+#include "zvision/text/truetype_font.h"
 
 namespace ZVision {
 
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index bce27cf0471..4cc9e708557 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -23,18 +23,14 @@
 #ifndef ZVISION_ZVISION_H
 #define ZVISION_ZVISION_H
 
-#include "zvision/core/clock.h"
-#include "zvision/file/search_manager.h"
-#include "zvision/detection.h"
-
 #include "common/random.h"
 #include "common/events.h"
-
 #include "engines/engine.h"
-
 #include "graphics/pixelformat.h"
-
 #include "gui/debugger.h"
+#include "zvision/detection.h"
+#include "zvision/core/clock.h"
+#include "zvision/file/search_manager.h"
 
 namespace Common {
 class Keymap;


Commit: 8c196ada85059f7061a271140913aae81b0f285f
    https://github.com/scummvm/scummvm/commit/8c196ada85059f7061a271140913aae81b0f285f
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:01+02:00

Commit Message:
ZVISION: Code formatting compliance; remove spurious semicolons.
Make appropriate methods const.

Changed paths:
    engines/zvision/scripting/menu.cpp
    engines/zvision/scripting/menu.h
    engines/zvision/sound/midi.h
    engines/zvision/sound/volume_manager.h


diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index 29bb27ab7c9..87269532215 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -280,7 +280,7 @@ MenuZGI::~MenuZGI() {
 	}
 }
 
-bool MenuZGI::inMenu(const Common::Point &Pos) {
+bool MenuZGI::inMenu(const Common::Point &Pos) const {
 	return _menuTriggerArea.contains(Pos) || (_menuFocus.front() != kFocusNone);
 }
 
@@ -575,7 +575,7 @@ MenuNemesis::~MenuNemesis() {
 
 }
 
-bool MenuNemesis::inMenu(const Common::Point &Pos) {
+bool MenuNemesis::inMenu(const Common::Point &Pos) const {
 	return _menuTriggerArea.contains(Pos) || (_menuFocus.front() != kFocusNone);
 }
 
diff --git a/engines/zvision/scripting/menu.h b/engines/zvision/scripting/menu.h
index 194fa84071c..689c90dd976 100644
--- a/engines/zvision/scripting/menu.h
+++ b/engines/zvision/scripting/menu.h
@@ -91,26 +91,26 @@ public:
 	virtual void onMouseDown(const Common::Point &Pos);
 	virtual void onMouseUp(const Common::Point &Pos);
 	virtual void process(uint32 deltaTimeInMillis);
-	bool inMenu() {
+	bool inMenu() const {
 		return _prevInMenu;
-	};
-	virtual bool inMenu(const Common::Point &Pos) {
+	}
+	virtual bool inMenu(const Common::Point &Pos) const {
 		return false;
-	}; // For widescreen mod; used to suspend panning, tilting & scripting triggers when the mouse is within the working window but also in the menu.
+	} // For widescreen mod; used to suspend panning, tilting & scripting triggers when the mouse is within the working window but also in the menu.
 
 	void mainMouseDown(const Common::Point &Pos); // Show clicked graphic under selected button
 	bool mainMouseMove(const Common::Point &Pos); // return true if selected button has changed
 
 	void setEnable(uint16 flags);
-	uint16 getEnable() {
+	uint16 getEnable() const {
 		return _menuBarFlag;
 	}
-	bool getEnable(uint8 flag) {
+	bool getEnable(uint8 flag) const {
 		return _enableFlags.get(flag);
 	}
 
 protected:
-	virtual void redrawAll() {};
+	virtual void redrawAll() {}
 	void redrawMain();
 	int mouseOverMain(const Common::Point &Pos);
 	void setFocus(int8 currentFocus);
@@ -146,7 +146,7 @@ public:
 	void onMouseMove(const Common::Point &Pos) override;  // NB Pos is in screen coordinates
 	void onMouseUp(const Common::Point &Pos) override;
 	void process(uint32 deltaTimeInMillis) override;
-	bool inMenu(const Common::Point &Pos) override;
+	bool inMenu(const Common::Point &Pos) const override;
 private:
 	void redrawAll() override;
 	Graphics::Surface _menuBack[3];
@@ -182,7 +182,7 @@ public:
 	MenuNemesis(ZVision *engine, Common::Rect menuArea);
 	~MenuNemesis() override;
 	void onMouseMove(const Common::Point &Pos) override;
-	bool inMenu(const Common::Point &Pos) override;
+	bool inMenu(const Common::Point &Pos) const override;
 private:
 	void redrawAll() override;
 };
diff --git a/engines/zvision/sound/midi.h b/engines/zvision/sound/midi.h
index 1d4435723be..9cf7ceb0054 100644
--- a/engines/zvision/sound/midi.h
+++ b/engines/zvision/sound/midi.h
@@ -40,9 +40,9 @@ public:
 	void setProgram(uint8 channel, uint8 prog);
 
 	int8 getFreeChannel();  // Negative if none available
-	bool isAvailable() {
+	bool isAvailable() const {
 		return _available;
-	};
+	}
 
 protected:
 	bool _available = false;
@@ -51,7 +51,7 @@ protected:
 		bool playing;
 		uint8 note;
 
-		chan() : playing(false), note(0) {};
+		chan() : playing(false), note(0) {}
 	};
 	void send(uint8 status, uint8 data1 = 0x00, uint8 data2 = 0x00);
 	uint8 _startChannel = 0;
diff --git a/engines/zvision/sound/volume_manager.h b/engines/zvision/sound/volume_manager.h
index 6d08042df07..8034a3ae600 100644
--- a/engines/zvision/sound/volume_manager.h
+++ b/engines/zvision/sound/volume_manager.h
@@ -42,12 +42,12 @@ class VolumeManager {
 public:
 	VolumeManager(ZVision *engine, volumeScaling mode);
 	~VolumeManager() {};
-	volumeScaling getMode() {
+	volumeScaling getMode() const {
 		return _mode;
-	};
+	}
 	void setMode(volumeScaling mode) {
 		_mode = mode;
-	};
+	}
 	uint8 convert(uint8 inputValue);
 	uint8 convert(uint8 inputValue, volumeScaling &mode);
 	uint8 convert(uint8 inputValue, Math::Angle azimuth, uint8 directionality = 255);


Commit: d123bba40cfe4c316d5524ccf6a152fcc2bae332
    https://github.com/scummvm/scummvm/commit/d123bba40cfe4c316d5524ccf6a152fcc2bae332
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:02+02:00

Commit Message:
ZVISION: Code formatting compliance.

Changed paths:
    engines/zvision/graphics/render_table.cpp
    engines/zvision/metaengine.cpp


diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index 88aa424b10b..ef149d544cd 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -15,7 +15,7 @@
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http:// www.gnu.org/licenses/>.
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
  */
 
diff --git a/engines/zvision/metaengine.cpp b/engines/zvision/metaengine.cpp
index b4e8eef9700..b75f58535aa 100644
--- a/engines/zvision/metaengine.cpp
+++ b/engines/zvision/metaengine.cpp
@@ -100,7 +100,7 @@ static const ADExtraGuiOptionsMap optionsList[] = {
 		GAMEOPTION_ENABLE_WIDESCREEN,
 		{
 			_s("Enable widescreen support"),
-			_s("Rearrange placement of menus & subtitles so as to make better use of modern wide aspect ratio displays."),
+			_s("Rearrange placement of menus & subtitles so as to make better use of modern wide aspect ratio displays"),
 			"widescreen",
 			true,
 			0,
@@ -112,7 +112,7 @@ static const ADExtraGuiOptionsMap optionsList[] = {
 		GAMEOPTION_HQ_PANORAMA,
 		{
 			_s("Enable high quality panoramas"),
-			_s("Apply bilinear filtering to panoramic backgrounds."),
+			_s("Apply bilinear filtering to panoramic backgrounds"),
 			"highquality",
 			true,
 			0,


Commit: d30bab31461eaede1c38afc293e53079d62af8c0
    https://github.com/scummvm/scummvm/commit/d30bab31461eaede1c38afc293e53079d62af8c0
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:02+02:00

Commit Message:
ZVISION: Make appropriate methods const.

Changed paths:
    engines/zvision/graphics/render_table.h


diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index 35a065dddbf..9980ffba82a 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -91,7 +91,7 @@ private:
 	bool _highQuality = false;
 	const Graphics::PixelFormat _pixelFormat;
 
-	inline void splitColor(uint16 &color, uint32 &r, uint32 &g, uint32 &b) {
+	inline void splitColor(uint16 &color, uint32 &r, uint32 &g, uint32 &b) const {
 		// NB Left & right shifting unnecessary for interpolating & recombining, so not bothering in order to save cycles
 		r = color & 0x001f;
 		g = color & 0x03e0;
@@ -128,7 +128,7 @@ public:
 // void mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 destWidth, const Common::Rect &subRect);
 	void mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf, bool filter = false);
 	template <typename I>
-	Common::String pixelToBinary(const I &pixel, bool splitColors = true) {
+	Common::String pixelToBinary(const I &pixel, bool splitColors = true) const {
 		uint8 bits = sizeof(pixel) << 3;
 		Common::String str("0b");
 		I spaceMask = 0;


Commit: 6a4c7b2631fef567490db02e244f136a1bf7beeb
    https://github.com/scummvm/scummvm/commit/6a4c7b2631fef567490db02e244f136a1bf7beeb
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:02+02:00

Commit Message:
GRAPHICS: Code formatting compliance, convert indents to tabs.

Changed paths:
    graphics/blit/blit.cpp


diff --git a/graphics/blit/blit.cpp b/graphics/blit/blit.cpp
index 1b57aeb80a8..6b73aa4610f 100644
--- a/graphics/blit/blit.cpp
+++ b/graphics/blit/blit.cpp
@@ -29,20 +29,20 @@ namespace Graphics {
 #ifndef ATARI
 // Function to blit a rect
 void copyBlit(byte *dst, const byte *src,
-			   const uint dstPitch, const uint srcPitch,
-			   const uint w, const uint h,
-			   const uint bytesPerPixel) {
+				const uint dstPitch, const uint srcPitch,
+				const uint w, const uint h,
+				const uint bytesPerPixel) {
 	if (dst == src)
 		return;
 
 	if (dstPitch == srcPitch && ((w * bytesPerPixel) == dstPitch)) {
-	  // Buffers have equal line pitch AND total number of bytes per line matches that pitch
-	  // Therefore we may copy a whole subset of h full-width raster lines in one go.
+		// Buffers have equal line pitch AND total number of bytes per line matches that pitch
+		// Therefore we may copy a whole subset of h full-width raster lines in one go.
 		memcpy(dst, src, dstPitch * h);
 	} else {
-	  // Not transferring whole width of either source or destination buffer, therefore must copy line-by-line
+		// Not transferring whole width of either source or destination buffer, therefore must copy line-by-line
 		for (uint i = 0; i < h; ++i) {
-		  // Copy sublength w of one full buffer raster line
+			// Copy sublength w of one full buffer raster line
 			memcpy(dst, src, w * bytesPerPixel);
 			// Iterate both buffer pointers by respective pitch, to horizontally align starting point of next raster line with that of the one just copied
 			dst += dstPitch;
@@ -56,7 +56,7 @@ namespace {
 
 template<typename Color, int Size>
 inline void keyBlitLogic(byte *dst, const byte *src, const uint w, const uint h,
-						 const uint srcDelta, const uint dstDelta, const uint32 key) {
+						const uint srcDelta, const uint dstDelta, const uint32 key) {
 	const uint8 *col = (const uint8 *)&key;
 #ifdef SCUMM_BIG_ENDIAN
 	if (Size == 3)
@@ -87,9 +87,9 @@ inline void keyBlitLogic(byte *dst, const byte *src, const uint w, const uint h,
 
 // Function to blit a rect with a transparent color key
 bool keyBlit(byte *dst, const byte *src,
-			   const uint dstPitch, const uint srcPitch,
-			   const uint w, const uint h,
-			   const uint bytesPerPixel, const uint32 key) {
+				const uint dstPitch, const uint srcPitch,
+				const uint w, const uint h,
+				const uint bytesPerPixel, const uint32 key) {
 	if (dst == src)
 		return true;
 
@@ -116,7 +116,7 @@ namespace {
 
 template<typename Color, int Size>
 inline void maskBlitLogic(byte *dst, const byte *src, const byte *mask, const uint w, const uint h,
-						 const uint srcDelta, const uint dstDelta, const uint maskDelta) {
+						const uint srcDelta, const uint dstDelta, const uint maskDelta) {
 	for (uint y = 0; y < h; ++y) {
 		for (uint x = 0; x < w; ++x) {
 			if (*mask) {
@@ -142,9 +142,9 @@ inline void maskBlitLogic(byte *dst, const byte *src, const byte *mask, const ui
 
 // Function to blit a rect with a transparent color mask
 bool maskBlit(byte *dst, const byte *src, const byte *mask,
-			   const uint dstPitch, const uint srcPitch, const uint maskPitch,
-			   const uint w, const uint h,
-			   const uint bytesPerPixel) {
+				const uint dstPitch, const uint srcPitch, const uint maskPitch,
+				const uint w, const uint h,
+				const uint bytesPerPixel) {
 	if (dst == src)
 		return true;
 
@@ -172,9 +172,9 @@ namespace {
 
 template<typename SrcColor, int SrcSize, typename DstColor, int DstSize, bool backward, bool hasKey, bool hasMask>
 inline void crossBlitLogic(byte *dst, const byte *src, const byte *mask, const uint w, const uint h,
-						   const PixelFormat &srcFmt, const PixelFormat &dstFmt,
-						   const uint srcDelta, const uint dstDelta, const uint maskDelta,
-						   const uint32 key) {
+							const PixelFormat &srcFmt, const PixelFormat &dstFmt,
+							const uint srcDelta, const uint dstDelta, const uint maskDelta,
+							const uint32 key) {
 	uint32 color;
 	byte a, r, g, b;
 	uint8 *col = (uint8 *)&color;
@@ -229,9 +229,9 @@ inline void crossBlitLogic(byte *dst, const byte *src, const byte *mask, const u
 
 template<bool hasKey, bool hasMask>
 inline bool crossBlitHelper(byte *dst, const byte *src, const byte *mask, const uint w, const uint h,
-						   const PixelFormat &srcFmt, const PixelFormat &dstFmt,
-						   const uint srcPitch, const uint dstPitch, const uint maskPitch,
-						   const uint32 key) {
+							const PixelFormat &srcFmt, const PixelFormat &dstFmt,
+							const uint srcPitch, const uint dstPitch, const uint maskPitch,
+							const uint32 key) {
 	// Faster, but larger, to provide optimized handling for each case.
 	const uint srcDelta = (srcPitch - w * srcFmt.bytesPerPixel);
 	const uint dstDelta = (dstPitch - w * dstFmt.bytesPerPixel);
@@ -296,12 +296,12 @@ inline bool crossBlitHelper(byte *dst, const byte *src, const byte *mask, const
 
 // Function to blit a rect from one color format to another
 bool crossBlit(byte *dst, const byte *src,
-			   const uint dstPitch, const uint srcPitch,
-			   const uint w, const uint h,
-			   const Graphics::PixelFormat &dstFmt, const Graphics::PixelFormat &srcFmt) {
+				const uint dstPitch, const uint srcPitch,
+				const uint w, const uint h,
+				const Graphics::PixelFormat &dstFmt, const Graphics::PixelFormat &srcFmt) {
 	// Error out if conversion is impossible
 	if ((srcFmt.bytesPerPixel == 1) || (dstFmt.bytesPerPixel == 1)
-			 || (!srcFmt.bytesPerPixel) || (!dstFmt.bytesPerPixel))
+			|| (!srcFmt.bytesPerPixel) || (!dstFmt.bytesPerPixel))
 		return false;
 
 	// Don't perform unnecessary conversion
@@ -315,12 +315,12 @@ bool crossBlit(byte *dst, const byte *src,
 
 // Function to blit a rect from one color format to another with a transparent color key
 bool crossKeyBlit(byte *dst, const byte *src,
-			   const uint dstPitch, const uint srcPitch,
-			   const uint w, const uint h,
-			   const Graphics::PixelFormat &dstFmt, const Graphics::PixelFormat &srcFmt, const uint32 key) {
+				const uint dstPitch, const uint srcPitch,
+				const uint w, const uint h,
+				const Graphics::PixelFormat &dstFmt, const Graphics::PixelFormat &srcFmt, const uint32 key) {
 	// Error out if conversion is impossible
 	if ((srcFmt.bytesPerPixel == 1) || (dstFmt.bytesPerPixel == 1)
-			 || (!srcFmt.bytesPerPixel) || (!dstFmt.bytesPerPixel))
+			|| (!srcFmt.bytesPerPixel) || (!dstFmt.bytesPerPixel))
 		return false;
 
 	// Don't perform unnecessary conversion
@@ -334,12 +334,12 @@ bool crossKeyBlit(byte *dst, const byte *src,
 
 // Function to blit a rect from one color format to another with a transparent color mask
 bool crossMaskBlit(byte *dst, const byte *src, const byte *mask,
-			   const uint dstPitch, const uint srcPitch, const uint maskPitch,
-			   const uint w, const uint h,
-			   const Graphics::PixelFormat &dstFmt, const Graphics::PixelFormat &srcFmt) {
+				const uint dstPitch, const uint srcPitch, const uint maskPitch,
+				const uint w, const uint h,
+				const Graphics::PixelFormat &dstFmt, const Graphics::PixelFormat &srcFmt) {
 	// Error out if conversion is impossible
 	if ((srcFmt.bytesPerPixel == 1) || (dstFmt.bytesPerPixel == 1)
-			 || (!srcFmt.bytesPerPixel) || (!dstFmt.bytesPerPixel))
+			|| (!srcFmt.bytesPerPixel) || (!dstFmt.bytesPerPixel))
 		return false;
 
 	// Don't perform unnecessary conversion
@@ -355,7 +355,7 @@ namespace {
 
 template<typename DstColor, int DstSize, bool backward, bool hasKey, bool hasMask>
 inline void crossBlitMapLogic(byte *dst, const byte *src, const byte *mask, const uint w, const uint h,
-									 const uint srcDelta, const uint dstDelta, const uint maskDelta, const uint32 *map, const uint32 key) {
+									const uint srcDelta, const uint dstDelta, const uint maskDelta, const uint32 *map, const uint32 key) {
 	for (uint y = 0; y < h; ++y) {
 		for (uint x = 0; x < w; ++x) {
 			const byte color = *src;
@@ -396,9 +396,9 @@ inline void crossBlitMapLogic(byte *dst, const byte *src, const byte *mask, cons
 
 template<bool hasKey, bool hasMask>
 inline bool crossBlitMapHelperLogic(byte *dst, const byte *src, const byte *mask, const uint w, const uint h,
-						   const uint bytesPerPixel, const uint32 *map,
-						   const uint srcPitch, const uint dstPitch, const uint maskPitch,
-						   const uint32 key) {
+							const uint bytesPerPixel, const uint32 *map,
+							const uint srcPitch, const uint dstPitch, const uint maskPitch,
+							const uint32 key) {
 	// Faster, but larger, to provide optimized handling for each case.
 	const uint srcDelta  = (srcPitch  - w);
 	const uint dstDelta  = (dstPitch  - w * bytesPerPixel);
@@ -446,9 +446,9 @@ inline bool crossBlitMapHelperLogic(byte *dst, const byte *src, const byte *mask
 
 // Function to blit a rect from one color format to another using a map
 bool crossBlitMap(byte *dst, const byte *src,
-			   const uint dstPitch, const uint srcPitch,
-			   const uint w, const uint h,
-			   const uint bytesPerPixel, const uint32 *map) {
+				const uint dstPitch, const uint srcPitch,
+				const uint w, const uint h,
+				const uint bytesPerPixel, const uint32 *map) {
 	// Error out if conversion is impossible
 	if (!bytesPerPixel)
 		return false;
@@ -458,9 +458,9 @@ bool crossBlitMap(byte *dst, const byte *src,
 
 // Function to blit a rect from one color format to another using a map with a transparent color key
 bool crossKeyBlitMap(byte *dst, const byte *src,
-			   const uint dstPitch, const uint srcPitch,
-			   const uint w, const uint h,
-			   const uint bytesPerPixel, const uint32 *map, const uint32 key) {
+				const uint dstPitch, const uint srcPitch,
+				const uint w, const uint h,
+				const uint bytesPerPixel, const uint32 *map, const uint32 key) {
 	// Error out if conversion is impossible
 	if (!bytesPerPixel)
 		return false;
@@ -470,9 +470,9 @@ bool crossKeyBlitMap(byte *dst, const byte *src,
 
 // Function to blit a rect from one color format to another using a map with a transparent color mask
 bool crossMaskBlitMap(byte *dst, const byte *src, const byte *mask,
-			   const uint dstPitch, const uint srcPitch, const uint maskPitch,
-			   const uint w, const uint h,
-			   const uint bytesPerPixel, const uint32 *map) {
+				const uint dstPitch, const uint srcPitch, const uint maskPitch,
+				const uint w, const uint h,
+				const uint bytesPerPixel, const uint32 *map) {
 	// Error out if conversion is impossible
 	if (!bytesPerPixel)
 		return false;


Commit: 9873a40562a608bfe9dcc2f9d898a804927f7893
    https://github.com/scummvm/scummvm/commit/9873a40562a608bfe9dcc2f9d898a804927f7893
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:02+02:00

Commit Message:
ZVISION: Code cleanup, reduced unnecessary indentation.

Changed paths:
    engines/zvision/file/save_manager.cpp
    engines/zvision/text/subtitle_manager.cpp


diff --git a/engines/zvision/file/save_manager.cpp b/engines/zvision/file/save_manager.cpp
index 9555cf3afd4..32599b93535 100644
--- a/engines/zvision/file/save_manager.cpp
+++ b/engines/zvision/file/save_manager.cpp
@@ -64,14 +64,12 @@ bool SaveManager::scummVMSaveLoadDialog(bool isSave) {
 
 	if (slot < 0)
 		return false;
-
-	if (isSave) {
-		saveGame(slot, desc, false);
-		return true;
-	} else {
+	if (!isSave) {
 		Common::ErrorCode result = loadGame(slot).getCode();
 		return (result == Common::kNoError);
 	}
+	saveGame(slot, desc, false);
+	return true;
 }
 
 void SaveManager::saveGame(uint slot, const Common::String &saveName, bool useSaveBuffer) {
@@ -131,49 +129,46 @@ Common::Error SaveManager::loadGame(int slot) {
 		// Restart game, used by ZGI death screen only
 		_engine->getScriptManager()->initialize(true);
 		return Common::kNoError;
-	} else {
-		saveFile = getSlotFile(slot);
-		if (!saveFile)
-			return Common::kPathDoesNotExist;
-		// Read the header
-		SaveGameHeader header;
-		if (!readSaveGameHeader(saveFile, header))
-			return Common::kUnknownError;
-		ScriptManager *scriptManager = _engine->getScriptManager();
-		// Update the state table values
-		scriptManager->deserialize(saveFile);
-		delete saveFile;
-		if (_engine->getGameId() == GID_NEMESIS)  {
-			// Zork Nemesis has no in-game option to select panorama quality or animation options
-			// We set them here to ensure loaded games don't override current game configuration
-			scriptManager->setStateValue(StateKey_HighQuality, ConfMan.getBool("highquality"));
-			scriptManager->setStateValue(StateKey_NoTurnAnim, ConfMan.getBool("noanimwhileturning"));
-			if (scriptManager->getCurrentLocation() == "tv2f") {
-				// WORKAROUND for script bug #6793: location tv2f (stairs) has two states:
-				// one at the top of the stairs, and one at the bottom. When the player
-				// goes to the bottom of the stairs, the screen changes, and hotspot
-				// 4652 (exit opposite the stairs) is enabled. However, the variable that
-				// controls the state (2408) is reset when the player goes down the stairs.
-				// Furthermore, the room's initialization script disables the stair exit
-				// control (4652). This leads to an impossible situation, where all the
-				// exit controls are disabled, and the player can't more anywhere. Thus,
-				// when loading a game in that room, we check for that impossible
-				// situation, which only occurs after the player has moved down the stairs,
-				// and fix it here by setting the correct background, and enabling the
-				// stair exit hotspot.
-				if ((scriptManager->getStateFlag(2411) & Puzzle::DISABLED) &&
-				        (scriptManager->getStateFlag(2408) & Puzzle::DISABLED) &&
-				        (scriptManager->getStateFlag(4652) & Puzzle::DISABLED)) {
-					_engine->getRenderManager()->setBackgroundImage("tv2fb21c.tga");
-					scriptManager->unsetStateFlag(4652, Puzzle::DISABLED);
-				}
+	}
+	saveFile = getSlotFile(slot);
+	if (!saveFile)
+		return Common::kPathDoesNotExist;
+	// Read the header
+	SaveGameHeader header;
+	if (!readSaveGameHeader(saveFile, header))
+		return Common::kUnknownError;
+	ScriptManager *scriptManager = _engine->getScriptManager();
+	// Update the state table values
+	scriptManager->deserialize(saveFile);
+	delete saveFile;
+	if (_engine->getGameId() == GID_NEMESIS)  {
+		// Zork Nemesis has no in-game option to select panorama quality or animation options
+		// We set them here to ensure loaded games don't override current game configuration
+		scriptManager->setStateValue(StateKey_HighQuality, ConfMan.getBool("highquality"));
+		scriptManager->setStateValue(StateKey_NoTurnAnim, ConfMan.getBool("noanimwhileturning"));
+		if (scriptManager->getCurrentLocation() == "tv2f") {
+			// WORKAROUND for script bug #6793: location tv2f (stairs) has two states:
+			// one at the top of the stairs, and one at the bottom. When the player
+			// goes to the bottom of the stairs, the screen changes, and hotspot
+			// 4652 (exit opposite the stairs) is enabled. However, the variable that
+			// controls the state (2408) is reset when the player goes down the stairs.
+			// Furthermore, the room's initialization script disables the stair exit
+			// control (4652). This leads to an impossible situation, where all the
+			// exit controls are disabled, and the player can't more anywhere. Thus,
+			// when loading a game in that room, we check for that impossible
+			// situation, which only occurs after the player has moved down the stairs,
+			// and fix it here by setting the correct background, and enabling the
+			// stair exit hotspot.
+			if ((scriptManager->getStateFlag(2411) & Puzzle::DISABLED) &&
+							(scriptManager->getStateFlag(2408) & Puzzle::DISABLED) &&
+							(scriptManager->getStateFlag(4652) & Puzzle::DISABLED)) {
+				_engine->getRenderManager()->setBackgroundImage("tv2fb21c.tga");
+				scriptManager->unsetStateFlag(4652, Puzzle::DISABLED);
 			}
-
 		}
-		g_engine->setTotalPlayTime(header.playTime * 1000);
-		return Common::kNoError;
 	}
-
+	g_engine->setTotalPlayTime(header.playTime * 1000);
+	return Common::kNoError;
 }
 
 bool SaveManager::readSaveGameHeader(Common::InSaveFile *in, SaveGameHeader &header, bool skipThumbnail) {
@@ -209,8 +204,8 @@ bool SaveManager::readSaveGameHeader(Common::InSaveFile *in, SaveGameHeader &hea
 		GUI::MessageDialog dialog(
 			Common::U32String::format(
 				_("This saved game uses version %u, but this engine only "
-				  "supports up to version %d. You will need an updated version "
-				  "of the engine to use this saved game."), tempVersion, SAVE_VERSION
+					"supports up to version %d. You will need an updated version "
+					"of the engine to use this saved game."), tempVersion, SAVE_VERSION
 			),
 		_("OK"));
 		dialog.runModal();
diff --git a/engines/zvision/text/subtitle_manager.cpp b/engines/zvision/text/subtitle_manager.cpp
index eb367f2193f..8a7d25b3be2 100644
--- a/engines/zvision/text/subtitle_manager.cpp
+++ b/engines/zvision/text/subtitle_manager.cpp
@@ -250,63 +250,63 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool vob) :
 	_redraw(false) {
 	Common::File subFile;
 	Common::Point _textOffset = _engine->getSubtitleManager()->getTextOffset();
-	if (_engine->getSearchManager()->openFile(subFile, subname)) {
-		// Parse subtitle parameters from script
-		while (!subFile.eos()) {
-			Common::String str = subFile.readLine();
-			if (str.lastChar() == '~')
-				str.deleteLastChar();
-			if (str.matchString("*Initialization*", true)) {
-				// Not used
-			} else if (str.matchString("*Rectangle*", true)) {
-				int32 x1, y1, x2, y2;
-				sscanf(str.c_str(), "%*[^:]:%d %d %d %d", &x1, &y1, &x2, &y2);
-				_textArea = Common::Rect(x1, y1, x2, y2);
-				debug(1, "Original subtitle script rectangle coordinates: l%d, t%d, r%d, b%d", x1, y1, x2, y2);
-				// Original game subtitle scripts appear to define subtitle rectangles relative to origin of working area.
-				// To allow arbitrary aspect ratios, we need to instead place these relative to origin of text area.
-				// This will allow the managed text area to then be arbitrarily placed on the screen to suit different aspect ratios.
-				_textArea.translate(_textOffset.x, _textOffset.y);  // Convert working area coordinates to text area coordinates
-				debug(1, "Text area coordinates: l%d, t%d, r%d, b%d", _textArea.left, _textArea.top, _textArea.right, _textArea.bottom);
-			} else if (str.matchString("*TextFile*", true)) {
-				char filename[64];
-				sscanf(str.c_str(), "%*[^:]:%s", filename);
-				Common::File txtFile;
-				if (_engine->getSearchManager()->openFile(txtFile, Common::Path(filename))) {
-					while (!txtFile.eos()) {
-						Common::String txtline = readWideLine(txtFile).encode();
-						Line curLine;
-						curLine.start = -1;
-						curLine.stop = -1;
-						curLine.subStr = txtline;
-						_lines.push_back(curLine);
-					}
-					txtFile.close();
+	if (!_engine->getSearchManager()->openFile(subFile, subname)) {
+		warning("Failed to open subtitle %s", subname.toString().c_str());
+		_toDelete = true;
+		return;
+	}
+	// Parse subtitle parameters from script
+	while (!subFile.eos()) {
+		Common::String str = subFile.readLine();
+		if (str.lastChar() == '~')
+			str.deleteLastChar();
+		if (str.matchString("*Initialization*", true)) {
+			// Not used
+		} else if (str.matchString("*Rectangle*", true)) {
+			int32 x1, y1, x2, y2;
+			sscanf(str.c_str(), "%*[^:]:%d %d %d %d", &x1, &y1, &x2, &y2);
+			_textArea = Common::Rect(x1, y1, x2, y2);
+			debug(1, "Original subtitle script rectangle coordinates: l%d, t%d, r%d, b%d", x1, y1, x2, y2);
+			// Original game subtitle scripts appear to define subtitle rectangles relative to origin of working area.
+			// To allow arbitrary aspect ratios, we need to instead place these relative to origin of text area.
+			// This will allow the managed text area to then be arbitrarily placed on the screen to suit different aspect ratios.
+			_textArea.translate(_textOffset.x, _textOffset.y);  // Convert working area coordinates to text area coordinates
+			debug(1, "Text area coordinates: l%d, t%d, r%d, b%d", _textArea.left, _textArea.top, _textArea.right, _textArea.bottom);
+		} else if (str.matchString("*TextFile*", true)) {
+			char filename[64];
+			sscanf(str.c_str(), "%*[^:]:%s", filename);
+			Common::File txtFile;
+			if (_engine->getSearchManager()->openFile(txtFile, Common::Path(filename))) {
+				while (!txtFile.eos()) {
+					Common::String txtline = readWideLine(txtFile).encode();
+					Line curLine;
+					curLine.start = -1;
+					curLine.stop = -1;
+					curLine.subStr = txtline;
+					_lines.push_back(curLine);
 				}
-			} else {
-				int32 st; // Line start time
-				int32 en; // Line end time
-				int32 sb; // Line number
-				if (sscanf(str.c_str(), "%*[^:]:(%d,%d)=%d", &st, &en, &sb) == 3) {
-					if (sb <= (int32)_lines.size()) {
-						if (vob) {
-							// Convert frame number from 15FPS (AVI) to 29.97FPS (VOB) to synchronise with video
-							// st = st * 2997 / 1500;
-							// en = en * 2997 / 1500;
-							st = st * 2900 / 1500;  // TODO: Subtitles only synchronise correctly at 29fps, but vob files should be 29.97fps; check if video codec is rounding this value down!
-							en = en * 2900 / 1500;
-						}
-						_lines[sb].start = st;
-						_lines[sb].stop = en;
+				txtFile.close();
+			}
+		} else {
+			int32 st; // Line start time
+			int32 en; // Line end time
+			int32 sb; // Line number
+			if (sscanf(str.c_str(), "%*[^:]:(%d,%d)=%d", &st, &en, &sb) == 3) {
+				if (sb <= (int32)_lines.size()) {
+					if (vob) {
+						// Convert frame number from 15FPS (AVI) to 29.97FPS (VOB) to synchronise with video
+						// st = st * 2997 / 1500;
+						// en = en * 2997 / 1500;
+						st = st * 2900 / 1500;  // TODO: Subtitles only synchronise correctly at 29fps, but vob files should be 29.97fps; check if video codec is rounding this value down!
+						en = en * 2900 / 1500;
 					}
+					_lines[sb].start = st;
+					_lines[sb].stop = en;
 				}
 			}
 		}
-		subFile.close();
-	} else {
-		// TODO - add error message here
-		_toDelete = true;
 	}
+	subFile.close();
 }
 
 Subtitle::Subtitle(ZVision *engine, const Common::String &str, const Common::Rect &textArea) :


Commit: 39fa339f936d93e4ec2348b9516aefa57d8938d1
    https://github.com/scummvm/scummvm/commit/39fa339f936d93e4ec2348b9516aefa57d8938d1
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:02+02:00

Commit Message:
ZVISION: Code formatting compliance, lower case argument names.

Changed paths:
    engines/zvision/scripting/menu.cpp
    engines/zvision/scripting/menu.h


diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index 87269532215..b9688b346d0 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -71,9 +71,9 @@ void MenuManager::setEnable(uint16 flags) {
 	}
 }
 
-void MenuManager::onMouseUp(const Common::Point &Pos) {
+void MenuManager::onMouseUp(const Common::Point &pos) {
 	if (_menuFocus.front() == kFocusMain) {
-		_mouseOnItem = mouseOverMain(Pos);
+		_mouseOnItem = mouseOverMain(pos);
 		if (_mouseOnItem == _mainClicked)
 			// Activate clicked action from main menu
 			switch (_mouseOnItem) {
@@ -105,9 +105,9 @@ void MenuManager::onMouseUp(const Common::Point &Pos) {
 	_mainClicked = -1;
 }
 
-void MenuManager::onMouseDown(const Common::Point &Pos) {
+void MenuManager::onMouseDown(const Common::Point &pos) {
 	if (_menuFocus.front() == kFocusMain) {
-		_mouseOnItem = mouseOverMain(Pos);
+		_mouseOnItem = mouseOverMain(pos);
 		// Show clicked graphic
 		if ((_mouseOnItem >= 0) && (_mouseOnItem < 4))
 			if (_enableFlags.get(_mouseOnItem)) {
@@ -115,12 +115,12 @@ void MenuManager::onMouseDown(const Common::Point &Pos) {
 				_redraw = true;
 			}
 	}
-	debug(1, "mouse position %d %d", Pos.x, Pos.y);
-	debug(1, "panorama position %d %d", Pos.x, Pos.y);
+	debug(1, "mouse position %d %d", pos.x, pos.y);
+	debug(1, "panorama position %d %d", pos.x, pos.y);
 }
 
-void MenuManager::onMouseMove(const Common::Point &Pos) {
-	bool nowInMenu = inMenu(Pos);
+void MenuManager::onMouseMove(const Common::Point &pos) {
+	bool nowInMenu = inMenu(pos);
 	if (nowInMenu != _prevInMenu)
 		_redraw = true;
 	_prevInMenu = nowInMenu;
@@ -132,7 +132,7 @@ void MenuManager::onMouseMove(const Common::Point &Pos) {
 		// Inform game scripting engine that mouse is in main menu
 		if (_engine->getScriptManager()->getStateValue(StateKey_MenuState) != 2)
 			_engine->getScriptManager()->setStateValue(StateKey_MenuState, 2);
-		_mouseOnItem = mouseOverMain(Pos);
+		_mouseOnItem = mouseOverMain(pos);
 		break;
 	case kFocusNone:
 		// Inform game scripting engine that mouse is not in any menu
@@ -152,11 +152,11 @@ void MenuManager::onMouseMove(const Common::Point &Pos) {
 		_redraw = true;
 }
 
-int MenuManager::mouseOverMain(const Common::Point &Pos) {
+int MenuManager::mouseOverMain(const Common::Point &pos) {
 	// Common::Rect mainHotspot(28,_hSideMenu);
 	// mainHotspot.moveTo(mainOrigin + _mainScroller._pos);
 	for (int8 i = 0; i < 4; i++) {
-		if (_enableFlags.get(i) && _menuHotspots[i].contains(Pos))
+		if (_enableFlags.get(i) && _menuHotspots[i].contains(pos))
 			return i;
 	}
 	return -1;
@@ -280,12 +280,12 @@ MenuZGI::~MenuZGI() {
 	}
 }
 
-bool MenuZGI::inMenu(const Common::Point &Pos) const {
-	return _menuTriggerArea.contains(Pos) || (_menuFocus.front() != kFocusNone);
+bool MenuZGI::inMenu(const Common::Point &pos) const {
+	return _menuTriggerArea.contains(pos) || (_menuFocus.front() != kFocusNone);
 }
 
-void MenuZGI::onMouseUp(const Common::Point &Pos) {
-	if (inMenu(Pos))
+void MenuZGI::onMouseUp(const Common::Point &pos) {
+	if (inMenu(pos))
 		// _redraw = true;
 		switch (_menuFocus.front()) {
 		case kFocusItems:
@@ -293,7 +293,7 @@ void MenuZGI::onMouseUp(const Common::Point &Pos) {
 				int itemCount = _engine->getScriptManager()->getStateValue(StateKey_Inv_TotalSlots);
 				if (itemCount == 0)
 					itemCount = 20;
-				int i = mouseOverItem(Pos, itemCount);
+				int i = mouseOverItem(pos, itemCount);
 				if (i != -1) {
 					int32 mouseItem = _engine->getScriptManager()->getStateValue(StateKey_InventoryItem);
 					if (mouseItem >= 0  && mouseItem < 0xE0) {
@@ -308,7 +308,7 @@ void MenuZGI::onMouseUp(const Common::Point &Pos) {
 
 		case kFocusMagic:
 			if (_enableFlags.get(kMagicMenu)) {
-				int i = mouseOverMagic(Pos);
+				int i = mouseOverMagic(pos);
 				if (i != -1) {
 
 					uint itemnum = _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + i);
@@ -327,7 +327,7 @@ void MenuZGI::onMouseUp(const Common::Point &Pos) {
 			break;
 
 		case kFocusMain:
-			MenuManager::onMouseUp(Pos);
+			MenuManager::onMouseUp(pos);
 			break;
 
 		default:
@@ -335,8 +335,8 @@ void MenuZGI::onMouseUp(const Common::Point &Pos) {
 		}
 }
 
-void MenuZGI::onMouseMove(const Common::Point &Pos) {
-	if (!inMenu(Pos)) {
+void MenuZGI::onMouseMove(const Common::Point &pos) {
+	if (!inMenu(pos)) {
 		_mainScroller.reset();
 		_magicScroller.reset();
 		_itemsScroller.reset();
@@ -346,19 +346,19 @@ void MenuZGI::onMouseMove(const Common::Point &Pos) {
 	for (uint8 i = 0; i < _menuFocus.size(); i++) {
 		switch (_menuFocus[i]) {
 		case kFocusItems:
-			if (_itemsArea.contains(Pos)) {
+			if (_itemsArea.contains(pos)) {
 				setFocus(kFocusItems);
 				i = _menuFocus.size() + 1;
 			}
 			break;
 		case kFocusMagic:
-			if (_magicArea.contains(Pos)) {
+			if (_magicArea.contains(pos)) {
 				setFocus(kFocusMagic);
 				i = _menuFocus.size() + 1;
 			}
 			break;
 		case kFocusMain:
-			if (_mainArea.contains(Pos)) {
+			if (_mainArea.contains(pos)) {
 				setFocus(kFocusMain);
 				i = _menuFocus.size() + 1;
 			}
@@ -380,7 +380,7 @@ void MenuZGI::onMouseMove(const Common::Point &Pos) {
 				else if (itemCount > 50)
 					itemCount = 50;
 				int lastItem = _mouseOnItem;
-				_mouseOnItem = mouseOverItem(Pos, itemCount);
+				_mouseOnItem = mouseOverItem(pos, itemCount);
 				if (lastItem != _mouseOnItem)
 					if (_engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + _mouseOnItem) || _engine->getScriptManager()->getStateValue(StateKey_Inv_StartSlot + lastItem))
 						_redraw = true;
@@ -390,7 +390,7 @@ void MenuZGI::onMouseMove(const Common::Point &Pos) {
 		case kFocusMagic:
 			if (_enableFlags.get(kMagicMenu)) {
 				int lastItem = _mouseOnItem;
-				_mouseOnItem = mouseOverMagic(Pos);
+				_mouseOnItem = mouseOverMagic(pos);
 
 				if (lastItem != _mouseOnItem)
 					if (_engine->getScriptManager()->getStateValue(StateKey_Spell_1 + _mouseOnItem) || _engine->getScriptManager()->getStateValue(StateKey_Spell_1 + lastItem))
@@ -402,27 +402,27 @@ void MenuZGI::onMouseMove(const Common::Point &Pos) {
 			break;
 		}
 	}
-	MenuManager::onMouseMove(Pos);
+	MenuManager::onMouseMove(pos);
 }
 
-int MenuZGI::mouseOverItem(const Common::Point &Pos, int itemCount) {
+int MenuZGI::mouseOverItem(const Common::Point &pos, int itemCount) {
 	int itemWidth = (_wSideMenu - 28) / itemCount;
 	Common::Rect itemHotspot = Common::Rect(28, _hSideMenu);
 	itemHotspot.moveTo(_itemsOrigin + _itemsScroller._pos);
 	for (int i = 0; i < itemCount; i++) {
-		if (itemHotspot.contains(Pos))
+		if (itemHotspot.contains(pos))
 			return i;
 		itemHotspot.translate(itemWidth, 0);
 	}
 	return -1;
 }
 
-int MenuZGI::mouseOverMagic(const Common::Point &Pos) {
+int MenuZGI::mouseOverMagic(const Common::Point &pos) {
 	Common::Rect magicHotspot(28, _hSideMenu);
 	magicHotspot.moveTo(_magicOrigin + _magicScroller._pos);
 	magicHotspot.translate(28, 0); // Offset from end of menu
 	for (int i = 0; i < 12; i++) {
-		if (magicHotspot.contains(Pos))
+		if (magicHotspot.contains(pos))
 			return i;
 		magicHotspot.translate(_magicWidth, 0);
 	}
@@ -575,18 +575,18 @@ MenuNemesis::~MenuNemesis() {
 
 }
 
-bool MenuNemesis::inMenu(const Common::Point &Pos) const {
-	return _menuTriggerArea.contains(Pos) || (_menuFocus.front() != kFocusNone);
+bool MenuNemesis::inMenu(const Common::Point &pos) const {
+	return _menuTriggerArea.contains(pos) || (_menuFocus.front() != kFocusNone);
 }
 
-void MenuNemesis::onMouseMove(const Common::Point &Pos) {
+void MenuNemesis::onMouseMove(const Common::Point &pos) {
 	// Trigger main menu scrolldown to get mouse over main trigger area
 	// Set focus to topmost layer of menus that mouse is currently over
-	if (_mainArea.contains(Pos) || _menuTriggerArea.contains(Pos))
+	if (_mainArea.contains(pos) || _menuTriggerArea.contains(pos))
 		setFocus(kFocusMain);
 	else
 		setFocus(kFocusNone);
-	MenuManager::onMouseMove(Pos);
+	MenuManager::onMouseMove(pos);
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/menu.h b/engines/zvision/scripting/menu.h
index 689c90dd976..283a14d1390 100644
--- a/engines/zvision/scripting/menu.h
+++ b/engines/zvision/scripting/menu.h
@@ -87,19 +87,19 @@ class MenuManager {
 public:
 	MenuManager(ZVision *engine, const Common::Rect menuArea, const MenuParams params);
 	virtual ~MenuManager();
-	virtual void onMouseMove(const Common::Point &Pos);
-	virtual void onMouseDown(const Common::Point &Pos);
-	virtual void onMouseUp(const Common::Point &Pos);
+	virtual void onMouseMove(const Common::Point &pos);
+	virtual void onMouseDown(const Common::Point &pos);
+	virtual void onMouseUp(const Common::Point &pos);
 	virtual void process(uint32 deltaTimeInMillis);
 	bool inMenu() const {
 		return _prevInMenu;
 	}
-	virtual bool inMenu(const Common::Point &Pos) const {
+	virtual bool inMenu(const Common::Point &pos) const {
 		return false;
 	} // For widescreen mod; used to suspend panning, tilting & scripting triggers when the mouse is within the working window but also in the menu.
 
-	void mainMouseDown(const Common::Point &Pos); // Show clicked graphic under selected button
-	bool mainMouseMove(const Common::Point &Pos); // return true if selected button has changed
+	void mainMouseDown(const Common::Point &pos); // Show clicked graphic under selected button
+	bool mainMouseMove(const Common::Point &pos); // return true if selected button has changed
 
 	void setEnable(uint16 flags);
 	uint16 getEnable() const {
@@ -112,7 +112,7 @@ public:
 protected:
 	virtual void redrawAll() {}
 	void redrawMain();
-	int mouseOverMain(const Common::Point &Pos);
+	int mouseOverMain(const Common::Point &pos);
 	void setFocus(int8 currentFocus);
 
 	bool _prevInMenu = false;
@@ -143,10 +143,10 @@ class MenuZGI: public MenuManager {
 public:
 	MenuZGI(ZVision *engine, Common::Rect menuArea);
 	~MenuZGI() override;
-	void onMouseMove(const Common::Point &Pos) override;  // NB Pos is in screen coordinates
-	void onMouseUp(const Common::Point &Pos) override;
+	void onMouseMove(const Common::Point &pos) override;  // NB Pos is in screen coordinates
+	void onMouseUp(const Common::Point &pos) override;
 	void process(uint32 deltaTimeInMillis) override;
-	bool inMenu(const Common::Point &Pos) const override;
+	bool inMenu(const Common::Point &pos) const override;
 private:
 	void redrawAll() override;
 	Graphics::Surface _menuBack[3];
@@ -158,8 +158,8 @@ private:
 //  void redrawMain(bool hasFocus) override;
 	void redrawItems();
 	void redrawMagic();
-	int mouseOverItem(const Common::Point &Pos, int itemCount);
-	int mouseOverMagic(const Common::Point &Pos);
+	int mouseOverItem(const Common::Point &pos, int itemCount);
+	int mouseOverMagic(const Common::Point &pos);
 
 	static const uint16 _hSideMenu = 32;
 	static const uint16 _wSideMenu = 600;
@@ -181,8 +181,8 @@ class MenuNemesis: public MenuManager {
 public:
 	MenuNemesis(ZVision *engine, Common::Rect menuArea);
 	~MenuNemesis() override;
-	void onMouseMove(const Common::Point &Pos) override;
-	bool inMenu(const Common::Point &Pos) const override;
+	void onMouseMove(const Common::Point &pos) override;
+	bool inMenu(const Common::Point &pos) const override;
 private:
 	void redrawAll() override;
 };


Commit: 09cbad54710b7eae4edb3aaac84ddc852288ba2d
    https://github.com/scummvm/scummvm/commit/09cbad54710b7eae4edb3aaac84ddc852288ba2d
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:02+02:00

Commit Message:
ZVISION: Code formatting compliance, lower case member names.

Changed paths:
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h


diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index ef149d544cd..1812ef83e8a 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -85,8 +85,8 @@ const Common::Point RenderTable::convertWarpedCoordToFlatCoord(const Common::Poi
 	uint32 index = point.y * _numColumns + point.x;
 
 	Common::Point newPoint(point);
-	newPoint.x += (_internalBuffer[index]._xDir ? _internalBuffer[index]._Src.right : _internalBuffer[index]._Src.left);
-	newPoint.y += (_internalBuffer[index]._yDir ? _internalBuffer[index]._Src.bottom : _internalBuffer[index]._Src.top);
+	newPoint.x += (_internalBuffer[index]._xDir ? _internalBuffer[index]._src.right : _internalBuffer[index]._src.left);
+	newPoint.y += (_internalBuffer[index]._yDir ? _internalBuffer[index]._src.bottom : _internalBuffer[index]._src.top);
 
 	return newPoint;
 }
@@ -105,8 +105,8 @@ void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 d
               uint32 normalizedX = x - subRect.left;
               uint32 index = sourceOffset + x;
               // RenderTable only stores offsets from the original coordinates
-              sourceYIndex = y + _internalBuffer[index]._Src.top;
-              sourceXIndex = x + _internalBuffer[index]._Src.left;
+              sourceYIndex = y + _internalBuffer[index]._src.top;
+              sourceXIndex = x + _internalBuffer[index]._src.left;
               destBuffer[destOffset + normalizedX] = sourceBuffer[sourceYIndex * _numColumns + sourceXIndex];
           }
           destOffset += destWidth;
@@ -119,8 +119,8 @@ void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 d
               uint32 normalizedX = x - subRect.left;
               uint32 index = sourceOffset + x;
               // RenderTable only stores offsets from the original coordinates
-              sourceYIndex = y + _internalBuffer[index]._Src.top;
-              sourceXIndex = x + _internalBuffer[index]._Src.left;
+              sourceYIndex = y + _internalBuffer[index]._src.top;
+              sourceXIndex = x + _internalBuffer[index]._src.left;
               destBuffer[destOffset + normalizedX] = sourceBuffer[sourceYIndex * _numColumns + sourceXIndex];
           }
           destOffset += destWidth;
@@ -153,10 +153,10 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 			sourceOffset = y * _numColumns;
 			for (int16 x = 0; x < srcBuf->w; ++x) {
 				curP = _internalBuffer[sourceOffset + x];
-				srcIndexYT = y + curP._Src.top;
-				srcIndexYB = y + curP._Src.bottom;
-				srcIndexXL = x + curP._Src.left;
-				srcIndexXR = x + curP._Src.right;
+				srcIndexYT = y + curP._src.top;
+				srcIndexYB = y + curP._src.bottom;
+				srcIndexXL = x + curP._src.left;
+				srcIndexXR = x + curP._src.right;
 				splitColor(sourceBuffer[srcIndexYT * _numColumns + srcIndexXL], rTL, gTL, bTL);
 				splitColor(sourceBuffer[srcIndexYT * _numColumns + srcIndexXR], rTR, gTR, bTR);
 				splitColor(sourceBuffer[srcIndexYB * _numColumns + srcIndexXL], rBL, gBL, bBL);
@@ -176,8 +176,8 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 			for (int16 x = 0; x < srcBuf->w; ++x) {
 				index = sourceOffset + x;
 				// RenderTable only stores offsets from the original coordinates
-				srcIndexXL = x + (_internalBuffer[index]._xDir ? _internalBuffer[index]._Src.right : _internalBuffer[index]._Src.left);
-				srcIndexYT = y + (_internalBuffer[index]._yDir ? _internalBuffer[index]._Src.bottom : _internalBuffer[index]._Src.top);
+				srcIndexXL = x + (_internalBuffer[index]._xDir ? _internalBuffer[index]._src.right : _internalBuffer[index]._src.left);
+				srcIndexYT = y + (_internalBuffer[index]._yDir ? _internalBuffer[index]._src.bottom : _internalBuffer[index]._src.top);
 				destBuffer[destOffset] = sourceBuffer[srcIndexYT * _numColumns + srcIndexXL];
 				destOffset++;
 			}
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index 9980ffba82a..10048dfb052 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -32,39 +32,39 @@ namespace ZVision {
 class FilterPixel {
 public:
 	// Bitfields representing sequential direction of contraction
-	bool _xDir = 0; // 0 left, 1 right
-	bool _yDir = 0; // 0 up, 1 down
-	Common::Rect _Src = Common::Rect(0, 0); // Coordinates of four panorama image pixels around actual working window pixel
+	bool _xDir = false; // false left, true right
+	bool _yDir = false; // false up, true down
+	Common::Rect _src = Common::Rect(0, 0); // Coordinates of four panorama image pixels around actual working window pixel
 
 	float _fX, _fY, _fTL, _fTR, _fBL, _fBR;
 	
 	FilterPixel() {}
 	FilterPixel(float x, float y, bool highQuality = false) {
-		_Src.left = int16(floor(x));
-		_Src.right = int16(ceil(x));
-		_Src.top = int16(floor(y));
-		_Src.bottom = int16(ceil(y));
+		_src.left = int16(floor(x));
+		_src.right = int16(ceil(x));
+		_src.top = int16(floor(y));
+		_src.bottom = int16(ceil(y));
 		if (highQuality) {
-			_fX = x - (float)_Src.left;
-			_fY = y - (float)_Src.top;
+			_fX = x - (float)_src.left;
+			_fY = y - (float)_src.top;
 			_fTL = (1 - _fX) * (1 - _fY);
 			_fTR = _fX * (1 - _fY);
 			_fBL = (1 - _fX) * _fY;
 			_fBR = _fX * _fY;
 		} else {
 			// Nearest neighbour
-			_xDir = (x - _Src.left) > 0.5f;
-			_yDir = (y - _Src.top) > 0.5f;
+			_xDir = (x - _src.left) > 0.5f;
+			_yDir = (y - _src.top) > 0.5f;
 		}
 	}
 	~FilterPixel() {}
 	inline void flipH() {
-		_Src.left = -_Src.left;
-		_Src.right = -_Src.right;
+		_src.left = -_src.left;
+		_src.right = -_src.right;
 	}
 	inline void flipV() {
-		_Src.top = -_Src.top;
-		_Src.bottom = -_Src.bottom;
+		_src.top = -_src.top;
+		_src.bottom = -_src.bottom;
 	}
 };
 


Commit: 85e6e05617cd352d4076190da8facb9931cae93d
    https://github.com/scummvm/scummvm/commit/85e6e05617cd352d4076190da8facb9931cae93d
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:02+02:00

Commit Message:
ZVISION: Code formatting compliance; alphabetical modules file.

Changed paths:
    engines/zvision/module.mk


diff --git a/engines/zvision/module.mk b/engines/zvision/module.mk
index cc7d392e0ee..ebc12af5393 100644
--- a/engines/zvision/module.mk
+++ b/engines/zvision/module.mk
@@ -1,16 +1,16 @@
 MODULE := engines/zvision
 
 MODULE_OBJS := \
-	core/console.o \
+	common/scroller.o \
 	core/clock.o \
+	core/console.o \
 	core/events.o \
-	common/scroller.o \
 	file/lzss_read_stream.o \
 	file/save_manager.o \
 	file/search_manager.o \
 	file/zfs_archive.o \
-	graphics/cursors/cursor_manager.o \
 	graphics/cursors/cursor.o \
+	graphics/cursors/cursor_manager.o \
 	graphics/effects/fog.o \
 	graphics/effects/light.o \
 	graphics/effects/wave.o \
@@ -29,10 +29,6 @@ MODULE_OBJS := \
 	scripting/controls/save_control.o \
 	scripting/controls/slot_control.o \
 	scripting/controls/titler_control.o \
-	scripting/inventory.o \
-	scripting/menu.o \
-	scripting/scr_file_handling.o \
-	scripting/script_manager.o \
 	scripting/effects/animation_effect.o \
 	scripting/effects/distort_effect.o \
 	scripting/effects/music_effect.o \
@@ -40,9 +36,13 @@ MODULE_OBJS := \
 	scripting/effects/syncsound_effect.o \
 	scripting/effects/timer_effect.o \
 	scripting/effects/ttytext_effect.o \
+	scripting/inventory.o \
+	scripting/menu.o \
+	scripting/scr_file_handling.o \
+	scripting/script_manager.o \
 	sound/midi.o \
-	sound/zork_raw.o \
 	sound/volume_manager.o \
+	sound/zork_raw.o \
 	text/string_manager.o \
 	text/subtitle_manager.o \
 	text/text.o \


Commit: 902dfc9cabee70530c2c335877f1384ebcff6666
    https://github.com/scummvm/scummvm/commit/902dfc9cabee70530c2c335877f1384ebcff6666
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:02+02:00

Commit Message:
ZVISION: Add parse error protection to all sscanf operations.
Add separate debug channels & convert debug messages to make use of them.

Changed paths:
    engines/zvision/core/events.cpp
    engines/zvision/detection.cpp
    engines/zvision/detection.h
    engines/zvision/file/zfs_archive.cpp
    engines/zvision/graphics/effects/fog.cpp
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_table.cpp
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/actions.h
    engines/zvision/scripting/control.cpp
    engines/zvision/scripting/controls/fist_control.cpp
    engines/zvision/scripting/controls/hotmov_control.cpp
    engines/zvision/scripting/controls/input_control.cpp
    engines/zvision/scripting/controls/lever_control.cpp
    engines/zvision/scripting/controls/paint_control.cpp
    engines/zvision/scripting/controls/push_toggle_control.cpp
    engines/zvision/scripting/controls/safe_control.cpp
    engines/zvision/scripting/controls/save_control.cpp
    engines/zvision/scripting/controls/slot_control.cpp
    engines/zvision/scripting/controls/titler_control.cpp
    engines/zvision/scripting/effects/music_effect.cpp
    engines/zvision/scripting/menu.cpp
    engines/zvision/scripting/scr_file_handling.cpp
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/sound/midi.cpp
    engines/zvision/sound/volume_manager.cpp
    engines/zvision/text/subtitle_manager.cpp
    engines/zvision/text/truetype_font.cpp
    engines/zvision/video/rlf_decoder.cpp
    engines/zvision/video/video.cpp
    engines/zvision/zvision.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/core/events.cpp b/engines/zvision/core/events.cpp
index b409626f72b..0573e68c6be 100644
--- a/engines/zvision/core/events.cpp
+++ b/engines/zvision/core/events.cpp
@@ -25,6 +25,7 @@
 #include "common/system.h"
 #include "common/rational.h"
 #include "engines/util.h"
+#include "zvision/detection.h"
 #include "zvision/zvision.h"
 #include "zvision/core/console.h"
 #include "zvision/graphics/cursors/cursor_manager.h"
@@ -277,7 +278,7 @@ void ZVision::processEvents() {
 }
 
 void ZVision::onMouseMove(const Common::Point &pos) {
-	debug(6, "ZVision::onMouseMove()");
+	debugC(6, kDebugEvent, "ZVision::onMouseMove()");
 	_menu->onMouseMove(pos);
 	Common::Point imageCoord(_renderManager->screenSpaceToImageSpace(pos));
 	Common::Rect workingArea = _renderManager->getWorkingArea();
@@ -314,7 +315,7 @@ void ZVision::onMouseMove(const Common::Point &pos) {
 	//               ^
 
 	// Clip the horizontal mouse position to the working window
-	debug(6, "Mouse pos.x, %d, clipping with %d+1, %d+1", pos.x, workingArea.left, workingArea.right);
+	debugC(6, kDebugEvent, "Mouse pos.x, %d, clipping with %d+1, %d+1", pos.x, workingArea.left, workingArea.right);
 	Common::Point clippedPos = pos;
 	clippedPos.x = CLIP<int16>(pos.x, workingArea.left + 1, workingArea.right - 1);
 	if (workingArea.contains(clippedPos) && !_menu->inMenu()) {
diff --git a/engines/zvision/detection.cpp b/engines/zvision/detection.cpp
index 89cdf062478..4711cbac547 100644
--- a/engines/zvision/detection.cpp
+++ b/engines/zvision/detection.cpp
@@ -20,12 +20,33 @@
  */
 
 #include "base/plugins.h"
+#include "common/debug-channels.h"
 #include "common/scummsys.h"
 #include "common/str-array.h"
 #include "engines/advancedDetector.h"
 #include "zvision/detection.h"
 #include "zvision/detection_tables.h"
 
+namespace ZVision {
+
+static const DebugChannelDef debugFlagList[] = {
+	{ ZVision::kDebugScript, "Script", "Show debug messages for script file parsing" },
+	{ ZVision::kDebugLoop, "Loop", "Show debug messages for main game logic cycle" },
+	{ ZVision::kDebugPuzzle, "Puzzle", "Show debug messages for puzzle processing" },
+	{ ZVision::kDebugAction, "Action", "Show debug messages for action processing" },
+	{ ZVision::kDebugControl, "Control", "Show debug messages for control processing" },
+	{ ZVision::kDebugEffect, "Effect", "Show debug messages for effect processing" },
+	{ ZVision::kDebugGraphics, "Graphics", "Show debug messages for graphics compositing & rendering" },
+	{ ZVision::kDebugVideo, "Video", "Show debug messages for video decoding & playback" },
+	{ ZVision::kDebugSound, "Sound", "Show debug messages for sound & music" },
+	{ ZVision::kDebugSubtitle, "Subtitle", "Show debug messages for subtitles" },
+	{ ZVision::kDebugFile, "File", "Show debug messages for file search & load operations" },
+	{ ZVision::kDebugMouse, "Mouse", "Print coordinates of mouse clicks"},
+	{ ZVision::kDebugAssign, "Assign", "Print new slotkey values when changed by an assignment action"},
+	{ ZVision::kDebugEvent, "Event", "Show debug messages for event processing"},
+	DEBUG_CHANNEL_END
+};
+
 class ZVisionMetaEngineDetection : public AdvancedMetaEngineDetection<ZVision::ZVisionGameDescription> {
 public:
 	ZVisionMetaEngineDetection() : AdvancedMetaEngineDetection(ZVision::gameDescriptions, ZVision::zVisionGames) {
@@ -44,6 +65,12 @@ public:
 	const char *getOriginalCopyright() const override {
 		return "Z-Vision (C) 1996 Activision";
 	}
+
+	const DebugChannelDef *getDebugChannels() const override {
+		return debugFlagList;
+	}
 };
 
-REGISTER_PLUGIN_STATIC(ZVISION_DETECTION, PLUGIN_TYPE_ENGINE_DETECTION, ZVisionMetaEngineDetection);
+} // End of namespace ZVision
+
+REGISTER_PLUGIN_STATIC(ZVISION_DETECTION, PLUGIN_TYPE_ENGINE_DETECTION, ZVision::ZVisionMetaEngineDetection);
diff --git a/engines/zvision/detection.h b/engines/zvision/detection.h
index 405dbbc0207..fa664b73dce 100644
--- a/engines/zvision/detection.h
+++ b/engines/zvision/detection.h
@@ -26,6 +26,23 @@
 
 namespace ZVision {
 
+enum ZVisionDebugChannels {
+	kDebugScript = 1,
+	kDebugLoop,
+	kDebugPuzzle,
+	kDebugAction,
+	kDebugControl,
+	kDebugEffect,
+	kDebugGraphics,
+	kDebugVideo,
+	kDebugSound,
+	kDebugSubtitle,
+	kDebugFile,
+	kDebugMouse,
+	kDebugAssign,
+	kDebugEvent
+};
+
 enum ZVisionGameId {
 	GID_NONE = 0,
 	GID_NEMESIS = 1,
diff --git a/engines/zvision/file/zfs_archive.cpp b/engines/zvision/file/zfs_archive.cpp
index 0921a881113..25e4dc1337d 100644
--- a/engines/zvision/file/zfs_archive.cpp
+++ b/engines/zvision/file/zfs_archive.cpp
@@ -23,6 +23,7 @@
 #include "common/file.h"
 #include "common/memstream.h"
 #include "common/scummsys.h"
+#include "zvision/detection.h"
 #include "zvision/file/zfs_archive.h"
 
 namespace ZVision {
@@ -38,17 +39,17 @@ ZfsArchive::ZfsArchive(const Common::Path &fileName) : _fileName(fileName) {
 
 	readHeaders(&zfsFile);
 
-	debug(1, "ZfsArchive::ZfsArchive(%s): Located %d files", _fileName.toString(Common::Path::kNativeSeparator).c_str(), _entryHeaders.size());
+	debugC(1, kDebugFile, "ZfsArchive::ZfsArchive(%s): Located %d files", _fileName.toString(Common::Path::kNativeSeparator).c_str(), _entryHeaders.size());
 }
 
 ZfsArchive::ZfsArchive(const Common::Path &fileName, Common::SeekableReadStream *stream) : _fileName(fileName) {
 	readHeaders(stream);
 
-	debug(1, "ZfsArchive::ZfsArchive(%s): Located %d files", _fileName.toString(Common::Path::kNativeSeparator).c_str(), _entryHeaders.size());
+	debugC(1, kDebugFile, "ZfsArchive::ZfsArchive(%s): Located %d files", _fileName.toString(Common::Path::kNativeSeparator).c_str(), _entryHeaders.size());
 }
 
 ZfsArchive::~ZfsArchive() {
-	debug(1, "ZfsArchive Destructor Called");
+	debugC(1, kDebugFile, "ZfsArchive Destructor Called");
 	ZfsEntryHeaderMap::iterator it = _entryHeaders.begin();
 	for (; it != _entryHeaders.end(); ++it) {
 		delete it->_value;
diff --git a/engines/zvision/graphics/effects/fog.cpp b/engines/zvision/graphics/effects/fog.cpp
index 3727621c71f..c2f2eb49626 100644
--- a/engines/zvision/graphics/effects/fog.cpp
+++ b/engines/zvision/graphics/effects/fog.cpp
@@ -109,7 +109,7 @@ const Graphics::Surface *FogFx::draw(const Graphics::Surface &srcSubRect) {
 void FogFx::update() {
 	_pos += _engine->getScriptManager()->getStateValue(StateKey_EF9_Speed);
 	_pos %= _fog.w;
-	debug(2, "Updating fog effect");
+	debugC(2, kDebugEffect, "Updating fog effect");
 	uint8 dr = _engine->getScriptManager()->getStateValue(StateKey_EF9_R);
 	uint8 dg = _engine->getScriptManager()->getStateValue(StateKey_EF9_G);
 	uint8 db = _engine->getScriptManager()->getStateValue(StateKey_EF9_B);
diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index dc159741afe..51fcf1af201 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -27,6 +27,7 @@
 #include "engines/util.h"
 #include "graphics/blit.h"
 #include "image/tga.h"
+#include "zvision/detection.h"
 #include "zvision/zvision.h"
 #include "zvision/file/lzss_read_stream.h"
 #include "zvision/graphics/render_manager.h"
@@ -52,7 +53,7 @@ RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const G
 	  _doubleFPS(doubleFPS),
 	  _widescreen(widescreen),
 	  _frameLimiter(engine->_system, doubleFPS ? 60 : 30) {
-	debug(1, "creating render manager");
+	debugC(1, kDebugGraphics, "creating render manager");
 	// Define graphics modes & screen subarea geometry
 	Graphics::ModeList modes;
 	_textOffset = _layout.workingArea.origin() - _layout.textArea.origin();
@@ -72,7 +73,7 @@ RenderManager::RenderManager(ZVision *engine, const ScreenLayout layout, const G
 	_warpedSceneSurface.create(_workingArea.width(), _workingArea.height(), _pixelFormat);
 	_menuSurface.create(_menuArea.width(), _menuArea.height(), _pixelFormat);
 	_textSurface.create(_textArea.width(), _textArea.height(), _pixelFormat);
-	debug(1, "render manager created");
+	debugC(1, kDebugGraphics, "render manager created");
 	initialize(false);
 }
 
@@ -90,7 +91,7 @@ RenderManager::~RenderManager() {
 }
 
 void RenderManager::initialize(bool hiRes) {
-	debug(1, "Initializing render manager");
+	debugC(1, kDebugGraphics, "Initializing render manager");
 	_hiRes = hiRes;
 
 	_screenArea = _layout.screenArea;
@@ -110,26 +111,26 @@ void RenderManager::initialize(bool hiRes) {
 	// Screen
 #if defined(USE_MPEG2) && defined(USE_A52)
 	if (_hiRes) {
-		debug(1, "Switching to high resolution");
+		debugC(1, kDebugGraphics, "Switching to high resolution");
 		upscaleRect(_screenArea);
 		upscaleRect(_workingArea);
 		upscaleRect(_textArea);
 	} else
-		debug(1, "Switching to standard resolution");
+		debugC(1, kDebugGraphics, "Switching to standard resolution");
 #endif
 	_screen.create(_screenArea.width(), _screenArea.height(), _engine->_screenPixelFormat);
 	_screen.setTransparentColor(-1);
 	_screen.clear();
 
-	debug(1, "_workingAreaCenter = %d,%d", _workingAreaCenter.x, _workingAreaCenter.y);
+	debugC(1, kDebugGraphics, "_workingAreaCenter = %d,%d", _workingAreaCenter.x, _workingAreaCenter.y);
 
 	// Managed screen subsurfaces
 	_workingManagedSurface.create(_screen, _workingArea);
 	_menuManagedSurface.create(_screen, _menuArea);
 	_textManagedSurface.create(_screen, _textArea);
-	debug(2, "screen area: %d,%d,%d,%d", _screenArea.left, _screenArea.top, _screenArea.bottom, _screenArea.right);
-	debug(2, "working area: %d,%d,%d,%d", _workingArea.left, _workingArea.top, _workingArea.bottom, _workingArea.right);
-	debug(2, "text area: %d,%d,%d,%d", _textArea.left, _textArea.top, _textArea.bottom, _textArea.right);
+	debugC(2, kDebugGraphics, "screen area: %d,%d,%d,%d", _screenArea.left, _screenArea.top, _screenArea.bottom, _screenArea.right);
+	debugC(2, kDebugGraphics, "working area: %d,%d,%d,%d", _workingArea.left, _workingArea.top, _workingArea.bottom, _workingArea.right);
+	debugC(2, kDebugGraphics, "text area: %d,%d,%d,%d", _textArea.left, _textArea.top, _textArea.bottom, _textArea.right);
 
 	// Menu & text area dirty rectangles
 	_menuOverlay = _menuArea.findIntersectingRect(_workingArea);
@@ -144,31 +145,31 @@ void RenderManager::initialize(bool hiRes) {
 	else
 		_textLetterbox = _textArea;
 
-	debug(2, "text overlay area: %d,%d,%d,%d", _textOverlay.left, _textOverlay.top, _textOverlay.bottom, _textOverlay.right);
-	debug(2, "menu overlay area: %d,%d,%d,%d", _menuOverlay.left, _menuOverlay.top, _menuOverlay.bottom, _menuOverlay.right);
+	debugC(2, kDebugGraphics, "text overlay area: %d,%d,%d,%d", _textOverlay.left, _textOverlay.top, _textOverlay.bottom, _textOverlay.right);
+	debugC(2, kDebugGraphics, "menu overlay area: %d,%d,%d,%d", _menuOverlay.left, _menuOverlay.top, _menuOverlay.bottom, _menuOverlay.right);
 
-	debug(2, "Clearing backbuffers");
+	debugC(2, kDebugGraphics, "Clearing backbuffers");
 	// Clear backbuffer surfaces
 	clearMenuSurface(true);
 	clearTextSurface(true);
-	debug(2, "Backbuffers cleared");
+	debugC(2, kDebugGraphics, "Backbuffers cleared");
 
 	// Set hardware/window resolution
-	debug(1, "_screen.w = %d, _screen.h = %d", _screen.w, _screen.h);
+	debugC(1, kDebugGraphics, "_screen.w = %d, _screen.h = %d", _screen.w, _screen.h);
 	initGraphics(_screen.w, _screen.h, &_engine->_screenPixelFormat);
 	_frameLimiter.initialize();
-	debug(1, "Render manager initialized");
+	debugC(1, kDebugGraphics, "Render manager initialized");
 }
 
 bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool preStream) {
-	debug(5, "\nrenderSceneToScreen%s%s%s", immediate ? ", immediate" : "", overlayOnly ? ", overlay only" : "", preStream ? ", pre-stream" : "");
+	debugC(5, kDebugGraphics, "\nrenderSceneToScreen%s%s%s", immediate ? ", immediate" : "", overlayOnly ? ", overlay only" : "", preStream ? ", pre-stream" : "");
 	uint32 startTime = _system->getMillis();
 	if (!overlayOnly) {
 		Graphics::Surface *inputSurface = &_backgroundSurface;
 		Common::Rect outWndDirtyRect;
 		// Apply graphical effects to temporary effects buffer and/or directly to current background image, as appropriate
 		if (!_effects.empty()) {
-			debug(6, "Rendering effects");
+			debugC(6, kDebugGraphics, "Rendering effects");
 			bool copied = false;
 			const Common::Rect windowRect(_workingArea.width(), _workingArea.height());
 			for (EffectsList::iterator it = _effects.begin(); it != _effects.end(); it++) {
@@ -189,7 +190,7 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
 						post = (*it)->draw(_effectSurface.getSubArea(rect));
 					Common::Rect empty;
 					blitSurfaceToSurface(*post, empty, _effectSurface, screenSpaceLocation.left, screenSpaceLocation.top);
-					debug(1, "windowRect %d,%d,%d,%d, screenSpaceLocation %d,%d,%d,%d", windowRect.left, windowRect.top, windowRect.bottom, windowRect.right, screenSpaceLocation.left, screenSpaceLocation.top, screenSpaceLocation.bottom, screenSpaceLocation.right);
+					debugC(1, kDebugGraphics, "windowRect %d,%d,%d,%d, screenSpaceLocation %d,%d,%d,%d", windowRect.left, windowRect.top, windowRect.bottom, windowRect.right, screenSpaceLocation.left, screenSpaceLocation.top, screenSpaceLocation.bottom, screenSpaceLocation.right);
 					screenSpaceLocation.clip(windowRect);
 					if (_backgroundSurfaceDirtyRect.isEmpty())
 						_backgroundSurfaceDirtyRect = screenSpaceLocation;
@@ -197,13 +198,13 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
 						_backgroundSurfaceDirtyRect.extend(screenSpaceLocation);
 				}
 			}
-			debug(5, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
+			debugC(5, kDebugGraphics, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
 		}
 		// Apply panorama/tilt warp to background image
 		switch (_renderTable.getRenderState()) {
 		case RenderTable::PANORAMA:
 		case RenderTable::TILT:
-			debug(5, "Rendering panorama");
+			debugC(5, kDebugGraphics, "Rendering panorama");
 			if (!_backgroundSurfaceDirtyRect.isEmpty()) {
 				_renderTable.mutateImage(&_warpedSceneSurface, inputSurface, _engine->getScriptManager()->getStateValue(StateKey_HighQuality));
 				_outputSurface = &_warpedSceneSurface;
@@ -215,39 +216,39 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
 			outWndDirtyRect = _backgroundSurfaceDirtyRect;
 			break;
 		}
-		debug(5, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
-		debug(5, "Rendering working area");
+		debugC(5, kDebugGraphics, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
+		debugC(5, kDebugGraphics, "Rendering working area");
 		_workingManagedSurface.simpleBlitFrom(*_outputSurface); // TODO - use member functions of managed surface to eliminate manual juggling of dirty rectangles, above.
-		debug(5, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
+		debugC(5, kDebugGraphics, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
 	}
 	if (preStream && !_hiRes) {
-		debug(5, "Pre-rendering text area for video stream");
+		debugC(5, kDebugGraphics, "Pre-rendering text area for video stream");
 		_workingManagedSurface.simpleBlitFrom(*_outputSurface, _textOverlay, _textOverlay.origin()); // Prevents subtitle visual corruption when streaming videos that don't fully overlap them, e.g. Nemesis sarcophagi
 		return false;
 	} else {
-		debug(5, "Rendering menu");
+		debugC(5, kDebugGraphics, "Rendering menu");
 		_menuManagedSurface.transBlitFrom(_menuSurface, -1);
-		debug(5, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
-		debug(5, "Rendering text");
+		debugC(5, kDebugGraphics, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
+		debugC(5, kDebugGraphics, "Rendering text");
 		_textManagedSurface.transBlitFrom(_textSurface, -1);
-		debug(5, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
+		debugC(5, kDebugGraphics, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
 		if (immediate) {
 			_frameLimiter.startFrame();
-			debug(5, "Updating screen, immediate");
+			debugC(5, kDebugGraphics, "Updating screen, immediate");
 			_screen.update();
-			debug(5, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
-			debug(10, "~renderSceneToScreen, immediate");
+			debugC(5, kDebugGraphics, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
+			debugC(10, kDebugGraphics, "~renderSceneToScreen, immediate");
 			return true;
 		} else if (_engine->canRender()) {
 			_frameLimiter.delayBeforeSwap();
 			_frameLimiter.startFrame();
-			debug(5, "Updating screen, frame limited");
+			debugC(5, kDebugGraphics, "Updating screen, frame limited");
 			_screen.update();
-			debug(5, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
-			debug(10, "~renderSceneToScreen, frame limited");
+			debugC(5, kDebugGraphics, "\tCumulative render time this frame: %d ms", _system->getMillis() - startTime);
+			debugC(10, kDebugGraphics, "~renderSceneToScreen, frame limited");
 			return true;
 		} else {
-			debug(2, "Skipping screen update; engine forbids rendering at this time.");
+			debugC(2, kDebugGraphics, "Skipping screen update; engine forbids rendering at this time.");
 			return false;
 		}
 	}
@@ -256,7 +257,7 @@ bool RenderManager::renderSceneToScreen(bool immediate, bool overlayOnly, bool p
 Graphics::ManagedSurface &RenderManager::getVidSurface(Common::Rect dstRect) {
 	dstRect.translate(_workingArea.left, _workingArea.top);  // Convert to screen coordinates
 	_vidManagedSurface.create(_screen, dstRect);
-	debug(1, "Obtaining managed video surface at %d,%d,%d,%d", dstRect.left, dstRect.top, dstRect.right, dstRect.bottom);
+	debugC(1, kDebugGraphics, "Obtaining managed video surface at %d,%d,%d,%d", dstRect.left, dstRect.top, dstRect.right, dstRect.bottom);
 	return _vidManagedSurface;
 }
 
@@ -383,7 +384,7 @@ void RenderManager::readImageToSurface(const Common::Path &fileName, Graphics::S
 }
 
 const Common::Point RenderManager::screenSpaceToImageSpace(const Common::Point &point) {
-	debug(9, "screenSpaceToImageSpace()");
+	debugC(9, kDebugGraphics, "screenSpaceToImageSpace()");
 	if (_workingArea.contains(point)) {
 		// Convert from screen space to working image space, i.e. panoramic background image or static image
 		Common::Point newPoint(point - _workingArea.origin());
@@ -410,10 +411,10 @@ const Common::Point RenderManager::screenSpaceToImageSpace(const Common::Point &
 			newPoint.x += _backgroundWidth;
 		if (newPoint.y < 0)
 			newPoint.y += _backgroundHeight;
-		debug(9, "~screenSpaceToImageSpace()");
+		debugC(9, kDebugGraphics, "~screenSpaceToImageSpace()");
 		return newPoint;
 	} else {
-		debug(9, "~screenSpaceToImageSpace()");
+		debugC(9, kDebugGraphics, "~screenSpaceToImageSpace()");
 		return Common::Point(0, 0);
 	}
 }
@@ -500,7 +501,7 @@ void RenderManager::scaleBuffer(const void *src, void *dst, uint32 srcWidth, uin
 }
 
 void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, Common::Rect srcRect, Graphics::Surface &dst, int _x, int _y) {
-	debug(9, "blitSurfaceToSurface");
+	debugC(9, kDebugGraphics, "blitSurfaceToSurface");
 	Common::Point dstPos = Common::Point(_x, _y);
 	// Default to using whole source surface
 	if (srcRect.isEmpty())
@@ -540,7 +541,7 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, Common::R
 }
 
 void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, Common::Rect srcRect , Graphics::Surface &dst, int _x, int _y, uint32 colorkey) {
-	debug(9, "blitSurfaceToSurface");
+	debugC(9, kDebugGraphics, "blitSurfaceToSurface");
 	if (srcRect.isEmpty())
 		srcRect = Common::Rect(src.w, src.h);
 	srcRect.clip(src.w, src.h);
@@ -667,7 +668,7 @@ void RenderManager::clearTextSurface(bool force, int32 colorkey) {
 }
 
 Graphics::Surface *RenderManager::getBkgRect(Common::Rect &rect) {
-	debug(11, "getBkgRect()");
+	debugC(11, kDebugGraphics, "getBkgRect()");
 	Common::Rect dst = rect;
 	dst.clip(_backgroundWidth, _backgroundHeight);
 
@@ -695,7 +696,7 @@ Graphics::Surface *RenderManager::loadImage(const Common::Path &file, bool trans
 }
 
 void RenderManager::prepareBackground() {
-	debug(5, "prepareBackground()");
+	debugC(5, kDebugGraphics, "prepareBackground()");
 	_backgroundDirtyRect.clip(_backgroundWidth, _backgroundHeight);
 	switch (_renderTable.getRenderState()) {
 	case RenderTable::PANORAMA: {
@@ -768,7 +769,7 @@ void RenderManager::prepareBackground() {
 	// Clear the dirty rect since everything is clean now
 	_backgroundDirtyRect = Common::Rect();
 	_backgroundSurfaceDirtyRect.clip(_workingArea.width(), _workingArea.height());
-	debug(11, "~prepareBackground()");
+	debugC(11, kDebugGraphics, "~prepareBackground()");
 }
 
 Common::Point RenderManager::getBkgSize() {
@@ -789,7 +790,7 @@ void RenderManager::deleteEffect(uint32 ID) {
 }
 
 Common::Rect RenderManager::transformBackgroundSpaceRectToScreenSpace(const Common::Rect &src) {
-	debug(10, "transformBackgroundSpaceRectToScreenSpace");
+	debugC(10, kDebugGraphics, "transformBackgroundSpaceRectToScreenSpace");
 	Common::Rect tmp = src;
 	switch (_renderTable.getRenderState()) {
 	case RenderTable::PANORAMA: {
@@ -1063,7 +1064,7 @@ void RenderManager::checkBorders() {
 void RenderManager::rotateTo(int16 _toPos, int16 _time) {
 	if (_renderTable.getRenderState() != RenderTable::PANORAMA)
 		return;
-	debug(1, "Rotating panorama to %d", _toPos);
+	debugC(1, kDebugGraphics, "Rotating panorama to %d", _toPos);
 	if (_time == 0)
 		_time = 1;
 
diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index 1812ef83e8a..cd2434015ee 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -184,7 +184,7 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 		}
 	}
 	mutationTime = _system->getMillis() - mutationTime;
-	debug(5, "\tPanorama mutation time %dms, %s quality", mutationTime, _highQuality ? "high" : "low");
+	debugC(5, kDebugGraphics, "\tPanorama mutation time %dms, %s quality", mutationTime, _highQuality ? "high" : "low");
 }
 
 void RenderTable::generateRenderTable() {
@@ -205,9 +205,9 @@ void RenderTable::generateRenderTable() {
 }
 
 void RenderTable::generateLookupTable(bool tilt) {
-	debug(1, "Generating %s lookup table.", tilt ? "tilt" : "panorama");
-	debug(5, "_halfWidth %f, _halfHeight %f", _halfWidth, _halfHeight);
-	debug(5, "_halfRows %d, _halfColumns %d", _halfRows, _halfColumns);
+	debugC(1, kDebugGraphics, "Generating %s lookup table.", tilt ? "tilt" : "panorama");
+	debugC(5, kDebugGraphics, "_halfWidth %f, _halfHeight %f", _halfWidth, _halfHeight);
+	debugC(5, kDebugGraphics, "_halfRows %d, _halfColumns %d", _halfRows, _halfColumns);
 	uint32 generationTime = _system->getMillis();
 	float alpha, cosAlpha, polarCoordInCylinderCoords, linearCoordInCylinderCoords, cylinderRadius, xOffset, yOffset;
 	uint32 indexTL, indexBL, indexTR, indexBR;
@@ -278,8 +278,8 @@ void RenderTable::generateLookupTable(bool tilt) {
 		}
 	}
 	generationTime = _system->getMillis() - generationTime;
-	debug(1, "Render table generated, %s quality", _highQuality ? "high" : "low");
-	debug(1, "\tRender table generation time %dms", generationTime);
+	debugC(1, kDebugGraphics, "Render table generated, %s quality", _highQuality ? "high" : "low");
+	debugC(1, kDebugGraphics, "\tRender table generation time %dms", generationTime);
 }
 
 void RenderTable::setPanoramaFoV(float fov) {
diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index 13c726ca321..1461c011c14 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -21,6 +21,7 @@
 
 #include "common/scummsys.h"
 #include "video/video_decoder.h"
+#include "zvision/detection.h"
 #include "zvision/zvision.h"
 #include "zvision/file/save_manager.h"
 #include "zvision/graphics/graphics_effect.h"
@@ -61,7 +62,10 @@ ActionAdd::ActionAdd(ZVision *engine, int32 slotKey, const Common::String &line)
 
 	char buf[64];
 	memset(buf, 0, 64);
-	sscanf(line.c_str(), "%u,%s", &_key, buf);
+	if (sscanf(line.c_str(), "%u,%s", &_key, buf) != 2) {
+		debugC(kDebugScript, "Malformed ActionAdd line: %s", line.c_str());
+		return;
+	}
 	_value = new ValueSlot(_scriptManager, buf);
 }
 
@@ -84,7 +88,10 @@ ActionAssign::ActionAssign(ZVision *engine, int32 slotKey, const Common::String
 
 	char buf[64];
 	memset(buf, 0, 64);
-	sscanf(line.c_str(), "%u, %s", &_key, buf);
+	if (sscanf(line.c_str(), "%u, %s", &_key, buf) != 2) {
+		debugC(kDebugScript, "Malformed ActionAssign line: %s", line.c_str());
+		return;
+	}
 	_value = new ValueSlot(_scriptManager, buf);
 }
 
@@ -93,7 +100,7 @@ ActionAssign::~ActionAssign() {
 }
 
 bool ActionAssign::execute() {
-	debug(2, "[%d] = %d", _key, _value->getValue());
+	debugC(kDebugAssign, "[%d] = %d", _key, _value->getValue());
 	_scriptManager->setStateValue(_key, _value->getValue());
 	return true;
 }
@@ -102,21 +109,20 @@ bool ActionAssign::execute() {
 // ActionAttenuate
 //////////////////////////////////////////////////////////////////////////////
 
-// TODO: the effects of this seem permanent until the music node is deleted; check if they should only be applied on a per-cycle basis!
-
 ActionAttenuate::ActionAttenuate(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
 	_key = 0;
 	_attenuation = 0;
 
-	sscanf(line.c_str(), "%u, %d", &_key, &_attenuation);
-	debug(3, "Created Action: Attenuate, slotKey %d", _slotKey);
-	debug(3, "Attenuate script: %s", line.c_str());
-	debug(3, "Attenuate parameters: key1 %d, attenuation %d", _key, _attenuation);
+	if (sscanf(line.c_str(), "%u, %d", &_key, &_attenuation) != 2)
+		debugC(kDebugScript, "Malformed ActionAttenuate line: %s", line.c_str());
+	debugC(3, kDebugAction, "Created Action: Attenuate, slotKey %d", _slotKey);
+	debugC(3, kDebugAction, "Attenuate script: %s", line.c_str());
+	debugC(3, kDebugAction, "Attenuate parameters: key1 %d, attenuation %d", _key, _attenuation);
 }
 
 bool ActionAttenuate::execute() {
-	debug(3, "Executing Action: Attenuate, slotkey %d", _slotKey);
+	debugC(3, kDebugAction, "Executing Action: Attenuate, slotkey %d", _slotKey);
 	ScriptingEffect *fx = _scriptManager->getSideFX(_key);
 	if (fx && fx->getType() == ScriptingEffect::SCRIPTING_EFFECT_AUDIO) {
 		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
@@ -138,7 +144,8 @@ ActionChangeLocation::ActionChangeLocation(ZVision *engine, int32 slotKey, const
 	_view = 'y';
 	_offset = 0;
 
-	sscanf(line.c_str(), "%c, %c, %c%c, %u", &_world, &_room, &_node, &_view, &_offset);
+	if (sscanf(line.c_str(), "%c, %c, %c%c, %u", &_world, &_room, &_node, &_view, &_offset) != 5)
+		debugC(kDebugScript, "Malformed ActionChangeLocation line: %s", line.c_str());
 }
 
 bool ActionChangeLocation::execute() {
@@ -161,16 +168,17 @@ ActionCrossfade::ActionCrossfade(ZVision *engine, int32 slotKey, const Common::S
 	_twoEndVolume = 0;
 	_timeInMillis = 0;
 
-	sscanf(line.c_str(),
+	if (sscanf(line.c_str(),
 	       "%u %u %d %d %d %d %d",
-	       &_keyOne, &_keyTwo, &_oneStartVolume, &_twoStartVolume, &_oneEndVolume, &_twoEndVolume, &_timeInMillis);
-	debug(3, "Created Action: CrossFade, slotKey %d", _slotKey);
-	debug(3, "Crossfade script: %s", line.c_str());
-	debug(3, "Crossfade parameters: key1 %u, key2 %u, startVol1 %d, startVol2 %d, endVol1 %d, endVol2 %d, time %dms", _keyOne, _keyTwo, _oneStartVolume, _twoStartVolume, _oneEndVolume, _twoEndVolume, _timeInMillis);
+	       &_keyOne, &_keyTwo, &_oneStartVolume, &_twoStartVolume, &_oneEndVolume, &_twoEndVolume, &_timeInMillis) != 7)
+		debugC(kDebugScript, "Malformed ActionCrossFade line: %s", line.c_str());
+	debugC(3, kDebugAction, "Created Action: CrossFade, slotKey %d", _slotKey);
+	debugC(3, kDebugAction, "Crossfade script: %s", line.c_str());
+	debugC(3, kDebugAction, "Crossfade parameters: key1 %u, key2 %u, startVol1 %d, startVol2 %d, endVol1 %d, endVol2 %d, time %dms", _keyOne, _keyTwo, _oneStartVolume, _twoStartVolume, _oneEndVolume, _twoEndVolume, _timeInMillis);
 }
 
 bool ActionCrossfade::execute() {
-	debug(3, "Executing Action: CrossFade, slotkey %d", _slotKey);
+	debugC(3, kDebugAction, "Executing Action: CrossFade, slotkey %d", _slotKey);
 	if (_keyOne) {
 		ScriptingEffect *fx = _scriptManager->getSideFX(_keyOne);
 		if (fx && fx->getType() == ScriptingEffect::SCRIPTING_EFFECT_AUDIO) {
@@ -233,14 +241,15 @@ bool ActionCursor::execute() {
 ActionDelayRender::ActionDelayRender(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
 	_framesToDelay = 0;
-	sscanf(line.c_str(), "%u", &_framesToDelay);
+	if (sscanf(line.c_str(), "%u", &_framesToDelay) != 1)
+		debugC(kDebugScript, "Malformed ActionDelayRender line: %s", line.c_str());
 	// Limit to 10 frames maximum. This fixes the script bug in ZGI scene px10
 	// (outside Frobozz Electric building), where this is set to 100 (bug #6791).
 	_framesToDelay = MIN<uint32>(_framesToDelay, 10);
 }
 
 bool ActionDelayRender::execute() {
-	debug(3, "Executing Action: DelayRender");
+	debugC(3, kDebugAction, "Executing Action: DelayRender");
 	_engine->setRenderDelay(_framesToDelay);
 	return true;
 }
@@ -253,7 +262,8 @@ ActionDisableControl::ActionDisableControl(ZVision *engine, int32 slotKey, const
 	ResultAction(engine, slotKey) {
 	_key = 0;
 
-	sscanf(line.c_str(), "%u", &_key);
+	if (sscanf(line.c_str(), "%u", &_key) != 1)
+		debugC(kDebugScript, "Malformed ActionDisableControl line: %s", line.c_str());
 }
 
 bool ActionDisableControl::execute() {
@@ -270,7 +280,8 @@ ActionDisplayMessage::ActionDisplayMessage(ZVision *engine, int32 slotKey, const
 	_control = 0;
 	_msgid = 0;
 
-	sscanf(line.c_str(), "%hd %hd", &_control, &_msgid);
+	if (sscanf(line.c_str(), "%hd %hd", &_control, &_msgid) != 2)
+		debugC(kDebugScript, "Malformed ActionDisplayMessage line: %s", line.c_str());
 }
 
 bool ActionDisplayMessage::execute() {
@@ -288,11 +299,11 @@ bool ActionDisplayMessage::execute() {
 
 ActionDissolve::ActionDissolve(ZVision *engine) :
 	ResultAction(engine, 0) {
-	debug(3, "Created action: Dissolve");
+	debugC(3, kDebugAction, "Created action: Dissolve");
 }
 
 bool ActionDissolve::execute() {
-	debug(3, "Executing action: Dissolve");
+	debugC(3, kDebugAction, "Executing action: Dissolve");
 	// Cause black screen flick
 	// Not ideal.  Original engine used a softer dissolve effect; simply turning the screen black is jarring, so disabled for now.
 	// _engine->getRenderManager()->bkgFill(0, 0, 0); // TODO - reimplement this?
@@ -312,7 +323,8 @@ ActionDistort::ActionDistort(ZVision *engine, int32 slotKey, const Common::Strin
 	_startLineScale = 1.0;
 	_endLineScale = 1.0;
 
-	sscanf(line.c_str(), "%hd %hd %f %f %f %f", &_distSlot, &_speed, &_startAngle, &_endAngle, &_startLineScale, &_endLineScale);
+	if (sscanf(line.c_str(), "%hd %hd %f %f %f %f", &_distSlot, &_speed, &_startAngle, &_endAngle, &_startLineScale, &_endLineScale) != 6)
+		debugC(kDebugScript, "Malformed ActionDistort line: %s", line.c_str());
 }
 
 ActionDistort::~ActionDistort() {
@@ -320,7 +332,7 @@ ActionDistort::~ActionDistort() {
 }
 
 bool ActionDistort::execute() {
-	debug(3, "Executing Action: Distort");
+	debugC(3, kDebugAction, "Executing Action: Distort");
 	if (_scriptManager->getSideFX(_distSlot))
 		return true;
 
@@ -337,7 +349,8 @@ ActionEnableControl::ActionEnableControl(ZVision *engine, int32 slotKey, const C
 	ResultAction(engine, slotKey) {
 	_key = 0;
 
-	sscanf(line.c_str(), "%u", &_key);
+	if (sscanf(line.c_str(), "%u", &_key) != 1)
+		debugC(kDebugScript, "Malformed ActionEnableControl line: %s", line.c_str());
 }
 
 bool ActionEnableControl::execute() {
@@ -369,8 +382,10 @@ ActionInventory::ActionInventory(ZVision *engine, int32 slotKey, const Common::S
 	_key = 0;
 
 	char buf[25];
-	sscanf(line.c_str(), "%24s %d", buf, &_key);
-
+	if (sscanf(line.c_str(), "%24s %d", buf, &_key) != 2) {
+		debugC(kDebugScript, "Malformed ActionInventory line: %s", line.c_str());
+		return;
+	}
 	if (strcmp(buf, "add") == 0) {
 		_type = 0;
 	} else if (strcmp(buf, "addi") == 0) {
@@ -382,7 +397,6 @@ ActionInventory::ActionInventory(ZVision *engine, int32 slotKey, const Common::S
 	} else if (strcmp(buf, "cycle") == 0) {
 		_type = 4;
 	}
-
 }
 
 bool ActionInventory::execute() {
@@ -420,34 +434,37 @@ ActionKill::ActionKill(ZVision *engine, int32 slotKey, const Common::String &lin
 	_key = 0;
 	_type = 0;
 	char keytype[25];
-	sscanf(line.c_str(), "%24s", keytype);
-	if (keytype[0] == '"') {
-		if (!scumm_stricmp(keytype, "\"ANIM\""))
-			_type = ScriptingEffect::SCRIPTING_EFFECT_ANIM;
-		else if (!scumm_stricmp(keytype, "\"AUDIO\""))
-			_type = ScriptingEffect::SCRIPTING_EFFECT_AUDIO;
-		else if (!scumm_stricmp(keytype, "\"DISTORT\""))
-			_type = ScriptingEffect::SCRIPTING_EFFECT_DISTORT;
-		else if (!scumm_stricmp(keytype, "\"PANTRACK\""))
-			_type = ScriptingEffect::SCRIPTING_EFFECT_PANTRACK;
-		else if (!scumm_stricmp(keytype, "\"REGION\""))
-			_type = ScriptingEffect::SCRIPTING_EFFECT_REGION;
-		else if (!scumm_stricmp(keytype, "\"TIMER\""))
-			_type = ScriptingEffect::SCRIPTING_EFFECT_TIMER;
-		else if (!scumm_stricmp(keytype, "\"TTYTEXT\""))
-			_type = ScriptingEffect::SCRIPTING_EFFECT_TTYTXT;
-		else if (!scumm_stricmp(keytype, "\"ALL\""))
-			_type = ScriptingEffect::SCRIPTING_EFFECT_ALL;
-	} else
-		_key = atoi(keytype);
-	debug(3, "Created Action: Kill, slotKey %d, type %s, target slotKey %d", _slotKey, keytype, _key);
+	if (sscanf(line.c_str(), "%24s", keytype) != 1) 
+		debugC(kDebugScript, "Malformed ActionKill line: %s", line.c_str());
+	else {
+		if (keytype[0] == '"') {
+			if (!scumm_stricmp(keytype, "\"ANIM\""))
+				_type = ScriptingEffect::SCRIPTING_EFFECT_ANIM;
+			else if (!scumm_stricmp(keytype, "\"AUDIO\""))
+				_type = ScriptingEffect::SCRIPTING_EFFECT_AUDIO;
+			else if (!scumm_stricmp(keytype, "\"DISTORT\""))
+				_type = ScriptingEffect::SCRIPTING_EFFECT_DISTORT;
+			else if (!scumm_stricmp(keytype, "\"PANTRACK\""))
+				_type = ScriptingEffect::SCRIPTING_EFFECT_PANTRACK;
+			else if (!scumm_stricmp(keytype, "\"REGION\""))
+				_type = ScriptingEffect::SCRIPTING_EFFECT_REGION;
+			else if (!scumm_stricmp(keytype, "\"TIMER\""))
+				_type = ScriptingEffect::SCRIPTING_EFFECT_TIMER;
+			else if (!scumm_stricmp(keytype, "\"TTYTEXT\""))
+				_type = ScriptingEffect::SCRIPTING_EFFECT_TTYTXT;
+			else if (!scumm_stricmp(keytype, "\"ALL\""))
+				_type = ScriptingEffect::SCRIPTING_EFFECT_ALL;
+		} else
+			_key = atoi(keytype);
+	}
+	debugC(3, kDebugAction, "Created Action: Kill, slotKey %d, type %s, target slotKey %d", _slotKey, keytype, _key);
 }
 
 bool ActionKill::execute() {
 	if (_type)
 		_scriptManager->killSideFxType((ScriptingEffect::ScriptingEffectType)_type);
 	else {
-		debug(2, "Executing Action: Kill, slotKey %d, target slotKey %d", _slotKey, _key);
+		debugC(2, kDebugAction, "Executing Action: Kill, slotKey %d, target slotKey %d", _slotKey, _key);
 		_scriptManager->killSideFx(_key);
 	}
 	return true;
@@ -461,7 +478,8 @@ ActionMenuBarEnable::ActionMenuBarEnable(ZVision *engine, int32 slotKey, const C
 	ResultAction(engine, slotKey) {
 	_menus = 0xFFFF;
 
-	sscanf(line.c_str(), "%hu", &_menus);
+	if (sscanf(line.c_str(), "%hu", &_menus) != 1)
+		debugC(kDebugScript, "Malformed ActionMenuBarEnable line: %s", line.c_str());
 }
 
 bool ActionMenuBarEnable::execute() {
@@ -486,7 +504,10 @@ ActionMusic::ActionMusic(ZVision *engine, int32 slotKey, const Common::String &l
 	// Volume is optional. If it doesn't appear, assume full volume
 	Common::strcpy_s(volumeBuffer, "100");
 
-	sscanf(line.c_str(), "%u %24s %u %14s", &type, fileNameBuffer, &loop, volumeBuffer);
+	if (sscanf(line.c_str(), "%u %24s %u %14s", &type, fileNameBuffer, &loop, volumeBuffer) < 3) {
+		debugC(kDebugScript, "Malformed ActionMusic line: %s", line.c_str());
+		return;
+	}
 
 	// Type 4 actions are MIDI commands, not files. These are only used by
 	// Zork: Nemesis, for the flute and piano puzzles (tj4e and ve6f, as well
@@ -496,7 +517,10 @@ ActionMusic::ActionMusic(ZVision *engine, int32 slotKey, const Common::String &l
 		_midi = true;
 		int note;
 		int prog;
-		sscanf(line.c_str(), "%u %d %d %14s", &type, &prog, &note, volumeBuffer);
+		if (sscanf(line.c_str(), "%u %d %d %14s", &type, &prog, &note, volumeBuffer) != 4) {
+			debugC(kDebugScript, "Malformed ActionMusic MIDI line: %s", line.c_str());
+			break;
+		}
 		_note = note;
 		_prog = prog;
 		_loop = false;
@@ -510,7 +534,7 @@ ActionMusic::ActionMusic(ZVision *engine, int32 slotKey, const Common::String &l
 	if (volumeBuffer[0] != '[' && atoi(volumeBuffer) > 100) {
 		// I thought I saw a case like this in Zork Nemesis, so
 		// let's guard against it.
-		warning("\tActionMusic: Adjusting volume for %s from %s to 100", _fileName.toString().c_str(), volumeBuffer);
+		debugC(kDebugSound, "\tActionMusic: Adjusting volume for %s from %s to 100", _fileName.toString().c_str(), volumeBuffer);
 		Common::strcpy_s(volumeBuffer, "100");
 	}
 	_volume = new ValueSlot(_scriptManager, volumeBuffer);
@@ -526,23 +550,23 @@ ActionMusic::ActionMusic(ZVision *engine, int32 slotKey, const Common::String &l
 	// Certain game scripts can become locked-up if this is not the case.
 	if (_engine->getScriptManager()->getStateValue(_slotKey) == 1)
 		if (!_scriptManager->getSideFX(_slotKey)) {
-			debug(1, "Recreating missing musicnode, slotkey %d", _slotKey);
+			debugC(1, kDebugAction, "Recreating missing musicnode, slotkey %d", _slotKey);
 			execute();
 		}
 
-	debug(2, "Created Action: Music, slotKey %d, type %u, file %24s, note %u, volume %d, %s", _slotKey, type, fileNameBuffer, _note, _volume->getValue(), _loop ? "looping" : "");
-	debug(4, "Music script: %s", line.c_str());
+	debugC(2, kDebugAction, "Created Action: Music, slotKey %d, type %u, file %24s, note %u, volume %d, %s", _slotKey, type, fileNameBuffer, _note, _volume->getValue(), _loop ? "looping" : "");
+	debugC(4, kDebugAction, "Music script: %s", line.c_str());
 }
 
 ActionMusic::~ActionMusic() {
 	if (!_universe)
 		_scriptManager->killSideFx(_slotKey);
 	delete _volume;
-	debug(2, "Destroyed Action: %sMusic, slotkey %d", _universe ? "Universe_" : "", _slotKey);
+	debugC(2, kDebugAction, "Destroyed Action: %sMusic, slotkey %d", _universe ? "Universe_" : "", _slotKey);
 }
 
 bool ActionMusic::execute() {
-	debug(2, "Executing Action: Music, slotKey %d, volume %d", _slotKey, _volume->getValue());
+	debugC(2, kDebugAction, "Executing Action: Music, slotKey %d, volume %d", _slotKey, _volume->getValue());
 	if (_scriptManager->getSideFX(_slotKey)) {
 		_scriptManager->killSideFx(_slotKey);
 		_scriptManager->setStateValue(_slotKey, 2);
@@ -577,29 +601,30 @@ ActionPanTrack::ActionPanTrack(ZVision *engine, int32 slotKey, const Common::Str
 	uint resetMusicNode = 1;  // Original game scripts do not specify this, but require it to be true to work correctly.
 	uint resetMixerOnDelete = 0;  // Original game scripts do not specify this, but require it to be false to work correctly.
 	uint staticScreen = 0;  // Original game scripts do not specify this, but require it to be false to work correctly.
-	sscanf(line.c_str(), "%u %d %u %u %u %u", &_musicSlot, &_pos, &mag, &resetMusicNode, &resetMixerOnDelete, &staticScreen);
+	if (sscanf(line.c_str(), "%u %d %u %u %u %u", &_musicSlot, &_pos, &mag, &resetMusicNode, &resetMixerOnDelete, &staticScreen) < 2)
+		debugC(kDebugScript, "Malformed ActionPanTrack line: %s", line.c_str());
 	_resetMusicNode = resetMusicNode > 0;
 	_resetMixerOnDelete = resetMixerOnDelete > 0;
 	_staticScreen = staticScreen > 0;
 	_mag = mag;
 	if (_resetMusicNode) {
 		if (_scriptManager->getStateValue(_musicSlot) != 2) {
-			debug(3, "Forcing musicSlot %d to 2", _musicSlot);
+			debugC(3, kDebugAction, "Forcing musicSlot %d to 2", _musicSlot);
 			_scriptManager->setStateValue(_musicSlot, 2); // Not all original game pan_track scripts trigger correctly unless this is set!
 		} else
-			debug(3, "musicSlot %d already set to 2", _musicSlot);
+			debugC(3, kDebugAction, "musicSlot %d already set to 2", _musicSlot);
 	} else
-		debug(3, "NOT forcing musicSlot %d to 2", _musicSlot);
-	debug(3, "Created Action: PanTrack, slotkey %d, musicSlot %u, pos %d, mag %d", _slotKey, _musicSlot, _pos, _mag);
+		debugC(3, kDebugAction, "NOT forcing musicSlot %d to 2", _musicSlot);
+	debugC(3, kDebugAction, "Created Action: PanTrack, slotkey %d, musicSlot %u, pos %d, mag %d", _slotKey, _musicSlot, _pos, _mag);
 }
 
 ActionPanTrack::~ActionPanTrack() {
 	_scriptManager->killSideFx(_slotKey);
-	debug(3, "Destroyed Action: PanTrack, slotkey %d", _slotKey);
+	debugC(3, kDebugAction, "Destroyed Action: PanTrack, slotkey %d", _slotKey);
 }
 
 bool ActionPanTrack::execute() {
-	debug(3, "Executing Action: PanTrack, slotkey %d, musicSlot %u, pos %d, mag %d", _slotKey, _musicSlot, _pos, _mag);
+	debugC(3, kDebugAction, "Executing Action: PanTrack, slotkey %d, musicSlot %u, pos %d, mag %d", _slotKey, _musicSlot, _pos, _mag);
 	if (_scriptManager->getSideFX(_slotKey))
 		return true;
 
@@ -641,8 +666,10 @@ ActionPreloadAnimation::ActionPreloadAnimation(ZVision *engine, int32 slotKey, c
 	char fileName[25];
 
 	// The two %*u are usually 0 and dont seem to have a use
-	sscanf(line.c_str(), "%24s %*u %*u %d %d", fileName, &_mask, &_framerate);
-
+	if (sscanf(line.c_str(), "%24s %*u %*u %d %d", fileName, &_mask, &_framerate) != 3) {
+		debugC(kDebugScript, "Malformed ActionPreloadAnimation line: %s", line.c_str());
+		return;
+	}
 	// Mask 0 means "no transparency" in this case. Since we use a common blitting
 	// code for images and animations, we set it to -1 to avoid confusion with
 	// color 0, which is used as a mask in some images
@@ -676,7 +703,8 @@ ActionUnloadAnimation::ActionUnloadAnimation(ZVision *engine, int32 slotKey, con
 	ResultAction(engine, slotKey) {
 	_key = 0;
 
-	sscanf(line.c_str(), "%u", &_key);
+	if (sscanf(line.c_str(), "%u", &_key) != 1)
+		debugC(kDebugScript, "Malformed ActionUnloadAnimation line: %s", line.c_str());
 }
 
 bool ActionUnloadAnimation::execute() {
@@ -707,9 +735,12 @@ ActionPlayAnimation::ActionPlayAnimation(ZVision *engine, int32 slotKey, const C
 	char fileName[25];
 
 	// The two %*u are always 0 and dont seem to have a use
-	sscanf(line.c_str(),
-	       "%24s %u %u %u %u %u %u %d %*u %*u %d %d",
-	       fileName, &_x, &_y, &_x2, &_y2, &_start, &_end, &_loopCount, &_mask, &_framerate);
+	if (sscanf(line.c_str(),
+			"%24s %u %u %u %u %u %u %d %*u %*u %d %d",
+			fileName, &_x, &_y, &_x2, &_y2, &_start, &_end, &_loopCount, &_mask, &_framerate) != 10) {
+		debugC(kDebugScript, "Malformed ActionPlayAnimation line: %s", line.c_str());
+		return;
+	}
 
 	// Mask 0 means "no transparency" in this case. Since we use a common blitting
 	// code for images and animations, we set it to -1 to avoid confusion with
@@ -761,9 +792,10 @@ ActionPlayPreloadAnimation::ActionPlayPreloadAnimation(ZVision *engine, int32 sl
 	_endFrame = 0;
 	_loopCount = 0;
 
-	sscanf(line.c_str(),
-	       "%u %u %u %u %u %u %u %u",
-	       &_controlKey, &_x1, &_y1, &_x2, &_y2, &_startFrame, &_endFrame, &_loopCount);
+	if (sscanf(line.c_str(),
+			"%u %u %u %u %u %u %u %u",
+			&_controlKey, &_x1, &_y1, &_x2, &_y2, &_startFrame, &_endFrame, &_loopCount) != 8)
+		debugC(kDebugScript, "Malformed ActionPlayPreloadAnimation line: %s", line.c_str());
 	       
 	// WORKAROUND for script bug in Zork Nemesis, room tl9e
 	// Original script gives wrong coordinates & frames
@@ -824,7 +856,10 @@ ActionRegion::ActionRegion(ZVision *engine, int32 slotKey, const Common::String
 
 	int32 x1 = 0, x2 = 0, y1 = 0, y2 = 0;
 
-	sscanf(line.c_str(), "%s %d %d %d %d %hu %hu %hu %hu %s", art, &x1, &y1, &x2, &y2, &_delay, &_type, &_unk1, &_unk2, custom);
+	if (sscanf(line.c_str(), "%s %d %d %d %d %hu %hu %hu %hu %s", art, &x1, &y1, &x2, &y2, &_delay, &_type, &_unk1, &_unk2, custom) != 10) {
+		debugC(kDebugScript, "Malformed ActionRegion line: %s", line.c_str());
+		return;
+	}
 	_art = Common::String(art);
 	_custom = Common::String(custom);
 	_rect = Common::Rect(x1, y1, x2 + 1, y2 + 1);
@@ -835,7 +870,7 @@ ActionRegion::~ActionRegion() {
 }
 
 bool ActionRegion::execute() {
-	debug(2, "Executing Action: Region");
+	debugC(2, kDebugAction, "Executing Action: Region");
 	if (_scriptManager->getSideFX(_slotKey))
 		return true;
 
@@ -844,16 +879,27 @@ bool ActionRegion::execute() {
 	case 0: {
 		uint16 centerX, centerY, frames;
 		double amplitude, waveln, speed;
-		sscanf(_custom.c_str(), "%hu,%hu,%hu,%lf,%lf,%lf,", &centerX, &centerY, &frames, &amplitude, &waveln, &speed);
+		if (sscanf(_custom.c_str(), "%hu,%hu,%hu,%lf,%lf,%lf,", &centerX, &centerY, &frames, &amplitude, &waveln, &speed) != 6) {
+			debugC(kDebugScript, "Malformed ActionRegion custom string: %s", _custom.c_str());
+			break;
+		}
 		effect = new WaveFx(_engine, _slotKey, _rect, _unk1, frames, centerX, centerY, amplitude, waveln, speed);
 	}
 	break;
 	case 1: {
 		uint16 aX, aY, aD;
-		if (_engine->getRenderManager()->getRenderTable()->getRenderState() == RenderTable::PANORAMA)
-			sscanf(_art.c_str(), "useart[%hu,%hu,%hu]", &aY, &aX, &aD);
-		else
-			sscanf(_art.c_str(), "useart[%hu,%hu,%hu]", &aX, &aY, &aD);
+		if (_engine->getRenderManager()->getRenderTable()->getRenderState() == RenderTable::PANORAMA) {
+			if (sscanf(_art.c_str(), "useart[%hu,%hu,%hu]", &aY, &aX, &aD) != 3) {
+				debugC(kDebugScript, "Malformed ActionRegion art string: %s", _art.c_str());
+				break;
+			}
+		}
+		else {
+			if (sscanf(_art.c_str(), "useart[%hu,%hu,%hu]", &aX, &aY, &aD) != 3) {
+				debugC(kDebugScript, "Malformed ActionRegion art string: %s", _art.c_str());
+				break;
+			}
+		}
 		int8 minD;
 		int8 maxD;
 		EffectMap *_map = _engine->getRenderManager()->makeEffectMap(Common::Point(aX, aY), aD, _rect, &minD, &maxD);
@@ -864,7 +910,10 @@ bool ActionRegion::execute() {
 		int16 dum1;
 		int32 dum2;
 		char buf[64];
-		sscanf(_custom.c_str(), "%hd,%d,%s", &dum1, &dum2, buf);
+		if (sscanf(_custom.c_str(), "%hd,%d,%s", &dum1, &dum2, buf) != 3) {
+				debugC(kDebugScript, "Malformed ActionRegion custom string: %s", _custom.c_str());
+			break;
+		}
 		Graphics::Surface tempMask;
 		_engine->getRenderManager()->readImageToSurface(Common::Path(_art), tempMask);
 		if (_rect.width() != tempMask.w)
@@ -897,7 +946,10 @@ ActionRandom::ActionRandom(ZVision *engine, int32 slotKey, const Common::String
 	ResultAction(engine, slotKey) {
 	char maxBuffer[64];
 	memset(maxBuffer, 0, 64);
-	sscanf(line.c_str(), "%s", maxBuffer);
+	if (sscanf(line.c_str(), "%s", maxBuffer) != 1) {
+		debugC(kDebugScript, "Malformed ActionRandom line: %s", line.c_str());
+		return;
+	}
 	_max = new ValueSlot(_scriptManager, maxBuffer);
 }
 
@@ -918,7 +970,10 @@ bool ActionRandom::execute() {
 ActionRestoreGame::ActionRestoreGame(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
 	char buf[128];
-	sscanf(line.c_str(), "%s", buf);
+	if (sscanf(line.c_str(), "%s", buf) != 1) {
+		debugC(kDebugScript, "Malformed ActionRestoreGame line: %s", line.c_str());
+		return;
+	}
 	_fileName = Common::String(buf);
 }
 
@@ -936,7 +991,8 @@ ActionRotateTo::ActionRotateTo(ZVision *engine, int32 slotKey, const Common::Str
 	_time = 0;
 	_toPos = 0;
 
-	sscanf(line.c_str(), "%d, %d", &_toPos, &_time);
+	if (sscanf(line.c_str(), "%d, %d", &_toPos, &_time) != 2)
+		debugC(kDebugScript, "Malformed ActionRotateTo line: %s", line.c_str());
 }
 
 bool ActionRotateTo::execute() {
@@ -956,8 +1012,10 @@ ActionSetPartialScreen::ActionSetPartialScreen(ZVision *engine, int32 slotKey, c
 
 	char fileName[25];
 
-	sscanf(line.c_str(), "%u %u %24s %*u %d", &_x, &_y, fileName, &_backgroundColor);
-
+	if (sscanf(line.c_str(), "%u %u %24s %*u %d", &_x, &_y, fileName, &_backgroundColor) != 4) {
+		debugC(kDebugScript, "Malformed ActionSetPartialScreen line: %s", line.c_str());
+		return;
+	}
 	_fileName = Common::String(fileName);
 
 	if (_backgroundColor > 65535) {
@@ -992,8 +1050,10 @@ bool ActionSetPartialScreen::execute() {
 ActionSetScreen::ActionSetScreen(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
 	char fileName[25];
-	sscanf(line.c_str(), "%24s", fileName);
-
+	if (sscanf(line.c_str(), "%24s", fileName) != 1) {
+		debugC(kDebugScript, "Malformed ActionSetScreen line: %s", line.c_str());
+		return;
+	}
 	_fileName = Common::String(fileName);
 }
 
@@ -1010,11 +1070,12 @@ bool ActionSetScreen::execute() {
 ActionStop::ActionStop(ZVision *engine, int32 slotKey, const Common::String &line) :
 	ResultAction(engine, slotKey) {
 	_key = 0;
-	sscanf(line.c_str(), "%u", &_key);
+	if (sscanf(line.c_str(), "%u", &_key) != 1)
+		debugC(kDebugScript, "Malformed ActionStop line: %s", line.c_str());
 }
 
 bool ActionStop::execute() {
-	debug(2, "Executing Action: Stop, key %d", _key);
+	debugC(2, kDebugAction, "Executing Action: Stop, key %d", _key);
 	_scriptManager->stopSideFx(_key);
 	return true;
 }
@@ -1033,19 +1094,21 @@ ActionStreamVideo::ActionStreamVideo(ZVision *engine, int32 slotKey, const Commo
 
 	char fileName[25];
 	uint skipline = 0;    // skipline - render video with skip every second line, not skippable.
-
-	sscanf(line.c_str(), "%24s %u %u %u %u %u %u", fileName, &_x1, &_y1, &_x2, &_y2, &_flags, &skipline);
-
-	_fileName = Common::String(fileName);
 	_skippable = true;
+	
+	if (sscanf(line.c_str(), "%24s %u %u %u %u %u %u", fileName, &_x1, &_y1, &_x2, &_y2, &_flags, &skipline) != 7) {
+		debugC(kDebugScript, "Malformed ActionStreamVideo line: %s", line.c_str());
+		return;
+	}
+	_fileName = Common::String(fileName);
 }
 
 bool ActionStreamVideo::execute() {
-	debug(3, "Executing video stream");
+	debugC(3, kDebugAction, "Executing video stream");
 	Video::VideoDecoder *decoder;
 	Common::Rect destRect = Common::Rect(_x1, _y1, _x2 + 1, _y2 + 1);
 	Common::Rect srcRect = Common::Rect(0, 0);
-	debug(3, "Streaming video original scripted destination left=%d, top=%d, right=%d, bottom=%d", destRect.left, destRect.top, destRect.right, destRect.bottom);
+	debugC(3, kDebugAction, "Streaming video original scripted destination left=%d, top=%d, right=%d, bottom=%d", destRect.left, destRect.top, destRect.right, destRect.bottom);
 	Common::String subname = _fileName.baseName();
 	subname.setChar('s', subname.size() - 3);
 	subname.setChar('u', subname.size() - 2);
@@ -1117,7 +1180,7 @@ bool ActionStreamVideo::execute() {
 	_engine->getCursorManager()->showMouse(true);
 	_engine->getSubtitleManager()->destroy(sub);
 	_engine->setRenderDelay(2); // Necessary for avoiding redraw of previous scene between sequential videos (eg totemization sequence in ZGI) & when changing location right after a video (e.g. opening temple door in Nemesis)
-	debug(3, "Completed executing video stream");
+	debugC(3, kDebugAction, "Completed executing video stream");
 
 	return true;
 }
@@ -1133,13 +1196,15 @@ ActionSyncSound::ActionSyncSound(ZVision *engine, int32 slotKey, const Common::S
 	char fileName[25];
 	int notUsed = 0;
 
-	sscanf(line.c_str(), "%d %d %24s", &_syncto, &notUsed, fileName);
-
+	if (sscanf(line.c_str(), "%d %d %24s", &_syncto, &notUsed, fileName) != 3) {
+		debugC(kDebugScript, "Malformed ActionSyncSound line: %s", line.c_str());
+		return;
+	}
 	_fileName = Common::String(fileName);
 }
 
 bool ActionSyncSound::execute() {
-	debug(3, "Executing Action: SyncSound");
+	debugC(3, kDebugAction, "Executing Action: SyncSound");
 	ScriptingEffect *fx = _scriptManager->getSideFX(_syncto);
 	if (!fx)
 		return true;
@@ -1159,7 +1224,10 @@ ActionTimer::ActionTimer(ZVision *engine, int32 slotKey, const Common::String &l
 	ResultAction(engine, slotKey) {
 	char timeBuffer[64];
 	memset(timeBuffer, 0, 64);
-	sscanf(line.c_str(), "%s", timeBuffer);
+	if (sscanf(line.c_str(), "%s", timeBuffer) != 1) {
+		debugC(kDebugScript, "Malformed ActionTimer line: %s", line.c_str());
+		return;
+	}
 	_time = new ValueSlot(_scriptManager, timeBuffer);
 }
 
@@ -1185,7 +1253,10 @@ ActionTtyText::ActionTtyText(ZVision *engine, int32 slotKey, const Common::Strin
 
 	char filename[64];
 	int32 x1 = 0, y1 = 0, x2 = 0, y2 = 0;
-	sscanf(line.c_str(), "%d %d %d %d %63s %u", &x1, &y1, &x2, &y2, filename, &_delay);
+	if (sscanf(line.c_str(), "%d %d %d %d %63s %u", &x1, &y1, &x2, &y2, filename, &_delay) != 6) {
+		debugC(kDebugScript, "Malformed ActionTtyText line: %s", line.c_str());
+		return;
+	}
 	_r = Common::Rect(x1, y1, x2, y2);
 	_filename = Common::String(filename);
 }
diff --git a/engines/zvision/scripting/actions.h b/engines/zvision/scripting/actions.h
index 908ed6918b6..c34e17f778d 100644
--- a/engines/zvision/scripting/actions.h
+++ b/engines/zvision/scripting/actions.h
@@ -64,7 +64,7 @@ public:
 
 private:
 	uint32 _key;
-	ValueSlot *_value;
+	ValueSlot *_value = NULL;
 };
 
 class ActionAssign : public ResultAction {
@@ -75,7 +75,7 @@ public:
 
 private:
 	uint32 _key;
-	ValueSlot *_value;
+	ValueSlot *_value = NULL;
 };
 
 class ActionAttenuate : public ResultAction {
diff --git a/engines/zvision/scripting/control.cpp b/engines/zvision/scripting/control.cpp
index ea73ddd3ff6..4e0f7e2bc85 100644
--- a/engines/zvision/scripting/control.cpp
+++ b/engines/zvision/scripting/control.cpp
@@ -1,3 +1,4 @@
+
 /* ScummVM - Graphic Adventure Engine
  *
  * ScummVM is the legal property of its developers, whose names
@@ -22,6 +23,7 @@
 #include "common/debug.h"
 #include "common/scummsys.h"
 #include "common/stream.h"
+#include "zvision/detection.h"
 #include "zvision/zvision.h"
 #include "zvision/graphics/render_manager.h"
 #include "zvision/scripting/control.h"
@@ -30,12 +32,12 @@
 namespace ZVision {
 
 void Control::parseFlatControl(ZVision *engine) {
-	debug(1, "Setting render state to FLAT");
+	debugC(1, kDebugGraphics, "Setting render state to FLAT");
 	engine->getRenderManager()->getRenderTable()->setRenderState(RenderTable::FLAT);
 }
 
 void Control::parsePanoramaControl(ZVision *engine, Common::SeekableReadStream &stream) {
-	debug(1, "Setting render state to PANORAMA");
+	debugC(1, kDebugGraphics, "Setting render state to PANORAMA");
 	RenderTable *renderTable = engine->getRenderManager()->getRenderTable();
 	renderTable->setRenderState(RenderTable::PANORAMA);
 
@@ -46,22 +48,22 @@ void Control::parsePanoramaControl(ZVision *engine, Common::SeekableReadStream &
 	while (!stream.eos() && !line.contains('}')) {
 		if (line.matchString("angle*", true)) {
 			float fov;
-			sscanf(line.c_str(), "angle(%f)", &fov);
-			renderTable->setPanoramaFoV(fov);
+			if (sscanf(line.c_str(), "angle(%f)", &fov) == 1)
+				renderTable->setPanoramaFoV(fov);
 		} else if (line.matchString("linscale*", true)) {
 			float scale;
-			sscanf(line.c_str(), "linscale(%f)", &scale);
-			renderTable->setPanoramaScale(scale);
+			if (sscanf(line.c_str(), "linscale(%f)", &scale) == 1)
+				renderTable->setPanoramaScale(scale);
 		} else if (line.matchString("reversepana*", true)) {
-			uint reverse;
+			uint reverse = 0;
 			sscanf(line.c_str(), "reversepana(%u)", &reverse);
 			if (reverse == 1) {
 				renderTable->setPanoramaReverse(true);
 			}
 		} else if (line.matchString("zeropoint*", true)) {
 			uint point;
-			sscanf(line.c_str(), "zeropoint(%u)", &point);
-			renderTable->setPanoramaZeroPoint(point);
+			if (sscanf(line.c_str(), "zeropoint(%u)", &point) == 1)
+				renderTable->setPanoramaZeroPoint(point);
 		}
 
 		line = stream.readLine();
@@ -73,7 +75,7 @@ void Control::parsePanoramaControl(ZVision *engine, Common::SeekableReadStream &
 
 // Only used in Zork Nemesis, handles tilt controls (ZGI doesn't have a tilt view)
 void Control::parseTiltControl(ZVision *engine, Common::SeekableReadStream &stream) {
-	debug(1, "Setting render state to TILT");
+	debugC(1, kDebugGraphics, "Setting render state to TILT");
 	RenderTable *renderTable = engine->getRenderManager()->getRenderTable();
 	renderTable->setRenderState(RenderTable::TILT);
 
@@ -84,14 +86,14 @@ void Control::parseTiltControl(ZVision *engine, Common::SeekableReadStream &stre
 	while (!stream.eos() && !line.contains('}')) {
 		if (line.matchString("angle*", true)) {
 			float fov;
-			sscanf(line.c_str(), "angle(%f)", &fov);
-			renderTable->setTiltFoV(fov);
+			if (sscanf(line.c_str(), "angle(%f)", &fov) == 1)
+				renderTable->setTiltFoV(fov);
 		} else if (line.matchString("linscale*", true)) {
 			float scale;
-			sscanf(line.c_str(), "linscale(%f)", &scale);
-			renderTable->setTiltScale(scale);
+			if (sscanf(line.c_str(), "linscale(%f)", &scale) == 1)
+				renderTable->setTiltScale(scale);
 		} else if (line.matchString("reversepana*", true)) {
-			uint reverse;
+			uint reverse = 0;
 			sscanf(line.c_str(), "reversepana(%u)", &reverse);
 			if (reverse == 1) {
 				renderTable->setTiltReverse(true);
diff --git a/engines/zvision/scripting/controls/fist_control.cpp b/engines/zvision/scripting/controls/fist_control.cpp
index d99de8641ec..055fb3cc79a 100644
--- a/engines/zvision/scripting/controls/fist_control.cpp
+++ b/engines/zvision/scripting/controls/fist_control.cpp
@@ -179,39 +179,42 @@ void FistControl::readDescFile(const Common::Path &fileName) {
 			_animation = _engine->loadAnimation(Common::Path(values));
 		} else if (param.matchString("anim_rect", true)) {
 			int left, top, right, bottom;
-			sscanf(values.c_str(), "%d %d %d %d", &left, &top, &right, &bottom);
-			_anmRect = Common::Rect(left, top, right, bottom);
+			if (sscanf(values.c_str(), "%d %d %d %d", &left, &top, &right, &bottom) == 4)
+				_anmRect = Common::Rect(left, top, right, bottom);
 		} else if (param.matchString("num_fingers", true)) {
-			sscanf(values.c_str(), "%d", &_fistnum);
-			_fistsUp.resize(_fistnum);
-			_fistsDwn.resize(_fistnum);
+			if (sscanf(values.c_str(), "%d", &_fistnum) == 1) {
+				_fistsUp.resize(_fistnum);
+				_fistsDwn.resize(_fistnum);
+			}
 		} else if (param.matchString("entries", true)) {
-			sscanf(values.c_str(), "%d", &_numEntries);
-			_entries.resize(_numEntries);
+			if (sscanf(values.c_str(), "%d", &_numEntries) == 1)
+				_entries.resize(_numEntries);
 		} else if (param.matchString("eval_order_ascending", true)) {
 			sscanf(values.c_str(), "%d", &_order);
 		} else if (param.matchString("up_hs_num_*", true)) {
 			int fist, num;
 			num = atoi(values.c_str());
 
-			sscanf(param.c_str(), "up_hs_num_%d", &fist);
-			_fistsUp[fist].resize(num);
+			if (sscanf(param.c_str(), "up_hs_num_%d", &fist) == 1)
+				_fistsUp[fist].resize(num);
 		} else if (param.matchString("up_hs_*", true)) {
 			int16 fist, box, x1, y1, x2, y2;
-			sscanf(param.c_str(), "up_hs_%hd_%hd", &fist, &box);
-			sscanf(values.c_str(), "%hd %hd %hd %hd", &x1, &y1, &x2, &y2);
-			(_fistsUp[fist])[box] = Common::Rect(x1, y1, x2, y2);
+			if (sscanf(param.c_str(), "up_hs_%hd_%hd", &fist, &box) == 2) {
+				if (sscanf(values.c_str(), "%hd %hd %hd %hd", &x1, &y1, &x2, &y2) == 4)
+					(_fistsUp[fist])[box] = Common::Rect(x1, y1, x2, y2);
+			}
 		} else if (param.matchString("down_hs_num_*", true)) {
 			int fist, num;
 			num = atoi(values.c_str());
 
-			sscanf(param.c_str(), "down_hs_num_%d", &fist);
-			_fistsDwn[fist].resize(num);
+			if (sscanf(param.c_str(), "down_hs_num_%d", &fist) == 1)
+				_fistsDwn[fist].resize(num);
 		} else if (param.matchString("down_hs_*", true)) {
 			int16 fist, box, x1, y1, x2, y2;
-			sscanf(param.c_str(), "down_hs_%hd_%hd", &fist, &box);
-			sscanf(values.c_str(), "%hd %hd %hd %hd", &x1, &y1, &x2, &y2);
-			(_fistsDwn[fist])[box] = Common::Rect(x1, y1, x2, y2);
+			if (sscanf(param.c_str(), "down_hs_%hd_%hd", &fist, &box) == 2) {
+				if (sscanf(values.c_str(), "%hd %hd %hd %hd", &x1, &y1, &x2, &y2) == 4)
+					(_fistsDwn[fist])[box] = Common::Rect(x1, y1, x2, y2);
+			}
 		} else {
 			int  entry, start, end, sound;
 			char bitsStart[33];
diff --git a/engines/zvision/scripting/controls/hotmov_control.cpp b/engines/zvision/scripting/controls/hotmov_control.cpp
index f14c18dd346..4f6ea40ddb4 100644
--- a/engines/zvision/scripting/controls/hotmov_control.cpp
+++ b/engines/zvision/scripting/controls/hotmov_control.cpp
@@ -59,19 +59,19 @@ HotMovControl::HotMovControl(ZVision *engine, uint32 key, Common::SeekableReadSt
 			int width;
 			int height;
 
-			sscanf(values.c_str(), "%d %d %d %d", &x, &y, &width, &height);
-
-			_rectangle = Common::Rect(x, y, width, height);
+			if (sscanf(values.c_str(), "%d %d %d %d", &x, &y, &width, &height) == 4)
+				_rectangle = Common::Rect(x, y, width, height);
 		} else if (param.matchString("num_frames", true)) {
 			_framesCount = atoi(values.c_str());
 		} else if (param.matchString("num_cycles", true)) {
 			_cyclesCount = atoi(values.c_str());
 		} else if (param.matchString("animation", true)) {
 			char filename[64];
-			sscanf(values.c_str(), "%s", filename);
-			values = Common::String(filename);
-			_animation = _engine->loadAnimation(Common::Path(values));
-			_animation->start();
+			if (sscanf(values.c_str(), "%s", filename) == 1) {
+				values = Common::String(filename);
+				_animation = _engine->loadAnimation(Common::Path(values));
+				_animation->start();
+			}
 		} else if (param.matchString("venus_id", true)) {
 			_venusId = atoi(values.c_str());
 		}
@@ -173,10 +173,10 @@ void HotMovControl::readHsFile(const Common::Path &fileName) {
 		int width;
 		int height;
 
-		sscanf(line.c_str(), "%d:%d %d %d %d~", &frame, &x, &y, &width, &height);
-
-		if (frame >= 0 && frame < _framesCount)
-			_frames[frame] = Common::Rect(x, y, width, height);
+		if (sscanf(line.c_str(), "%d:%d %d %d %d~", &frame, &x, &y, &width, &height) == 5) {
+			if (frame >= 0 && frame < _framesCount)
+				_frames[frame] = Common::Rect(x, y, width, height);
+		}
 	}
 	file.close();
 }
diff --git a/engines/zvision/scripting/controls/input_control.cpp b/engines/zvision/scripting/controls/input_control.cpp
index 09ac08dd752..371d4e6453a 100644
--- a/engines/zvision/scripting/controls/input_control.cpp
+++ b/engines/zvision/scripting/controls/input_control.cpp
@@ -55,35 +55,21 @@ InputControl::InputControl(ZVision *engine, uint32 key, Common::SeekableReadStre
 
 	while (!stream.eos() && !line.contains('}')) {
 		if (param.matchString("rectangle", true)) {
-			int x1;
-			int y1;
-			int x2;
-			int y2;
-
-			sscanf(values.c_str(), "%d %d %d %d", &x1, &y1, &x2, &y2);
-
-			_textRectangle = Common::Rect(x1, y1, x2, y2);
+			int x1, y1, x2, y2;
+			if (sscanf(values.c_str(), "%d %d %d %d", &x1, &y1, &x2, &y2) == 4)
+				_textRectangle = Common::Rect(x1, y1, x2, y2);
 		} else if (param.matchString("aux_hotspot", true)) {
-			int x1;
-			int y1;
-			int x2;
-			int y2;
-
-			sscanf(values.c_str(), "%d %d %d %d", &x1, &y1, &x2, &y2);
-
-			_headerRectangle = Common::Rect(x1, y1, x2, y2);
+			int x1, y1, x2, y2;
+			if (sscanf(values.c_str(), "%d %d %d %d", &x1, &y1, &x2, &y2) == 4)
+				_headerRectangle = Common::Rect(x1, y1, x2, y2);
 		} else if (param.matchString("string_init", true)) {
 			uint fontFormatNumber;
-
-			sscanf(values.c_str(), "%u", &fontFormatNumber);
-
-			_stringInit.readAllStyles(_engine->getStringManager()->getTextLine(fontFormatNumber));
+			if (sscanf(values.c_str(), "%u", &fontFormatNumber) == 1)
+				_stringInit.readAllStyles(_engine->getStringManager()->getTextLine(fontFormatNumber));
 		} else if (param.matchString("chooser_init_string", true)) {
 			uint fontFormatNumber;
-
-			sscanf(values.c_str(), "%u", &fontFormatNumber);
-
-			_stringChooserInit.readAllStyles(_engine->getStringManager()->getTextLine(fontFormatNumber));
+			if (sscanf(values.c_str(), "%u", &fontFormatNumber) == 1)
+				_stringChooserInit.readAllStyles(_engine->getStringManager()->getTextLine(fontFormatNumber));
 		} else if (param.matchString("next_tabstop", true)) {
 			sscanf(values.c_str(), "%u", &_nextTabstop);
 		} else if (param.matchString("cursor_dimensions", true)) {
@@ -92,11 +78,10 @@ InputControl::InputControl(ZVision *engine, uint32 key, Common::SeekableReadStre
 			// Ignore, use the frame count in the animation file
 		} else if (param.matchString("cursor_animation", true)) {
 			char fileName[25];
-
-			sscanf(values.c_str(), "%24s %*u", fileName);
-
-			_animation = _engine->loadAnimation(fileName);
-			_animation->start();
+			if (sscanf(values.c_str(), "%24s %*u", fileName) == 1) {
+				_animation = _engine->loadAnimation(fileName);
+				_animation->start();
+			}
 		} else if (param.matchString("focus", true)) {
 			_focused = true;
 			_engine->getScriptManager()->setFocusControlKey(_key);
diff --git a/engines/zvision/scripting/controls/lever_control.cpp b/engines/zvision/scripting/controls/lever_control.cpp
index bed9ef55830..3ef02c5a65c 100644
--- a/engines/zvision/scripting/controls/lever_control.cpp
+++ b/engines/zvision/scripting/controls/lever_control.cpp
@@ -60,14 +60,12 @@ LeverControl::LeverControl(ZVision *engine, uint32 key, Common::SeekableReadStre
 	while (!stream.eos() && !line.contains('}')) {
 		if (param.matchString("descfile", true)) {
 			char levFileName[25];
-			sscanf(values.c_str(), "%24s", levFileName);
-
-			parseLevFile(levFileName);
+			if (sscanf(values.c_str(), "%24s", levFileName) == 1)
+				parseLevFile(levFileName);
 		} else if (param.matchString("cursor", true)) {
 			char cursorName[25];
-			sscanf(values.c_str(), "%24s", cursorName);
-
-			_cursor = _engine->getCursorManager()->getCursorId(Common::String(cursorName));
+			if (sscanf(values.c_str(), "%24s", cursorName) == 1)
+				_cursor = _engine->getCursorManager()->getCursorId(Common::String(cursorName));
 		}
 
 		line = stream.readLine();
@@ -108,35 +106,33 @@ void LeverControl::parseLevFile(const Common::Path &fileName) {
 			// Not used
 		} else if (param.matchString("anim_coords", true)) {
 			int left, top, right, bottom;
-			sscanf(values.c_str(), "%d %d %d %d", &left, &top, &right, &bottom);
-
-			_animationCoords.left = left;
-			_animationCoords.top = top;
-			_animationCoords.right = right;
-			_animationCoords.bottom = bottom;
+			if (sscanf(values.c_str(), "%d %d %d %d", &left, &top, &right, &bottom) == 4) {
+				_animationCoords.left = left;
+				_animationCoords.top = top;
+				_animationCoords.right = right;
+				_animationCoords.bottom = bottom;
+			}
 		} else if (param.matchString("mirrored", true)) {
 			uint mirrored;
-			sscanf(values.c_str(), "%u", &mirrored);
-
-			_mirrored = mirrored == 0 ? false : true;
+			if (sscanf(values.c_str(), "%u", &mirrored) == 1)
+				_mirrored = mirrored == 0 ? false : true;
 		} else if (param.matchString("frames", true)) {
-			sscanf(values.c_str(), "%u", &_frameCount);
-
-			_frameInfo = new FrameInfo[_frameCount];
+			if (sscanf(values.c_str(), "%u", &_frameCount) == 1)
+				_frameInfo = new FrameInfo[_frameCount];
 		} else if (param.matchString("elsewhere", true)) {
 			// Not used
 		} else if (param.matchString("out_of_control", true)) {
 			// Not used
 		} else if (param.matchString("start_pos", true)) {
-			sscanf(values.c_str(), "%u", &_startFrame);
-			_currentFrame = _startFrame;
+			if (sscanf(values.c_str(), "%u", &_startFrame) == 1)
+				_currentFrame = _startFrame;
 		} else if (param.matchString("hotspot_deltas", true)) {
 			uint x;
 			uint y;
-			sscanf(values.c_str(), "%u %u", &x, &y);
-
-			_hotspotDelta.x = x;
-			_hotspotDelta.y = y;
+			if (sscanf(values.c_str(), "%u %u", &x, &y) == 2) {
+				_hotspotDelta.x = x;
+				_hotspotDelta.y = y;
+			}
 		} else if (param.matchString("venus_id", true)) {
 			_venusId = atoi(values.c_str());
 		} else {
@@ -163,9 +159,8 @@ void LeverControl::parseLevFile(const Common::Path &fileName) {
 
 					uint angle;
 					uint toFrame;
-					sscanf(token.c_str(), "%u,%u", &toFrame, &angle);
-
-					_frameInfo[frameNumber].directions.push_back(Direction(angle, toFrame));
+					if (sscanf(token.c_str(), "%u,%u", &toFrame, &angle) == 2)
+						_frameInfo[frameNumber].directions.push_back(Direction(angle, toFrame));
 				} else if (token.hasPrefix("p")) {
 					// Format: P(<from> to <to>)
 					tokenizer.nextToken();
diff --git a/engines/zvision/scripting/controls/paint_control.cpp b/engines/zvision/scripting/controls/paint_control.cpp
index 55e9f410ef8..5edb9554dda 100644
--- a/engines/zvision/scripting/controls/paint_control.cpp
+++ b/engines/zvision/scripting/controls/paint_control.cpp
@@ -52,9 +52,8 @@ PaintControl::PaintControl(ZVision *engine, uint32 key, Common::SeekableReadStre
 			int width;
 			int height;
 
-			sscanf(values.c_str(), "%d %d %d %d", &x, &y, &width, &height);
-
-			_rectangle = Common::Rect(x, y, width + x, height + y);
+			if (sscanf(values.c_str(), "%d %d %d %d", &x, &y, &width, &height) == 4)
+				_rectangle = Common::Rect(x, y, width + x, height + y);
 		} else if (param.matchString("cursor", true)) {
 			_cursor = _engine->getCursorManager()->getCursorId(values);
 		} else if (param.matchString("brush_file", true)) {
diff --git a/engines/zvision/scripting/controls/push_toggle_control.cpp b/engines/zvision/scripting/controls/push_toggle_control.cpp
index acd1cee89b1..eaa82172d04 100644
--- a/engines/zvision/scripting/controls/push_toggle_control.cpp
+++ b/engines/zvision/scripting/controls/push_toggle_control.cpp
@@ -50,9 +50,8 @@ PushToggleControl::PushToggleControl(ZVision *engine, uint32 key, Common::Seekab
 			uint width;
 			uint height;
 
-			sscanf(values.c_str(), "%u,%u,%u,%u", &x, &y, &width, &height);
-
-			_hotspots.push_back(Common::Rect(x, y, x + width + 1, y + height + 1));
+			if (sscanf(values.c_str(), "%u,%u,%u,%u", &x, &y, &width, &height) == 4)
+				_hotspots.push_back(Common::Rect(x, y, x + width + 1, y + height + 1));
 		} else if (param.matchString("cursor", true)) {
 			_cursor = _engine->getCursorManager()->getCursorId(values);
 		} else if (param.matchString("animation", true)) {
diff --git a/engines/zvision/scripting/controls/safe_control.cpp b/engines/zvision/scripting/controls/safe_control.cpp
index 36ede185d4b..3e13a7787ae 100644
--- a/engines/zvision/scripting/controls/safe_control.cpp
+++ b/engines/zvision/scripting/controls/safe_control.cpp
@@ -64,17 +64,16 @@ SafeControl::SafeControl(ZVision *engine, uint32 key, Common::SeekableReadStream
 			int width;
 			int height;
 
-			sscanf(values.c_str(), "%d %d %d %d", &x, &y, &width, &height);
-
-			_rectangle = Common::Rect(x, y, width, height);
+			if (sscanf(values.c_str(), "%d %d %d %d", &x, &y, &width, &height) == 4)
+				_rectangle = Common::Rect(x, y, width, height);
 		} else if (param.matchString("num_states", true)) {
 			_statesCount = atoi(values.c_str());
 		} else if (param.matchString("center", true)) {
 			int x;
 			int y;
 
-			sscanf(values.c_str(), "%d %d", &x, &y);
-			_center = Common::Point(x, y);
+			if (sscanf(values.c_str(), "%d %d", &x, &y) == 2)
+				_center = Common::Point(x, y);
 		} else if (param.matchString("dial_inner_radius", true)) {
 			_innerRaduis = atoi(values.c_str());
 			_innerRadiusSqr = _innerRaduis * _innerRaduis;
diff --git a/engines/zvision/scripting/controls/save_control.cpp b/engines/zvision/scripting/controls/save_control.cpp
index 5d66933c121..700837ec330 100644
--- a/engines/zvision/scripting/controls/save_control.cpp
+++ b/engines/zvision/scripting/controls/save_control.cpp
@@ -46,13 +46,13 @@ SaveControl::SaveControl(ZVision *engine, uint32 key, Common::SeekableReadStream
 		if (param.matchString("savebox", true)) {
 			int saveId;
 			int inputId;
-
-			sscanf(values.c_str(), "%d %d", &saveId, &inputId);
-			saveElement elmnt;
-			elmnt.inputKey = inputId;
-			elmnt.saveId = saveId;
-			elmnt.exist = false;
-			_inputs.push_back(elmnt);
+			if (sscanf(values.c_str(), "%d %d", &saveId, &inputId) == 2) {
+				saveElement elmnt;
+				elmnt.inputKey = inputId;
+				elmnt.saveId = saveId;
+				elmnt.exist = false;
+				_inputs.push_back(elmnt);
+			}
 		} else if (param.matchString("control_type", true)) {
 			if (values.contains("save"))
 				_saveControl = true;
diff --git a/engines/zvision/scripting/controls/slot_control.cpp b/engines/zvision/scripting/controls/slot_control.cpp
index db1c5d2cce1..7affe167034 100644
--- a/engines/zvision/scripting/controls/slot_control.cpp
+++ b/engines/zvision/scripting/controls/slot_control.cpp
@@ -51,18 +51,16 @@ SlotControl::SlotControl(ZVision *engine, uint32 key, Common::SeekableReadStream
 			int width;
 			int height;
 
-			sscanf(values.c_str(), "%d %d %d %d", &x, &y, &width, &height);
-
-			_hotspot = Common::Rect(x, y, width, height);
+			if (sscanf(values.c_str(), "%d %d %d %d", &x, &y, &width, &height) == 4)
+				_hotspot = Common::Rect(x, y, width, height);
 		} else if (param.matchString("rectangle", true)) {
 			int x;
 			int y;
 			int width;
 			int height;
 
-			sscanf(values.c_str(), "%d %d %d %d", &x, &y, &width, &height);
-
-			_rectangle = Common::Rect(x, y, width, height);
+			if (sscanf(values.c_str(), "%d %d %d %d", &x, &y, &width, &height) == 4)
+				_rectangle = Common::Rect(x, y, width, height);
 		} else if (param.matchString("cursor", true)) {
 			_cursor = _engine->getCursorManager()->getCursorId(values);
 		} else if (param.matchString("distance_id", true)) {
diff --git a/engines/zvision/scripting/controls/titler_control.cpp b/engines/zvision/scripting/controls/titler_control.cpp
index bd20fb91004..9f93ec2040e 100644
--- a/engines/zvision/scripting/controls/titler_control.cpp
+++ b/engines/zvision/scripting/controls/titler_control.cpp
@@ -51,9 +51,8 @@ TitlerControl::TitlerControl(ZVision *engine, uint32 key, Common::SeekableReadSt
 			int x2;
 			int y2;
 
-			sscanf(values.c_str(), "%d %d %d %d", &x, &y, &x2, &y2);
-
-			_rectangle = Common::Rect(x, y, x2, y2);
+			if (sscanf(values.c_str(), "%d %d %d %d", &x, &y, &x2, &y2) == 4)
+				_rectangle = Common::Rect(x, y, x2, y2);
 		}
 
 		line = stream.readLine();
diff --git a/engines/zvision/scripting/effects/music_effect.cpp b/engines/zvision/scripting/effects/music_effect.cpp
index dbd399b66ab..f0276e73eeb 100644
--- a/engines/zvision/scripting/effects/music_effect.cpp
+++ b/engines/zvision/scripting/effects/music_effect.cpp
@@ -97,7 +97,7 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 		}
 
 		if (_key != StateKey_NotSet) {
-			debug(3, "setting musicnode state value to 1");
+			debugC(3, kDebugSound, "setting musicnode state value to 1");
 			_engine->getScriptManager()->setStateValue(_key, 1);
 		}
 
@@ -114,7 +114,7 @@ MusicNode::MusicNode(ZVision *engine, uint32 key, Common::Path &filename, bool l
 		_loaded = true;
 		updateMixer();
 	}
-	debug(3, "MusicNode: %d created", _key);
+	debugC(3, kDebugSound, "MusicNode: %d created", _key);
 }
 
 MusicNode::~MusicNode() {
@@ -124,7 +124,7 @@ MusicNode::~MusicNode() {
 		_engine->getScriptManager()->setStateValue(_key, 2);
 	if (_sub)
 		_engine->getSubtitleManager()->destroy(_sub);
-	debug(3, "MusicNode: %d destroyed", _key);
+	debugC(3, kDebugSound, "MusicNode: %d destroyed", _key);
 }
 
 void MusicNode::outputMixer() {
@@ -145,7 +145,7 @@ bool MusicNode::process(uint32 deltaTimeInMillis) {
 		return stop();
 	else {
 		if (_fade) {
-			debug(3, "Fading music, endVol %d, startVol %d, current %d, fade time %d, elapsed time %dms", _fadeEndVol, _fadeStartVol, _volume, _fadeTime, _fadeElapsed);
+			debugC(3, kDebugSound, "Fading music, endVol %d, startVol %d, current %d, fade time %d, elapsed time %dms", _fadeEndVol, _fadeStartVol, _volume, _fadeTime, _fadeElapsed);
 			uint8 _newvol = 0;
 			_fadeElapsed += deltaTimeInMillis;
 			if ((_fadeTime <= 0) | (_fadeElapsed >= _fadeTime)) {
@@ -166,7 +166,7 @@ bool MusicNode::process(uint32 deltaTimeInMillis) {
 
 void MusicNode::setVolume(uint8 newVolume) {
 	if (_loaded) {
-		debug(4, "Changing volume of music node %d from %d to %d", _key, _volume, newVolume);
+		debugC(4, kDebugSound, "Changing volume of music node %d from %d to %d", _key, _volume, newVolume);
 		_volume = newVolume;
 		updateMixer();
 	}
@@ -183,24 +183,24 @@ PanTrackNode::PanTrackNode(ZVision *engine, uint32 key, uint32 slot, int16 pos,
 	  _pos(pos),
 	  _staticScreen(staticScreen),
 	  _resetMixerOnDelete(resetMixerOnDelete) {
-	debug(3, "Created PanTrackNode, key %d, slot %d", _key, _slot);
+	debugC(3, kDebugSound, "Created PanTrackNode, key %d, slot %d", _key, _slot);
 	process(0);     // Try to set pan value for music node immediately
 }
 
 PanTrackNode::~PanTrackNode() {
-	debug(1, "Deleting PanTrackNode, key %d, slot %d", _key, _slot);
+	debugC(1, kDebugSound, "Deleting PanTrackNode, key %d, slot %d", _key, _slot);
 	ScriptManager *scriptManager = _engine->getScriptManager();
 	ScriptingEffect *fx = scriptManager->getSideFX(_slot);
 	if (fx && fx->getType() == SCRIPTING_EFFECT_AUDIO && _resetMixerOnDelete) {
-		debug(1, "Resetting mixer, slot %d", _slot);
+		debugC(1, kDebugSound, "Resetting mixer, slot %d", _slot);
 		MusicNodeBASE *mus = (MusicNodeBASE *)fx;
 		mus->setBalance(0);
 	} else
-		debug(1, "NOT resetting mixer, slot %d", _slot);
+		debugC(1, kDebugSound, "NOT resetting mixer, slot %d", _slot);
 }
 
 bool PanTrackNode::process(uint32 deltaTimeInMillis) {
-	debug(3, "Processing PanTrackNode, key %d", _key);
+	debugC(3, kDebugSound, "Processing PanTrackNode, key %d", _key);
 	ScriptManager *scriptManager = _engine->getScriptManager();
 	ScriptingEffect *fx = scriptManager->getSideFX(_slot);
 	if (fx && fx->getType() == SCRIPTING_EFFECT_AUDIO) {
@@ -209,7 +209,7 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 			// Original game scripted behaviour
 			switch (_engine->getRenderManager()->getRenderTable()->getRenderState()) {
 			case RenderTable::PANORAMA:
-				debug(3, "PanTrackNode in panorama mode");
+				debugC(3, kDebugSound, "PanTrackNode in panorama mode");
 				_width = _engine->getRenderManager()->getBkgSize().x;
 				if (_width) {
 					_sourcePos.setDegrees(360 * _pos / _width);
@@ -221,7 +221,7 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 			case RenderTable::FLAT:
 			case RenderTable::TILT:
 			default:
-				debug(3, "PanTrackNode in FLAT/TILT mode");
+				debugC(3, kDebugSound, "PanTrackNode in FLAT/TILT mode");
 				_sourcePos.setDegrees(0);
 				_viewPos.setDegrees(0);
 				break;
@@ -232,7 +232,7 @@ bool PanTrackNode::process(uint32 deltaTimeInMillis) {
 		}
 		Math::Angle azimuth;
 		azimuth = _sourcePos - _viewPos;
-		debug(3, "soundPos: %f, _viewPos: %f, azimuth: %f, width %d", _sourcePos.getDegrees(), _viewPos.getDegrees(), azimuth.getDegrees(), _width);
+		debugC(3, kDebugSound, "soundPos: %f, _viewPos: %f, azimuth: %f, width %d", _sourcePos.getDegrees(), _viewPos.getDegrees(), azimuth.getDegrees(), _width);
 		// azimuth is sound source position relative to player, clockwise from centre of camera axis to front when viewed top-down
 		mus->setDirection(azimuth, _mag);
 	}
diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index b9688b346d0..2349506ab01 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -19,6 +19,7 @@
  *
  */
 
+#include "zvision/detection.h"
 #include "zvision/graphics/render_manager.h"
 #include "zvision/scripting/menu.h"
 
@@ -115,8 +116,8 @@ void MenuManager::onMouseDown(const Common::Point &pos) {
 				_redraw = true;
 			}
 	}
-	debug(1, "mouse position %d %d", pos.x, pos.y);
-	debug(1, "panorama position %d %d", pos.x, pos.y);
+	debugC(kDebugMouse, "mouse position %d %d", pos.x, pos.y);
+	debugC(kDebugMouse, "panorama position %d %d", pos.x, pos.y);
 }
 
 void MenuManager::onMouseMove(const Common::Point &pos) {
diff --git a/engines/zvision/scripting/scr_file_handling.cpp b/engines/zvision/scripting/scr_file_handling.cpp
index 21bbeda4689..61d1baf3fe7 100644
--- a/engines/zvision/scripting/scr_file_handling.cpp
+++ b/engines/zvision/scripting/scr_file_handling.cpp
@@ -24,6 +24,7 @@
 #include "common/str.h"
 #include "common/textconsole.h"
 #include "common/tokenizer.h"
+#include "zvision/detection.h"
 #include "zvision/zvision.h"
 #include "zvision/scripting/actions.h"
 #include "zvision/scripting/puzzle.h"
@@ -52,7 +53,10 @@ void ScriptManager::parseScrFile(const Common::Path &fileName, ScriptScope &scop
 				continue;
 			if (line.matchString("puzzle:*", true)) {
 				Puzzle *puzzle = new Puzzle();
-				sscanf(line.c_str(), "puzzle:%u", &(puzzle->key));
+				if (sscanf(line.c_str(), "puzzle:%u", &(puzzle->key)) != 1) {
+					debugC(kDebugScript, "Malformed puzzle string: %s", line.c_str());
+					continue;
+				}
 				if (getStateFlag(puzzle->key) & Puzzle::ONCE_PER_INST)
 					setStateValue(puzzle->key, 0);
 				parsePuzzle(puzzle, file);
@@ -69,23 +73,23 @@ void ScriptManager::parseScrFile(const Common::Path &fileName, ScriptScope &scop
 	Common::File auxFile;
 	Common::String auxFileName = fileName.toString();
 	replace(auxFileName, Common::String(".scr"), Common::String(".aux"));
-	debug(1, "Auxiliary filename %s", auxFileName.c_str());
+	debugC(1, kDebugFile, "Auxiliary filename %s", auxFileName.c_str());
 	Common::Path auxFilePath(auxFileName);
-	debug(1, "Auxiliary path %s", auxFilePath.toString().c_str());
+	debugC(1, kDebugFile, "Auxiliary path %s", auxFilePath.toString().c_str());
 
 	if (!_engine->getSearchManager()->openFile(mainFile, fileName))
 		error("Script file not found: %s", fileName.toString().c_str());
 	else {
-		debug(1, "Parsing primary script file");
+		debugC(1, kDebugScript, "Parsing primary script file %s", fileName.toString().c_str());
 		parse(mainFile);
 		// TODO - add config option to disable/enable auxiliary scripting
 		if (auxFile.exists(auxFilePath)) {
-			debug(1, "Auxiliary script file found");
+			debugC(1, kDebugFile, "Auxiliary script file found");
 			if (auxFile.open(auxFilePath)) {
-				debug(1, "Parsing auxiliary script file %s", auxFilePath.toString().c_str());
+				debugC(1, kDebugScript, "Parsing auxiliary script file %s", auxFilePath.toString().c_str());
 				parse(auxFile);
 			} else
-				debug(1, "Unable to open auxiliary script file %s", auxFilePath.toString().c_str());
+				debugC(1, kDebugFile, "Unable to open auxiliary script file %s", auxFilePath.toString().c_str());
 		}
 	}
 	scope.procCount = 0;
@@ -225,7 +229,10 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 
 		// Parse the id out of the first token
 		token = tokenizer.nextToken();
-		sscanf(token.c_str(), "[%u]", &(entry.key));
+		if (sscanf(token.c_str(), "[%u]", &(entry.key)) != 1) {
+			debugC(kDebugScript, "Malformed criteria ID string %s", token.c_str());
+			return false;
+		}
 
 		// WORKAROUND for a script bug in Zork: Nemesis, room td9e (fist puzzle)
 		// Check for the state of animation 567 (left fist) when manipulating
@@ -257,10 +264,16 @@ bool ScriptManager::parseCriteria(Common::SeekableReadStream &stream, Common::Li
 		// First determine if the last token is an id or a value
 		// Then parse it into 'argument'
 		if (token.contains('[')) {
-			sscanf(token.c_str(), "[%u]", &(entry.argument));
+			if (sscanf(token.c_str(), "[%u]", &(entry.argument)) != 1) {
+				debugC(kDebugScript, "Malformed token string %s", token.c_str());
+				return false;
+			}
 			entry.argumentIsAKey = true;
 		} else {
-			sscanf(token.c_str(), "%u", &(entry.argument));
+			if (sscanf(token.c_str(), "%u", &(entry.argument)) != 1) {
+				debugC(kDebugScript, "Malformed token string %s", token.c_str());
+				return false;
+			}
 			entry.argumentIsAKey = false;
 		}
 
@@ -311,7 +324,7 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 			line.toLowercase();
 			continue;
 		}
-		debug(4, "Result line: %s", line.c_str());
+		debugC(4, kDebugScript, "Result line: %s", line.c_str());
 		const char *chrs = line.c_str();
 		uint pos;
 		if (line.matchString("action:*", true))
@@ -329,7 +342,7 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 				if (chrs[pos] == ':' || chrs[pos] == '(')
 					break;
 
-			debug(4, "startpos %d, pos %d, line.size %d", startpos, pos, line.size());
+			debugC(4, kDebugScript, "startpos %d, pos %d, line.size %d", startpos, pos, line.size());
 			int32 slot = 11;  // Non-setting default slot
 			Common::String args = "";
 			Common::String act(chrs + startpos, chrs + pos);
@@ -357,7 +370,7 @@ void ScriptManager::parseResults(Common::SeekableReadStream &stream, Common::Lis
 					args = Common::String(chrs + startpos, chrs + pos);
 				}
 			}
-			debug(4, "Action string: '%s', slot %d, arguments string '%s'", act.c_str(), slot, args.c_str());
+			debugC(4, kDebugScript, "Action string: '%s', slot %d, arguments string '%s'", act.c_str(), slot, args.c_str());
 
 				// Parse for the action type
 				if (act.matchString("add", true)) {
@@ -494,10 +507,12 @@ Control *ScriptManager::parseControl(Common::String &line, Common::SeekableReadS
 	uint32 key;
 	char controlTypeBuffer[20];
 
-	sscanf(line.c_str(), "control:%u %s {", &key, controlTypeBuffer);
-
+	if (sscanf(line.c_str(), "control:%u %s {", &key, controlTypeBuffer) != 2) {
+		debugC(kDebugScript, "Malformed control string: %s", line.c_str());
+		return NULL;
+	}
+		
 	Common::String controlType(controlTypeBuffer);
-
 	if (controlType.equalsIgnoreCase("push_toggle")) {
 		// WORKAROUND for a script bug in ZGI: There is an invalid hotspot
 		// at scene em1h (bottom of tower), which points to a missing
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index 41019287c28..15a2fd18543 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -114,7 +114,7 @@ void ScriptManager::update(uint deltaTimeMillis) {
 	}
 
 	updateNodes(deltaTimeMillis);
-	debug(5, "Script nodes updated");
+	debugC(5, kDebugLoop, "Script nodes updated");
 	if (!execScope(_nodeview)) {
 		return;
 	}
@@ -320,7 +320,7 @@ bool ScriptManager::checkPuzzleCriteria(Puzzle *puzzle, uint counter) {
 
 	// criteriaList can be empty. Aka, the puzzle should be executed immediately
 	if (puzzle->criteriaList.empty() || criteriaMet) {
-		debug(1, "Puzzle %u criteria passed. Executing its ResultActions", puzzle->key);
+		debugC(1, kDebugPuzzle, "Puzzle %u criteria passed. Executing its ResultActions", puzzle->key);
 
 		// Set the puzzle as completed
 		setStateValue(puzzle->key, 1);
@@ -533,7 +533,7 @@ void ScriptManager::killSideFxType(ScriptingEffect::ScriptingEffectType type) {
 }
 
 void ScriptManager::onMouseDown(const Common::Point &screenSpacePos, const Common::Point &backgroundImageSpacePos) {
-	debug(1, "Mouse panorama/script coordinates %d x %d", backgroundImageSpacePos.x, backgroundImageSpacePos.y);
+	debugC(1, kDebugMouse, "Mouse panorama/script coordinates %d x %d", backgroundImageSpacePos.x, backgroundImageSpacePos.y);
 	if (!_activeControls) {
 		return;
 	}
@@ -596,6 +596,7 @@ void ScriptManager::changeLocation(const Location &_newLocation) {
 }
 
 void ScriptManager::changeLocation(char world, char room, char node, char view, uint32 offset) {
+	debugC(1, kDebugScript, "\tPreparing to change location");
 	_changeLocationDelayCycles = 1;
 
 	_nextLocation.world = world;
@@ -623,7 +624,7 @@ void ScriptManager::changeLocation(char world, char room, char node, char view,
 
 void ScriptManager::ChangeLocationReal(bool isLoading) {
 	assert(_nextLocation.world != 0);
-	debug(1, "\tChanging location to: World %c, Room %c, Node %c, View %c, Offset %u", _nextLocation.world, _nextLocation.room, _nextLocation.node, _nextLocation.view, _nextLocation.offset);
+	debugC(1, kDebugScript, "\tChanging location to: World %c, Room %c, Node %c, View %c, Offset %u", _nextLocation.world, _nextLocation.room, _nextLocation.node, _nextLocation.view, _nextLocation.offset);
 
 	const bool enteringMenu = (_nextLocation.world == 'g' && _nextLocation.room == 'j');
 	const bool leavingMenu = (_currentLocation.world == 'g' && _currentLocation.room == 'j');
@@ -760,6 +761,7 @@ void ScriptManager::ChangeLocationReal(bool isLoading) {
 	}
 
 	_engine->getRenderManager()->checkBorders();
+	debugC(1, kDebugScript, "\tLocation change complete");
 }
 
 void ScriptManager::serialize(Common::WriteStream *stream) {
diff --git a/engines/zvision/sound/midi.cpp b/engines/zvision/sound/midi.cpp
index 2729302478d..b0016680575 100644
--- a/engines/zvision/sound/midi.cpp
+++ b/engines/zvision/sound/midi.cpp
@@ -23,6 +23,7 @@
 #include "common/debug.h"
 #include "common/scummsys.h"
 #include "common/textconsole.h"
+#include "zvision/detection.h"
 #include "zvision/sound/midi.h"
 
 namespace ZVision {
@@ -37,7 +38,7 @@ MidiManager::MidiManager() {
 		Common::String driverName = MidiDriver::getDeviceString(dev, MidiDriver::DeviceStringType::kDriverName);
 		Common::String deviceName = MidiDriver::getDeviceString(dev, MidiDriver::DeviceStringType::kDeviceName);
 		_mt32 = MidiDriver::getMusicType(dev) == MT_MT32;
-		debug(1, "MIDI opened, driver type: %s, device name: %s", driverName.c_str(), deviceName.c_str());
+		debugC(1, kDebugSound, "MIDI opened, driver type: %s, device name: %s", driverName.c_str(), deviceName.c_str());
 		_available = true;
 		_maxChannels = _driver->MIDI_CHANNEL_COUNT;
 	}
@@ -67,7 +68,7 @@ void MidiManager::noteOn(uint8 channel, uint8 note, uint8 velocity) {
 	_activeChannels[channel].playing = true;
 	_activeChannels[channel].note = note;
 	send(0x90 | channel, note, velocity);
-	debug(1, "MIDI note on, channel %d, note %d, velocity %d", channel, note, velocity);
+	debugC(1, kDebugSound, "MIDI note on, channel %d, note %d, velocity %d", channel, note, velocity);
 }
 
 void MidiManager::noteOff(uint8 channel) {
@@ -89,21 +90,21 @@ int8 MidiManager::getFreeChannel() {
 
 void MidiManager::setVolume(uint8 channel, uint8 volume) {
 	assert(channel <= 15);
-	debug(1, "MIDI volume out %d", volume >> 1);
+	debugC(1, kDebugSound, "MIDI volume out %d", volume >> 1);
 	send(0xB0 | channel, 0x07, volume >> 1);
 }
 
 void MidiManager::setBalance(uint8 channel, int8 balance) {
 	assert(channel <= 15);
 	uint8 _balance = (uint8)(balance + 128);
-	debug(1, "MIDI balance out %d", _balance >> 1);
+	debugC(1, kDebugSound, "MIDI balance out %d", _balance >> 1);
 	send(0xB0 | channel, 0x08, _balance >> 1);
 }
 
 void MidiManager::setPan(uint8 channel, int8 pan) {
 	assert(channel <= 15);
 	uint8 _pan = (uint8)(pan + 128);
-	debug(1, "MIDI pan in %d, out %d", pan, _pan >> 1);
+	debugC(1, kDebugSound, "MIDI pan in %d, out %d", pan, _pan >> 1);
 	send(0xB0 | channel, 0x0A, _pan >> 1);
 }
 
diff --git a/engines/zvision/sound/volume_manager.cpp b/engines/zvision/sound/volume_manager.cpp
index 79d931d1a2c..e44061e7039 100644
--- a/engines/zvision/sound/volume_manager.cpp
+++ b/engines/zvision/sound/volume_manager.cpp
@@ -20,6 +20,7 @@
  */
 
 #include "common/debug.h"
+#include "zvision/detection.h"
 #include "zvision/scripting/script_manager.h"
 #include "zvision/sound/volume_manager.h"
 
@@ -151,7 +152,7 @@ uint8 VolumeManager::convert(uint8 inputValue, volumeScaling &mode, Math::Angle
 	directionalOutput /= 0xFF;
 	output *= (0xFF - directionality);
 	output = (output + directionalOutput) / 0xFF;
-	debug(4, "Directionally converted output %d", output);
+	debugC(4, kDebugSound, "Directionally converted output %d", output);
 	return output;
 };
 
@@ -189,7 +190,7 @@ uint8 VolumeManager::convert(uint8 inputValue, volumeScaling &mode) {
 		output = scaledInput;
 		break;
 	}
-	debug(4, "Scripted volume %d, scaled volume %d, converted output %d", inputValue, scaledInput, output);
+	debugC(4, kDebugSound, "Scripted volume %d, scaled volume %d, converted output %d", inputValue, scaledInput, output);
 	return output;
 };
 
diff --git a/engines/zvision/text/subtitle_manager.cpp b/engines/zvision/text/subtitle_manager.cpp
index 8a7d25b3be2..a15ed0a47ac 100644
--- a/engines/zvision/text/subtitle_manager.cpp
+++ b/engines/zvision/text/subtitle_manager.cpp
@@ -20,6 +20,7 @@
  */
 
 #include "common/system.h"
+#include "zvision/detection.h"
 #include "zvision/file/search_manager.h"
 #include "zvision/graphics/render_manager.h"
 #include "zvision/scripting/script_manager.h"
@@ -56,7 +57,7 @@ void SubtitleManager::process(int32 deltatime) {
 			_redraw = true;
 		// Update all subtitles' respective deletion timers
 		if (it->_value->process(deltatime)) {
-			debug(4, "Deleting subtitle, subId=%d", it->_key);
+			debugC(4, kDebugSubtitle, "Deleting subtitle, subId=%d", it->_key);
 			_subsFocus.remove(it->_key);
 			delete it->_value;
 			_subsList.erase(it);
@@ -65,18 +66,18 @@ void SubtitleManager::process(int32 deltatime) {
 	}
 	if (_subsList.size() == 0)
 		if (_subId != 0) {
-			debug(4, "Resetting subId to 0");
+			debugC(4, kDebugSubtitle, "Resetting subId to 0");
 			_subId = 0;
 			_subsFocus.clear();
 		}
 	if (_redraw) {
-		debug(4, "Redrawing subtitles");
+		debugC(4, kDebugSubtitle, "Redrawing subtitles");
 		// Blank subtitle buffer
 		_renderManager->clearTextSurface();
 		// Render just the most recent subtitle
 		if (_subsFocus.size()) {
 			uint16 curSub = _subsFocus.front();
-			debug(4, "Rendering subtitle %d", curSub);
+			debugC(4, kDebugSubtitle, "Rendering subtitle %d", curSub);
 			Subtitle *sub = _subsList[curSub];
 			if (sub->_lineId >= 0) {
 				Graphics::Surface textSurface;
@@ -102,7 +103,7 @@ void SubtitleManager::update(int32 count, uint16 subid) {
 
 uint16 SubtitleManager::create(const Common::Path &subname, bool vob) {
 	_subId++;
-	debug(2, "Creating scripted subtitle, subId=%d", _subId);
+	debugC(2, kDebugSubtitle, "Creating scripted subtitle, subId=%d", _subId);
 	_subsList[_subId] = new Subtitle(_engine, subname, vob);
 	_subsFocus.set(_subId);
 	return _subId;
@@ -110,7 +111,7 @@ uint16 SubtitleManager::create(const Common::Path &subname, bool vob) {
 
 uint16 SubtitleManager::create(const Common::Path &subname, Audio::SoundHandle handle) {
 	_subId++;
-	debug(2, "Creating scripted subtitle, subId=%d", _subId);
+	debugC(2, kDebugSubtitle, "Creating scripted subtitle, subId=%d", _subId);
 	_subsList[_subId] = new AutomaticSubtitle(_engine, subname, handle);
 	_subsFocus.set(_subId);
 	return _subId;
@@ -118,7 +119,7 @@ uint16 SubtitleManager::create(const Common::Path &subname, Audio::SoundHandle h
 
 uint16 SubtitleManager::create(const Common::String &str) {
 	_subId++;
-	debug(2, "Creating simple subtitle, subId=%d, message %s", _subId, str.c_str());
+	debugC(2, kDebugSubtitle, "Creating simple subtitle, subId=%d, message %s", _subId, str.c_str());
 	_subsList[_subId] = new Subtitle(_engine, str, _textArea);
 	_subsFocus.set(_subId);
 	return _subId;
@@ -126,21 +127,21 @@ uint16 SubtitleManager::create(const Common::String &str) {
 
 void SubtitleManager::destroy(uint16 id) {
 	if (_subsList.contains(id)) {
-		debug(2, "Marking subtitle %d for immediate deletion", id);
+		debugC(2, kDebugSubtitle, "Marking subtitle %d for immediate deletion", id);
 		_subsList[id]->_toDelete = true;
 	}
 }
 
 void SubtitleManager::destroy(uint16 id, int16 delay) {
 	if (_subsList.contains(id)) {
-		debug(2, "Marking subtitle %d for deletion in %dms", id, delay);
+		debugC(2, kDebugSubtitle, "Marking subtitle %d for deletion in %dms", id, delay);
 		_subsList[id]->_timer = delay;
 	}
 }
 
 void SubtitleManager::timedMessage(const Common::String &str, uint16 milsecs) {
 	uint16 msgid = create(str);
-	debug(1, "initiating timed message: %s to subtitle id %d, time %d", str.c_str(), msgid, milsecs);
+	debugC(1, kDebugSubtitle, "initiating timed message: %s to subtitle id %d, time %d", str.c_str(), msgid, milsecs);
 	update(0, msgid);
 	process(0);
 	destroy(msgid, milsecs);
@@ -148,7 +149,7 @@ void SubtitleManager::timedMessage(const Common::String &str, uint16 milsecs) {
 
 bool SubtitleManager::askQuestion(const Common::String &str) {
 	uint16 msgid = create(str);
-	debug(1, "initiating user question: %s to subtitle id %d", str.c_str(), msgid);
+	debugC(1, kDebugSubtitle, "initiating user question: %s to subtitle id %d", str.c_str(), msgid);
 	update(0, msgid);
 	process(0);
 	_renderManager->renderSceneToScreen(true);
@@ -208,7 +209,7 @@ bool SubtitleManager::askQuestion(const Common::String &str) {
 
 void SubtitleManager::delayedMessage(const Common::String &str, uint16 milsecs) {
 	uint16 msgid = create(str);
-	debug(1, "initiating delayed message: %s to subtitle id %d, delay %dms", str.c_str(), msgid, milsecs);
+	debugC(1, kDebugSubtitle, "initiating delayed message: %s to subtitle id %d, delay %dms", str.c_str(), msgid, milsecs);
 	update(0, msgid);
 	process(0);
 	_renderManager->renderSceneToScreen(true);
@@ -236,7 +237,7 @@ void SubtitleManager::delayedMessage(const Common::String &str, uint16 milsecs)
 
 void SubtitleManager::showDebugMsg(const Common::String &msg, int16 delay) {
 	uint16 msgid = create(msg);
-	debug(1, "initiating in-game debug message: %s to subtitle id %d, delay %dms", msg.c_str(), msgid, delay);
+	debugC(1, kDebugSubtitle, "initiating in-game debug message: %s to subtitle id %d, delay %dms", msg.c_str(), msgid, delay);
 	update(0, msgid);
 	process(0);
 	destroy(msgid, delay);
@@ -264,28 +265,30 @@ Subtitle::Subtitle(ZVision *engine, const Common::Path &subname, bool vob) :
 			// Not used
 		} else if (str.matchString("*Rectangle*", true)) {
 			int32 x1, y1, x2, y2;
-			sscanf(str.c_str(), "%*[^:]:%d %d %d %d", &x1, &y1, &x2, &y2);
-			_textArea = Common::Rect(x1, y1, x2, y2);
-			debug(1, "Original subtitle script rectangle coordinates: l%d, t%d, r%d, b%d", x1, y1, x2, y2);
-			// Original game subtitle scripts appear to define subtitle rectangles relative to origin of working area.
-			// To allow arbitrary aspect ratios, we need to instead place these relative to origin of text area.
-			// This will allow the managed text area to then be arbitrarily placed on the screen to suit different aspect ratios.
-			_textArea.translate(_textOffset.x, _textOffset.y);  // Convert working area coordinates to text area coordinates
-			debug(1, "Text area coordinates: l%d, t%d, r%d, b%d", _textArea.left, _textArea.top, _textArea.right, _textArea.bottom);
+			if (sscanf(str.c_str(), "%*[^:]:%d %d %d %d", &x1, &y1, &x2, &y2) == 4) {
+				_textArea = Common::Rect(x1, y1, x2, y2);
+				debugC(1, kDebugSubtitle, "Original subtitle script rectangle coordinates: l%d, t%d, r%d, b%d", x1, y1, x2, y2);
+				// Original game subtitle scripts appear to define subtitle rectangles relative to origin of working area.
+				// To allow arbitrary aspect ratios, we need to instead place these relative to origin of text area.
+				// This will allow the managed text area to then be arbitrarily placed on the screen to suit different aspect ratios.
+				_textArea.translate(_textOffset.x, _textOffset.y);  // Convert working area coordinates to text area coordinates
+				debugC(1, kDebugSubtitle, "Text area coordinates: l%d, t%d, r%d, b%d", _textArea.left, _textArea.top, _textArea.right, _textArea.bottom);
+			}
 		} else if (str.matchString("*TextFile*", true)) {
 			char filename[64];
-			sscanf(str.c_str(), "%*[^:]:%s", filename);
-			Common::File txtFile;
-			if (_engine->getSearchManager()->openFile(txtFile, Common::Path(filename))) {
-				while (!txtFile.eos()) {
-					Common::String txtline = readWideLine(txtFile).encode();
-					Line curLine;
-					curLine.start = -1;
-					curLine.stop = -1;
-					curLine.subStr = txtline;
-					_lines.push_back(curLine);
+			if (sscanf(str.c_str(), "%*[^:]:%s", filename) == 1) {
+				Common::File txtFile;
+				if (_engine->getSearchManager()->openFile(txtFile, Common::Path(filename))) {
+					while (!txtFile.eos()) {
+						Common::String txtline = readWideLine(txtFile).encode();
+						Line curLine;
+						curLine.start = -1;
+						curLine.stop = -1;
+						curLine.subStr = txtline;
+						_lines.push_back(curLine);
+					}
+					txtFile.close();
 				}
-				txtFile.close();
 			}
 		} else {
 			int32 st; // Line start time
@@ -316,7 +319,7 @@ Subtitle::Subtitle(ZVision *engine, const Common::String &str, const Common::Rec
 	_toDelete(false),
 	_redraw(false) {
 	_textArea = textArea;
-	debug(1, "Text area coordinates: l%d, t%d, r%d, b%d", _textArea.left, _textArea.top, _textArea.right, _textArea.bottom);
+	debugC(1, kDebugSubtitle, "Text area coordinates: l%d, t%d, r%d, b%d", _textArea.left, _textArea.top, _textArea.right, _textArea.bottom);
 	Line curLine;
 	curLine.start = -1;
 	curLine.stop = 0;
diff --git a/engines/zvision/text/truetype_font.cpp b/engines/zvision/text/truetype_font.cpp
index 78dfe0488c7..875c117a6c5 100644
--- a/engines/zvision/text/truetype_font.cpp
+++ b/engines/zvision/text/truetype_font.cpp
@@ -101,7 +101,7 @@ bool StyledTTFont::loadFont(const Common::String &fontName, int32 point, uint st
 	}
 
 	if (newFontName.empty()) {
-		debug("Could not identify font: %s. Reverting to Arial", fontName.c_str());
+		warning("Could not identify font: %s. Reverting to Arial", fontName.c_str());
 		newFontName = "arial.ttf";
 		liberationFontName = "LiberationSans-Regular.ttf";
 	}
diff --git a/engines/zvision/video/rlf_decoder.cpp b/engines/zvision/video/rlf_decoder.cpp
index 4e9f9444f76..7e380ad6168 100644
--- a/engines/zvision/video/rlf_decoder.cpp
+++ b/engines/zvision/video/rlf_decoder.cpp
@@ -25,6 +25,7 @@
 #include "common/scummsys.h"
 #include "common/str.h"
 #include "common/textconsole.h"
+#include "zvision/detection.h"
 #include "zvision/video/rlf_decoder.h"
 
 namespace ZVision {
@@ -227,7 +228,7 @@ void RLFDecoder::RLFVideoTrack::decodeMaskedRunLengthEncoding(int8 *source, int8
 				if (sourceOffset + 1 >= sourceSize) {
 					return;
 				} else if (destOffset + 1 >= destSize) {
-					debug(3, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
+					debugC(3, kDebugVideo, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
 					return;
 				}
 
@@ -244,7 +245,7 @@ void RLFDecoder::RLFVideoTrack::decodeMaskedRunLengthEncoding(int8 *source, int8
 			if (sourceOffset + 1 >= sourceSize) {
 				return;
 			} else if (destOffset + 1 >= destSize) {
-				debug(3, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
+				debugC(3, kDebugVideo, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
 				return;
 			}
 
@@ -271,7 +272,7 @@ void RLFDecoder::RLFVideoTrack::decodeSimpleRunLengthEncoding(int8 *source, int8
 				if (sourceOffset + 1 >= sourceSize) {
 					return;
 				} else if (destOffset + 1 >= destSize) {
-					debug(3, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
+					debugC(3, kDebugVideo, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
 					return;
 				}
 
@@ -295,7 +296,7 @@ void RLFDecoder::RLFVideoTrack::decodeSimpleRunLengthEncoding(int8 *source, int8
 			numberOfCopy = numberOfSamples + 2;
 			while (numberOfCopy > 0) {
 				if (destOffset + 1 >= destSize) {
-					debug(3, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
+					debugC(3, kDebugVideo, "Frame decoding overflow\n\tsourceOffset=%u\tsourceSize=%u\n\tdestOffset=%u\tdestSize=%u", sourceOffset, sourceSize, destOffset, destSize);
 					return;
 				}
 
diff --git a/engines/zvision/video/video.cpp b/engines/zvision/video/video.cpp
index ff4224c3fbc..7ccd69418b8 100644
--- a/engines/zvision/video/video.cpp
+++ b/engines/zvision/video/video.cpp
@@ -43,7 +43,7 @@ Video::VideoDecoder *ZVision::loadAnimation(const Common::Path &fileName) {
 	tmpFileName.toLowercase();
 	Video::VideoDecoder *animation = NULL;
 
-	debug(1, "Loading animation %s", fileName.toString().c_str());
+	debugC(1, kDebugVideo, "Loading animation %s", fileName.toString().c_str());
 
 	if (tmpFileName.hasSuffix(".rlf"))
 		animation = new RLFDecoder();
@@ -88,30 +88,30 @@ void ZVision::playVideo(Video::VideoDecoder &vid, Common::Rect dstRect, bool ski
 	bool scaled = false;
 	workingArea.moveTo(0, 0); // Set local origin system in this scope to origin of working area
 
-	debug(1, "Playing video, source %d,%d,%d,%d, at destination %d,%d,%d,%d", srcRect.left, srcRect.top, srcRect.right, srcRect.bottom, dstRect.left, dstRect.top, dstRect.right, dstRect.bottom);
+	debugC(1, kDebugVideo, "Playing video, source %d,%d,%d,%d, at destination %d,%d,%d,%d", srcRect.left, srcRect.top, srcRect.right, srcRect.bottom, dstRect.left, dstRect.top, dstRect.right, dstRect.bottom);
 
 	if (dstRect.isEmpty())
 		dstRect = frameArea;
 	dstRect.clip(workingArea);
 
-	debug(2, "Clipped dstRect = %d,%d,%d,%d", dstRect.left, dstRect.top, dstRect.right, dstRect.bottom);
+	debugC(2, kDebugVideo, "Clipped dstRect = %d,%d,%d,%d", dstRect.left, dstRect.top, dstRect.right, dstRect.bottom);
 
 	if (srcRect.isEmpty())
 		srcRect = frameArea;
 	else
 		srcRect.clip(frameArea);
 
-	debug(2, "Clipped srcRect = %d,%d,%d,%d", srcRect.left, srcRect.top, srcRect.right, srcRect.bottom);
+	debugC(2, kDebugVideo, "Clipped srcRect = %d,%d,%d,%d", srcRect.left, srcRect.top, srcRect.right, srcRect.bottom);
 
 	Graphics::ManagedSurface &outSurface = _renderManager->getVidSurface(dstRect);
 	dstRect.moveTo(0, 0);
 	dstRect.clip(Common::Rect(outSurface.w, outSurface.h));
 
-	debug(2, "dstRect clipped with outSurface = %d,%d,%d,%d", dstRect.left, dstRect.top, dstRect.right, dstRect.bottom);
+	debugC(2, kDebugVideo, "dstRect clipped with outSurface = %d,%d,%d,%d", dstRect.left, dstRect.top, dstRect.right, dstRect.bottom);
 
-	debug(1, "Final size %d x %d, at working window coordinates %d, %d", srcRect.width(), srcRect.height(), dstRect.left, dstRect.top);
+	debugC(1, kDebugVideo, "Final size %d x %d, at working window coordinates %d, %d", srcRect.width(), srcRect.height(), dstRect.left, dstRect.top);
 	if (srcRect.width() != dstRect.width() || srcRect.height() != dstRect.height()) {
-		debug(1, "Video will be scaled from %dx%d to %dx%d", srcRect.width(), srcRect.height(), dstRect.width(), dstRect.height());
+		debugC(1, kDebugVideo, "Video will be scaled from %dx%d to %dx%d", srcRect.width(), srcRect.height(), dstRect.width(), dstRect.height());
 		scaled = true;
 	}
 
@@ -155,10 +155,10 @@ void ZVision::playVideo(Video::VideoDecoder &vid, Common::Rect dstRect, bool ski
 			if (frame) {
 				_renderManager->renderSceneToScreen(true, true, true); // Redraw text area to clean background of subtitles for videos that don't fill entire working area, e.g, Nemesis sarcophagi
 				if (scaled) {
-					debug(8, "Scaled blit from area %d x %d to video output surface at output surface position %d, %d", srcRect.width(), srcRect.height(), dstRect.left, dstRect.top);
+					debugC(8, kDebugVideo, "Scaled blit from area %d x %d to video output surface at output surface position %d, %d", srcRect.width(), srcRect.height(), dstRect.left, dstRect.top);
 					outSurface.blitFrom(*frame, srcRect, dstRect);
 				} else {
-					debug(8, "Simple blit from area %d x %d to video output surface at output surface position %d, %d", srcRect.width(), srcRect.height(), dstRect.left, dstRect.top);
+					debugC(8, kDebugVideo, "Simple blit from area %d x %d to video output surface at output surface position %d, %d", srcRect.width(), srcRect.height(), dstRect.left, dstRect.top);
 					outSurface.simpleBlitFrom(*frame, srcRect, dstRect.origin());
 				}
 				_subtitleManager->process(0);
@@ -177,7 +177,7 @@ void ZVision::playVideo(Video::VideoDecoder &vid, Common::Rect dstRect, bool ski
 	_videoIsPlaying = false;
 	_clock.start();
 
-	debug(1, "Video playback complete");
+	debugC(1, kDebugVideo, "Video playback complete");
 }
 
 double ZVision::getVobAmplification(Common::String fileName) const {
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index 4d776ba8a6e..3904ec547cf 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -109,13 +109,13 @@ ZVision::ZVision(OSystem *syst, const ZVisionGameDescription *gameDesc)
 	  _renderedFrameCount(0),
 	  _fps(0) {
 
-	debug(1, "ZVision::ZVision");
+	debugC(1, kDebugLoop, "ZVision::ZVision");
 
 	memset(_cheatBuffer, 0, sizeof(_cheatBuffer));
 }
 
 ZVision::~ZVision() {
-	debug(1, "ZVision::~ZVision");
+	debugC(1, kDebugLoop, "ZVision::~ZVision");
 
 	// Dispose of resources
 	delete _cursorManager;
@@ -345,26 +345,26 @@ Common::Error ZVision::run() {
 
 	// Main loop
 	while (!shouldQuit()) {
-		debug(5, "\nInitiating new game cycle");
-		debug(5, "Timers");
+		debugC(1, kDebugLoop, "\nInitiating new game cycle");
+		debugC(5, kDebugLoop, "Timers");
 		// Timers
 		_clock.update();
 		uint32 deltaTime = _clock.getDeltaTime();
-		debug(5, "Logic");
+		debugC(5, kDebugLoop, "Logic");
 		// Process game logic & update backbuffers as necessary
-		debug(5, "Cursor");
+		debugC(5, kDebugLoop, "Cursor");
 		_cursorManager->setItemID(_scriptManager->getStateValue(StateKey_InventoryItem));
-		debug(5, "Events");
+		debugC(5, kDebugLoop, "Events");
 		processEvents();  // NB rotateTo or playVideo event will pause clock & call renderSceneToScreen() directly.
-		debug(5, "Rotation");
+		debugC(5, kDebugLoop, "Rotation");
 		_renderManager->updateRotation();
-		debug(5, "Scripts");
+		debugC(5, kDebugLoop, "Scripts");
 		_scriptManager->update(deltaTime);
-		debug(5, "Menu");
+		debugC(5, kDebugLoop, "Menu");
 		_menu->process(deltaTime);
-		debug(5, "Subtitles");
+		debugC(5, kDebugLoop, "Subtitles");
 		_subtitleManager->process(deltaTime);
-		debug(5, "Render");
+		debugC(5, kDebugLoop, "Render");
 		// Render the backBuffer to the screen
 		_renderManager->prepareBackground();
 		if (_renderManager->renderSceneToScreen()) {
@@ -388,7 +388,7 @@ void ZVision::pauseEngineIntern(bool pause) {
 }
 
 void ZVision::setRenderDelay(uint delay) {
-	debug(2, "Setting framerenderdelay to %d", delay);
+	debugC(2, kDebugGraphics, "Setting framerenderdelay to %d", delay);
 	_frameRenderDelay = delay;
 }
 
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index 4cc9e708557..786ea8bb3a5 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -52,6 +52,8 @@ class VideoDecoder;
  */
 namespace ZVision {
 
+struct ZvisionGameDescription;
+
 class Console;
 class ScriptManager;
 class RenderManager;


Commit: 9a7d11048c9dffe714f4b3c3cc516541d9c85af0
    https://github.com/scummvm/scummvm/commit/9a7d11048c9dffe714f4b3c3cc516541d9c85af0
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:02+02:00

Commit Message:
GRAPHICS: Frame limiter member initialisation moved to definition where possible.

Changed paths:
    graphics/framelimiter.cpp
    graphics/framelimiter.h


diff --git a/graphics/framelimiter.cpp b/graphics/framelimiter.cpp
index 0365098d39d..52c09b031f6 100644
--- a/graphics/framelimiter.cpp
+++ b/graphics/framelimiter.cpp
@@ -27,14 +27,7 @@ namespace Graphics {
 
 FrameLimiter::FrameLimiter(OSystem *system, const uint framerate, const bool deferToVsync) :
 	_system(system),
-	_deferToVsync(deferToVsync),
-	_frameStart(0),
-	_frameLimit(0),
-	_frameDuration(0),
-	_drawStart(0),
-	_drawDuration(0),
-	_loopDuration(0),
-	_delay(0) {
+	_deferToVsync(deferToVsync) {
 	initialize(framerate);
 }
 
diff --git a/graphics/framelimiter.h b/graphics/framelimiter.h
index 91aeab134e5..5422fe81404 100644
--- a/graphics/framelimiter.h
+++ b/graphics/framelimiter.h
@@ -96,14 +96,14 @@ private:
 
 	bool _enabled;
 	bool _deferToVsync;
-	uint _frameStart;  // Time at which screen update completed and startFrame() was called; start of next cycle of game logic
-	uint _frameLimit;  // Target frame duration to achieve specified FPS
-	uint _frameDuration; // Duration of previous frame between successive startFrame() calls; total game logic, delay (if any) and screen update time
-	uint _drawStart;  // Time at which delayBeforeSwap() returns
-	uint _drawDuration;  // Measured screen update time
-	uint _loopDuration;  // Duration of last game logic cycle, from when startFrame() was called to when delayBeforeSwap() was called
-	int _delay; // Time to delay before returning from delayBeforeSwap()
-	uint _now; // Current time
+	uint _frameStart = 0;  // Time at which screen update completed and startFrame() was called; start of next cycle of game logic
+	uint _frameLimit = 0;  // Target frame duration to achieve specified FPS
+	uint _frameDuration = 0; // Duration of previous frame between successive startFrame() calls; total game logic, delay (if any) and screen update time
+	uint _drawStart = 0;  // Time at which delayBeforeSwap() returns
+	uint _drawDuration = 0;  // Measured screen update time
+	uint _loopDuration = 0;  // Duration of last game logic cycle, from when startFrame() was called to when delayBeforeSwap() was called
+	int _delay = 0; // Time to delay before returning from delayBeforeSwap()
+	uint _now = 0; // Current time
 };
 
 } // End of namespace Graphics


Commit: 9b80184e12278fcf91124a63ff9b1aadcbaa93ce
    https://github.com/scummvm/scummvm/commit/9b80184e12278fcf91124a63ff9b1aadcbaa93ce
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:02+02:00

Commit Message:
ZVISION: Reduce variable scope & make const where appropriate in RenderTable methods.

Changed paths:
    engines/zvision/graphics/render_table.cpp
    engines/zvision/graphics/render_table.h


diff --git a/engines/zvision/graphics/render_table.cpp b/engines/zvision/graphics/render_table.cpp
index cd2434015ee..79cce7ad4c0 100644
--- a/engines/zvision/graphics/render_table.cpp
+++ b/engines/zvision/graphics/render_table.cpp
@@ -132,8 +132,6 @@ void RenderTable::mutateImage(uint16 *sourceBuffer, uint16 *destBuffer, uint32 d
 void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcBuf, bool highQuality) {
 	uint32 destOffset = 0;
 	uint32 sourceOffset = 0;
-	uint32 srcIndexXL, srcIndexYT;
-
 	uint16 *sourceBuffer = (uint16 *)srcBuf->getPixels();
 	uint16 *destBuffer = (uint16 *)dstBuf->getPixels();
 	if (highQuality != _highQuality) {
@@ -141,44 +139,40 @@ void RenderTable::mutateImage(Graphics::Surface *dstBuf, Graphics::Surface *srcB
 		generateRenderTable();
 	}
 	uint32 mutationTime = _system->getMillis();
-
 	if (_highQuality) {
 		// Apply bilinear interpolation
-		uint32 srcIndexYB, srcIndexXR;
-		uint32 rTL, rTR, rBL, rBR, rF;
-		uint32 gTL, gTR, gBL, gBR, gF;
-		uint32 bTL, bTR, bBL, bBR, bF;
-		FilterPixel curP;
 		for (int16 y = 0; y < srcBuf->h; ++y) {
 			sourceOffset = y * _numColumns;
 			for (int16 x = 0; x < srcBuf->w; ++x) {
-				curP = _internalBuffer[sourceOffset + x];
-				srcIndexYT = y + curP._src.top;
-				srcIndexYB = y + curP._src.bottom;
-				srcIndexXL = x + curP._src.left;
-				srcIndexXR = x + curP._src.right;
+				const FilterPixel &curP = _internalBuffer[sourceOffset + x];
+				const uint32 srcIndexYT = y + curP._src.top;
+				const uint32 srcIndexYB = y + curP._src.bottom;
+				const uint32 srcIndexXL = x + curP._src.left;
+				const uint32 srcIndexXR = x + curP._src.right;
+				uint32 rTL, rTR, rBL, rBR;
+				uint32 gTL, gTR, gBL, gBR;
+				uint32 bTL, bTR, bBL, bBR;
 				splitColor(sourceBuffer[srcIndexYT * _numColumns + srcIndexXL], rTL, gTL, bTL);
 				splitColor(sourceBuffer[srcIndexYT * _numColumns + srcIndexXR], rTR, gTR, bTR);
 				splitColor(sourceBuffer[srcIndexYB * _numColumns + srcIndexXL], rBL, gBL, bBL);
 				splitColor(sourceBuffer[srcIndexYB * _numColumns + srcIndexXR], rBR, gBR, bBR);
-				rF = curP._fTL * rTL + curP._fTR * rTR + curP._fBL * rBL + curP._fBR * rBR;
-				gF = curP._fTL * gTL + curP._fTR * gTR + curP._fBL * gBL + curP._fBR * gBR;
-				bF = curP._fTL * bTL + curP._fTR * bTR + curP._fBL * bBL + curP._fBR * bBR;
+				const uint32 rF = curP._fTL * rTL + curP._fTR * rTR + curP._fBL * rBL + curP._fBR * rBR;
+				const uint32 gF = curP._fTL * gTL + curP._fTR * gTR + curP._fBL * gBL + curP._fBR * gBR;
+				const uint32 bF = curP._fTL * bTL + curP._fTR * bTR + curP._fBL * bBL + curP._fBR * bBR;
 				destBuffer[destOffset] = mergeColor(rF, gF, bF);
 				destOffset++;
 			}
 		}
 	} else {
 		// Apply nearest-neighbour interpolation
-		uint32 index;
 		for (int16 y = 0; y < srcBuf->h; ++y) {
 			sourceOffset = y * _numColumns;
 			for (int16 x = 0; x < srcBuf->w; ++x) {
-				index = sourceOffset + x;
+				const uint32 index = sourceOffset + x;
 				// RenderTable only stores offsets from the original coordinates
-				srcIndexXL = x + (_internalBuffer[index]._xDir ? _internalBuffer[index]._src.right : _internalBuffer[index]._src.left);
-				srcIndexYT = y + (_internalBuffer[index]._yDir ? _internalBuffer[index]._src.bottom : _internalBuffer[index]._src.top);
-				destBuffer[destOffset] = sourceBuffer[srcIndexYT * _numColumns + srcIndexXL];
+				const uint32 srcIndexX = x + (_internalBuffer[index]._xDir ? _internalBuffer[index]._src.right : _internalBuffer[index]._src.left);
+				const uint32 srcIndexY = y + (_internalBuffer[index]._yDir ? _internalBuffer[index]._src.bottom : _internalBuffer[index]._src.top);
+				destBuffer[destOffset] = sourceBuffer[srcIndexY * _numColumns + srcIndexX];
 				destOffset++;
 			}
 		}
@@ -209,15 +203,13 @@ void RenderTable::generateLookupTable(bool tilt) {
 	debugC(5, kDebugGraphics, "_halfWidth %f, _halfHeight %f", _halfWidth, _halfHeight);
 	debugC(5, kDebugGraphics, "_halfRows %d, _halfColumns %d", _halfRows, _halfColumns);
 	uint32 generationTime = _system->getMillis();
-	float alpha, cosAlpha, polarCoordInCylinderCoords, linearCoordInCylinderCoords, cylinderRadius, xOffset, yOffset;
+	float cosAlpha, polarCoordInCylinderCoords, cylinderRadius, xOffset, yOffset;
 	uint32 indexTL, indexBL, indexTR, indexBR;
-	uint x = 0;
-	uint y = 0;
 	auto outerLoop = [&](uint & polarCoord, float & halfPolarSize, float & scale) {
 		// polarCoord is the coordinate of the working window pixel parallel to the direction of camera rotation
 		// halfPolarSize is the distance from the central axis to the outermost working window pixel in the direction of camera rotation
 		// alpha represents the angle in the direction of camera rotation between the view axis and the centre of a pixel at the given polar coordinate
-		alpha = atan(((float)polarCoord - halfPolarSize) / cylinderRadius);
+		const float alpha = atan(((float)polarCoord - halfPolarSize) / cylinderRadius);
 		// To map the polar coordinate to the cylinder surface coordinates, we just need to calculate the arc length
 		// We also scale it by linearScale
 		polarCoordInCylinderCoords = (cylinderRadius * scale * alpha) + halfPolarSize;
@@ -226,7 +218,7 @@ void RenderTable::generateLookupTable(bool tilt) {
 	auto innerLoop = [&](uint & polarCoord, uint & linearCoord, float & halfLinearSize,  float & polarOffset, float & linearOffset) {
 		// To calculate linear coordinate in cylinder coordinates, we can do similar triangles comparison,
 		// comparing the triangle from the center to the screen and from the center to the edge of the cylinder
-		linearCoordInCylinderCoords = halfLinearSize + ((float)linearCoord - halfLinearSize) * cosAlpha;
+		const float linearCoordInCylinderCoords = halfLinearSize + ((float)linearCoord - halfLinearSize) * cosAlpha;
 		linearOffset = linearCoordInCylinderCoords - linearCoord;
 		polarOffset = polarCoordInCylinderCoords - polarCoord;
 		_internalBuffer[indexTL] = FilterPixel(xOffset, yOffset, _highQuality);
@@ -240,16 +232,15 @@ void RenderTable::generateLookupTable(bool tilt) {
 		_internalBuffer[indexBR].flipH();
 	};
 	if (tilt) {
-		uint32 columnIndexTL, columnIndexBL, columnIndexTR, columnIndexBR;
 		cylinderRadius = (_halfWidth + 0.5f) / tan(_tiltOptions.verticalFOV);
 		_tiltOptions.gap = cylinderRadius * atan2((float)(_halfHeight / cylinderRadius), 1.0f) * _tiltOptions.linearScale;
-		for (y = 0; y <= _halfRows; ++y) {
+		for (uint y = 0; y <= _halfRows; ++y) {
 			outerLoop(y, _halfHeight, _tiltOptions.linearScale);
-			columnIndexTL = y * _numColumns;
-			columnIndexBL = (_numRows - (y + 1)) * _numColumns;
-			columnIndexTR = columnIndexTL + (_numColumns - 1);
-			columnIndexBR = columnIndexBL + (_numColumns - 1);
-			for (x = 0; x <= _halfColumns; ++x) {
+			const uint32 columnIndexTL = y * _numColumns;
+			const uint32 columnIndexBL = (_numRows - (y + 1)) * _numColumns;
+			const uint32 columnIndexTR = columnIndexTL + (_numColumns - 1);
+			const uint32 columnIndexBR = columnIndexBL + (_numColumns - 1);
+			for (uint x = 0; x <= _halfColumns; ++x) {
 				indexTL = columnIndexTL + x;
 				indexBL = columnIndexBL + x;
 				indexTR = columnIndexTR - x;
@@ -258,15 +249,14 @@ void RenderTable::generateLookupTable(bool tilt) {
 			}
 		}
 	} else {
-		uint32 rowIndexT, rowIndexB, columnIndexL, columnIndexR;
 		cylinderRadius = (_halfHeight + 0.5f) / tan(_panoramaOptions.verticalFOV);
-		for (x = 0; x <= _halfColumns; ++x) {
-			columnIndexL = x;
-			columnIndexR = (_numColumns - 1) - x;
-			rowIndexT = 0;
-			rowIndexB = _numColumns * (_numRows - 1);
+		for (uint x = 0; x <= _halfColumns; ++x) {
+			const uint32 columnIndexL = x;
+			const uint32 columnIndexR = (_numColumns - 1) - x;
+			uint32 rowIndexT = 0;
+			uint32 rowIndexB = _numColumns * (_numRows - 1);
 			outerLoop(x, _halfWidth, _panoramaOptions.linearScale);
-			for (y = 0; y <= _halfRows; ++y) {
+			for (uint y = 0; y <= _halfRows; ++y) {
 				indexTL = rowIndexT + columnIndexL;
 				indexBL = rowIndexB + columnIndexL;
 				indexTR = rowIndexT + columnIndexR;
diff --git a/engines/zvision/graphics/render_table.h b/engines/zvision/graphics/render_table.h
index 10048dfb052..fb31ebc1bf9 100644
--- a/engines/zvision/graphics/render_table.h
+++ b/engines/zvision/graphics/render_table.h
@@ -97,7 +97,7 @@ private:
 		g = color & 0x03e0;
 		b = color & 0x7c00;
 	}
-	inline uint16 mergeColor(uint32 &r, uint32 &g, uint32 &b) const {
+	inline uint16 mergeColor(const uint32 &r, const uint32 &g, const uint32 &b) const {
 		// NB Red uses the lowest bits in RGB555 and so doesn't need its fractional bits masked away after averaging
 		return r | (g & 0x03e0) | (b & 0x7c00);
 	}


Commit: 8e3434513fa34c4621c581d4386f30751d1e2691
    https://github.com/scummvm/scummvm/commit/8e3434513fa34c4621c581d4386f30751d1e2691
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:02+02:00

Commit Message:
ZVISION: Code formatting compliance.

Changed paths:
    engines/zvision/scripting/actions.h


diff --git a/engines/zvision/scripting/actions.h b/engines/zvision/scripting/actions.h
index c34e17f778d..137d89732d6 100644
--- a/engines/zvision/scripting/actions.h
+++ b/engines/zvision/scripting/actions.h
@@ -241,13 +241,10 @@ public:
 private:
 	int32 _pos; // Sound source position; NB in panoramas (all original game scripts), this is specified as the X background coordinate; otherwise it is specified in azimuth degrees.
 	uint8  _mag; // Magnitude of effect (not used by original game scripts); 255 for fully directional sound, 0 for fully ambient
-	bool _resetMusicNode; // If true (default, original game scripts have no concept of this), associated music slot value is reset to a value of 2 upon creation of this object;
-/*
-	* this seems necessary to ensure all original game pan-track effects load correctly, though it is still unclear exactly what the original intent of these values was.
-	* So far, best guess for music slotkey values is: 0 = has never been loaded, 1 = loaded and actively playing now, 2 = has loaded & played & then subsequently been killed.
-	* Since there is literally nothing in the game scripts that sets some of these values to 2, and certain pan_tracks require it to be 2 for the puzzle that creates them to trigger,
-	* the original game engine code must have set these values to 2 manually somehow upon conditions being met to allow a pan_track to be created?
-	*/
+	bool _resetMusicNode; // If true (default, original game scripts have no concept of this), associated music slot value is reset to a value of 2 upon creation of this object.
+	// This seems necessary to ensure all original game pan-track effects load correctly, though it is still unclear exactly what the original intent of these values was.
+	// So far, best guess for music slotkey values is: 0 = has never been loaded, 1 = loaded and actively playing now, 2 = has loaded & played & then subsequently been killed.
+	// Since there is literally nothing in the game scripts that sets some of these values to 2, and certain pan_tracks require it to be 2 for the puzzle that creates them to trigger, the original game engine code must have set these values to 2 manually somehow upon conditions being met to allow a pan_track to be created?
 	bool _staticScreen; // Used by auxiliary scripts to apply directionality to audio in static screens; not used in original game scripts.
 	bool _resetMixerOnDelete; // Unnecessary and should be set false for original scripts; useful in some cases in extra scripts to avoid brief volume spikes on location changes
 	uint32 _musicSlot;


Commit: b3654574f4d3f3857ba67ad8ee05e8449827b85c
    https://github.com/scummvm/scummvm/commit/b3654574f4d3f3857ba67ad8ee05e8449827b85c
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:02+02:00

Commit Message:
ZVISION: Simplify ~SubtitleManager()

Changed paths:
    engines/zvision/text/subtitle_manager.cpp


diff --git a/engines/zvision/text/subtitle_manager.cpp b/engines/zvision/text/subtitle_manager.cpp
index a15ed0a47ac..9a4990b48e0 100644
--- a/engines/zvision/text/subtitle_manager.cpp
+++ b/engines/zvision/text/subtitle_manager.cpp
@@ -43,11 +43,8 @@ SubtitleManager::SubtitleManager(ZVision *engine, const ScreenLayout layout, con
 
 SubtitleManager::~SubtitleManager() {
 	// Delete all subtitles referenced in subslist
-	for (SubtitleMap::iterator it = _subsList.begin(); it != _subsList.end(); it++) {
-		delete it->_value;
-		_subsList.erase(it);
-		_subsFocus.clear();
-	}
+	for (auto &it : _subsList)
+		delete it._value;
 }
 
 void SubtitleManager::process(int32 deltatime) {


Commit: d0bf337d734230befa42a5e04a43df916b48dc91
    https://github.com/scummvm/scummvm/commit/d0bf337d734230befa42a5e04a43df916b48dc91
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:03+02:00

Commit Message:
ZVISION: Return by reference for getMenuArea(), getWorkingArea(), getTextOffset()

Changed paths:
    engines/zvision/graphics/render_manager.h
    engines/zvision/text/subtitle_manager.h


diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index 593ef170999..a970dc8b671 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -171,10 +171,10 @@ public:
 
 	Graphics::ManagedSurface &getVidSurface(Common::Rect dstRect);  //dstRect is defined relative to working area origin
 
-	const Common::Rect getMenuArea() {
+	const Common::Rect &getMenuArea() const {
 		return _menuArea;
 	}
-	const Common::Rect getWorkingArea() {
+	const Common::Rect &getWorkingArea() const {
 		return _workingArea;
 	}
 
diff --git a/engines/zvision/text/subtitle_manager.h b/engines/zvision/text/subtitle_manager.h
index 579665f57d1..edae7328403 100644
--- a/engines/zvision/text/subtitle_manager.h
+++ b/engines/zvision/text/subtitle_manager.h
@@ -104,7 +104,7 @@ public:
 	// Update counter value of referenced subtitle id & set current line to display, if any.
 	void update(int32 count, uint16 subid);  // Count is milliseconds for sound & music; frames for video playback.
 
-	Common::Point getTextOffset() {
+	const Common::Point &getTextOffset() const {
 		return _textOffset;
 	}
 


Commit: 26230b3147a2e55326d6755d06c7e4687dacc34a
    https://github.com/scummvm/scummvm/commit/26230b3147a2e55326d6755d06c7e4687dacc34a
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:03+02:00

Commit Message:
ZVISION: Overload blitSurfaceToSurface() methods to tidy up ugly function calls.

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index 51fcf1af201..f9e0592e1eb 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -577,11 +577,10 @@ void RenderManager::blitSurfaceToSurface(const Graphics::Surface &src, Common::R
 }
 
 void RenderManager::blitSurfaceToBkg(const Graphics::Surface &src, int x, int y, int32 colorkey) {
-	Common::Rect empt;
 	if (colorkey >= 0)
-		blitSurfaceToSurface(src, empt, _currentBackgroundImage, x, y, colorkey);
+		blitSurfaceToSurface(src, _currentBackgroundImage, x, y, colorkey);
 	else
-		blitSurfaceToSurface(src, empt, _currentBackgroundImage, x, y);
+		blitSurfaceToSurface(src, _currentBackgroundImage, x, y);
 	Common::Rect dirty(src.w, src.h);
 	dirty.translate(x, y);
 	if (_backgroundDirtyRect.isEmpty())
@@ -604,8 +603,7 @@ void RenderManager::blitSurfaceToBkgScaled(const Graphics::Surface &src, const C
 }
 
 void RenderManager::blitSurfaceToMenu(const Graphics::Surface &src, int16 x, int16 y, int32 colorkey) {
-	Common::Rect empt;
-	blitSurfaceToSurface(src, empt, _menuSurface, x, y, colorkey);
+	blitSurfaceToSurface(src, _menuSurface, x, y, colorkey);
 	Common::Rect dirty(src.w, src.h);
 	dirty.moveTo(x, y);
 	if (_menuSurfaceDirtyRect.isEmpty())
@@ -636,8 +634,7 @@ void RenderManager::clearMenuSurface(bool force, int32 colorkey) {
 }
 
 void RenderManager::blitSurfaceToText(const Graphics::Surface &src, int16 x, int16 y, int32 colorkey) {
-	Common::Rect empt;
-	blitSurfaceToSurface(src, empt, _textSurface, x, y, colorkey);
+	blitSurfaceToSurface(src, _textSurface, x, y, colorkey);
 	Common::Rect dirty(src.w, src.h);
 	dirty.moveTo(x, y);
 	if (_textSurfaceDirtyRect.isEmpty())
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index a970dc8b671..b588367360a 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -260,7 +260,7 @@ public:
 	 * Blit from one surface to another surface
 	 *
 	 * @param src       Source surface
-	 * @param srcRect  Rectangle defining area of source surface to blit; if this rectangle is empty, entire source surface is blitted
+	 * @param srcRect  Rectangle defining area of source surface to blit; if this rectangle is empty or not supplied, entire source surface is blitted
 	 * @param dst       Destination surface
 	 * @param x         Destination surface x coordinate
 	 * @param y         Destination surface y coordinate
@@ -268,6 +268,8 @@ public:
 
 	void blitSurfaceToSurface(const Graphics::Surface &src, Common::Rect srcRect, Graphics::Surface &dst, int _x, int _y);
 	void blitSurfaceToSurface(const Graphics::Surface &src, Common::Rect srcRect, Graphics::Surface &dst, int _x, int _y, uint32 colorkey);
+	void blitSurfaceToSurface(const Graphics::Surface &src, Graphics::Surface &dst, int _x, int _y) {blitSurfaceToSurface(src, Common::Rect(src.w, src.h), dst, _x, _y);}
+	void blitSurfaceToSurface(const Graphics::Surface &src, Graphics::Surface &dst, int _x, int _y, uint32 colorkey) {blitSurfaceToSurface(src, Common::Rect(src.w, src.h), dst, _x, _y, colorkey);}
 
 	// Blitting surface-to-background methods
 	void blitSurfaceToBkg(const Graphics::Surface &src, int x, int y, int32 colorkey = -1);


Commit: 19cc9c7f7f7d674cf9d4a4d91bdfa1045547176d
    https://github.com/scummvm/scummvm/commit/19cc9c7f7f7d674cf9d4a4d91bdfa1045547176d
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:03+02:00

Commit Message:
ZVISION: Comment out disused function.
Leave in codebase in case the effect that uses it is properly reimplemented later.

Changed paths:
    engines/zvision/graphics/render_manager.cpp
    engines/zvision/graphics/render_manager.h


diff --git a/engines/zvision/graphics/render_manager.cpp b/engines/zvision/graphics/render_manager.cpp
index f9e0592e1eb..c436892b905 100644
--- a/engines/zvision/graphics/render_manager.cpp
+++ b/engines/zvision/graphics/render_manager.cpp
@@ -957,12 +957,13 @@ void RenderManager::markDirty() {
 	_backgroundDirtyRect = Common::Rect(_backgroundWidth, _backgroundHeight);
 }
 
-// *
+/*
+//Only needed by ActionDissolve, which is disabled unless and until a better dissolve effect can be implemented.  Gameplay is not significantly effected.
 void RenderManager::bkgFill(uint8 r, uint8 g, uint8 b) {
 	_currentBackgroundImage.fillRect(Common::Rect(_currentBackgroundImage.w, _currentBackgroundImage.h), _currentBackgroundImage.format.RGBToColor(r, g, b));
 	markDirty();
 }
-// */
+*/
 
 
 void RenderManager::updateRotation() {
diff --git a/engines/zvision/graphics/render_manager.h b/engines/zvision/graphics/render_manager.h
index b588367360a..175f580888a 100644
--- a/engines/zvision/graphics/render_manager.h
+++ b/engines/zvision/graphics/render_manager.h
@@ -360,10 +360,10 @@ public:
 	// Mark whole background surface as dirty
 	void markDirty();
 
-//*/
+/*
 	// Fill background surface by color
 	void bkgFill(uint8 r, uint8 g, uint8 b);
-//*/
+*/
 
 	void checkBorders();
 	void rotateTo(int16 to, int16 time);


Commit: 7d5b2522431d83602f35c423ad4f84b63728a3c5
    https://github.com/scummvm/scummvm/commit/7d5b2522431d83602f35c423ad4f84b63728a3c5
Author: Thomas N McEwan (46427621+tnm23 at users.noreply.github.com)
Date: 2025-06-19T23:54:03+02:00

Commit Message:
ZVISION: Respect confirm_exit option.
Enable quit dialog during videos.
Enable Ctrl-Q event handling functionality during askQuestion() & delayedMessage() function calls.
Rename ScriptManager::update() to ScriptManager.process() for consistency.

Changed paths:
    engines/zvision/core/events.cpp
    engines/zvision/scripting/actions.cpp
    engines/zvision/scripting/menu.cpp
    engines/zvision/scripting/script_manager.cpp
    engines/zvision/scripting/script_manager.h
    engines/zvision/text/subtitle_manager.cpp
    engines/zvision/text/subtitle_manager.h
    engines/zvision/video/video.cpp
    engines/zvision/zvision.cpp
    engines/zvision/zvision.h


diff --git a/engines/zvision/core/events.cpp b/engines/zvision/core/events.cpp
index 0573e68c6be..2a4254d0c46 100644
--- a/engines/zvision/core/events.cpp
+++ b/engines/zvision/core/events.cpp
@@ -20,6 +20,7 @@
  */
 
 #include "audio/mixer.h"
+#include "common/config-manager.h"
 #include "common/events.h"
 #include "common/scummsys.h"
 #include "common/system.h"
@@ -230,8 +231,12 @@ void ZVision::processEvents() {
 				break;
 
 			case kZVisionActionQuit:
-				if (_menu->getEnable(kMainMenuExit))
-					ifQuit();
+				if (_menu->getEnable(kMainMenuExit)) {
+					if (ConfMan.hasKey("confirm_exit") && ConfMan.getBool("confirm_exit"))
+						quit(true);
+					else
+						quit(false);
+				}
 				break;
 
 			case kZVisionActionShowFPS: {
@@ -471,12 +476,17 @@ uint8 ZVision::getZvisionKey(Common::KeyCode scummKeyCode) {
 	return 0;
 }
 
-bool ZVision::ifQuit() {
-	if (_subtitleManager->askQuestion(_stringManager->getTextLine(StringManager::ZVISION_STR_EXITPROMT))) {
-		quitGame();
-		return true;
-	}
-	return false;
+bool ZVision::quit(bool askFirst, bool streaming) {
+	debugC(1, kDebugEvent, "ZVision::quit()");
+	if (askFirst)
+		if (!_subtitleManager->askQuestion(_stringManager->getTextLine(StringManager::ZVISION_STR_EXITPROMT), streaming, true)) {
+			debugC(1, kDebugEvent, "~ZVision::quit()");
+			return false;
+		}
+	//quitGame();
+	_breakMainLoop = true;
+	debugC(1, kDebugEvent, "~ZVision::quit()");
+	return true;
 }
 
 } // End of namespace ZVision
diff --git a/engines/zvision/scripting/actions.cpp b/engines/zvision/scripting/actions.cpp
index 1461c011c14..7d646019d4c 100644
--- a/engines/zvision/scripting/actions.cpp
+++ b/engines/zvision/scripting/actions.cpp
@@ -835,8 +835,7 @@ bool ActionPlayPreloadAnimation::execute() {
 //////////////////////////////////////////////////////////////////////////////
 
 bool ActionQuit::execute() {
-	_engine->quitGame();
-
+	_engine->quit(false);
 	return true;
 }
 
diff --git a/engines/zvision/scripting/menu.cpp b/engines/zvision/scripting/menu.cpp
index 2349506ab01..6967b61dcb8 100644
--- a/engines/zvision/scripting/menu.cpp
+++ b/engines/zvision/scripting/menu.cpp
@@ -19,6 +19,7 @@
  *
  */
 
+#include "common/config-manager.h"
 #include "zvision/detection.h"
 #include "zvision/graphics/render_manager.h"
 #include "zvision/scripting/menu.h"
@@ -97,7 +98,7 @@ void MenuManager::onMouseUp(const Common::Point &pos) {
 				_redraw = true;
 				break;
 			case kMainMenuExit:
-				_engine->ifQuit();
+				_engine->quit(true);
 				break;
 			default:
 				break;
diff --git a/engines/zvision/scripting/script_manager.cpp b/engines/zvision/scripting/script_manager.cpp
index 15a2fd18543..62a41646a59 100644
--- a/engines/zvision/scripting/script_manager.cpp
+++ b/engines/zvision/scripting/script_manager.cpp
@@ -97,7 +97,7 @@ bool ScriptManager::changingLocation() const {
 	return _currentLocation != _nextLocation;
 }
 
-void ScriptManager::update(uint deltaTimeMillis) {
+void ScriptManager::process(uint deltaTimeMillis) {
 	if (changingLocation()) {
 		// The location is changing. The script that did that may have
 		// triggered other scripts, so give them all one extra cycle to
diff --git a/engines/zvision/scripting/script_manager.h b/engines/zvision/scripting/script_manager.h
index 33cca6d7ae6..5d1090dcac0 100644
--- a/engines/zvision/scripting/script_manager.h
+++ b/engines/zvision/scripting/script_manager.h
@@ -198,7 +198,7 @@ private:
 
 public:
 	void initialize(bool restarted = false);
-	void update(uint deltaTimeMillis);
+	void process(uint deltaTimeMillis);
 	void queuePuzzles(uint32 key);
 
 	int getStateValue(uint32 key);
diff --git a/engines/zvision/text/subtitle_manager.cpp b/engines/zvision/text/subtitle_manager.cpp
index 9a4990b48e0..1616ff764ce 100644
--- a/engines/zvision/text/subtitle_manager.cpp
+++ b/engines/zvision/text/subtitle_manager.cpp
@@ -19,6 +19,7 @@
  *
  */
 
+#include "common/config-manager.h"
 #include "common/system.h"
 #include "zvision/detection.h"
 #include "zvision/file/search_manager.h"
@@ -78,6 +79,7 @@ void SubtitleManager::process(int32 deltatime) {
 			Subtitle *sub = _subsList[curSub];
 			if (sub->_lineId >= 0) {
 				Graphics::Surface textSurface;
+				//TODO - make this surface a persistent member of the manager; only call create() when currently displayed subtitle is changed.
 				textSurface.create(sub->_textArea.width(), sub->_textArea.height(), _engine->_resourcePixelFormat);
 				textSurface.fillRect(Common::Rect(sub->_textArea.width(), sub->_textArea.height()), -1); // TODO Unnecessary operation?  Check later.
 				_engine->getTextRenderer()->drawTextWithWordWrapping(sub->_lines[sub->_lineId].subStr, textSurface, _engine->isWidescreen());
@@ -144,56 +146,75 @@ void SubtitleManager::timedMessage(const Common::String &str, uint16 milsecs) {
 	destroy(msgid, milsecs);
 }
 
-bool SubtitleManager::askQuestion(const Common::String &str) {
+bool SubtitleManager::askQuestion(const Common::String &str, bool streaming, bool safeDefault) {
 	uint16 msgid = create(str);
 	debugC(1, kDebugSubtitle, "initiating user question: %s to subtitle id %d", str.c_str(), msgid);
 	update(0, msgid);
 	process(0);
-	_renderManager->renderSceneToScreen(true);
+	if(streaming)
+		_renderManager->renderSceneToScreen(true,true,true);
+	else
+		_renderManager->renderSceneToScreen(true);
 	_engine->stopClock();
 	int result = 0;
 	while (result == 0) {
 		Common::Event evnt;
 		while (_engine->getEventManager()->pollEvent(evnt)) {
-			if (evnt.type == Common::EVENT_KEYDOWN) {
-				// English: yes/no
-				// German: ja/nein
-				// Spanish: si/no
-				// French Nemesis: F4/any other key  _engine(engine),
-				// French ZGI: oui/non
-				// TODO: Handle this using the keymapper
-				switch (evnt.kbd.keycode) {
-				case Common::KEYCODE_y:
-					if (_engine->getLanguage() == Common::EN_ANY)
-						result = 2;
-					break;
-				case Common::KEYCODE_j:
-					if (_engine->getLanguage() == Common::DE_DEU)
-						result = 2;
-					break;
-				case Common::KEYCODE_s:
-					if (_engine->getLanguage() == Common::ES_ESP)
-						result = 2;
-					break;
-				case Common::KEYCODE_o:
-					if (_engine->getLanguage() == Common::FR_FRA && _engine->getGameId() == GID_GRANDINQUISITOR)
-						result = 2;
+			switch (evnt.type) {
+				case Common::EVENT_CUSTOM_ENGINE_ACTION_START:
+					if ((ZVisionAction)evnt.customType != kZVisionActionQuit)
+						break;
+					// fall through
+				case Common::EVENT_QUIT:
+					debugC(1, kDebugEvent, "Attempting to quit within quit dialog!");
+					_engine->quit(false);
+					return safeDefault;
 					break;
-				case Common::KEYCODE_F4:
-					if (_engine->getLanguage() == Common::FR_FRA && _engine->getGameId() == GID_NEMESIS)
-						result = 2;
-					break;
-				case Common::KEYCODE_n:
-					result = 1;
+				case Common::EVENT_KEYDOWN:
+					// English: yes/no
+					// German: ja/nein
+					// Spanish: si/no
+					// French Nemesis: F4/any other key  _engine(engine),
+					// French ZGI: oui/non
+					// TODO: Handle this using the keymapper
+					switch (evnt.kbd.keycode) {
+					case Common::KEYCODE_y:
+						if (_engine->getLanguage() == Common::EN_ANY)
+							result = 2;
+						break;
+					case Common::KEYCODE_j:
+						if (_engine->getLanguage() == Common::DE_DEU)
+							result = 2;
+						break;
+					case Common::KEYCODE_s:
+						if (_engine->getLanguage() == Common::ES_ESP)
+							result = 2;
+						break;
+					case Common::KEYCODE_o:
+						if (_engine->getLanguage() == Common::FR_FRA && _engine->getGameId() == GID_GRANDINQUISITOR)
+							result = 2;
+						break;
+					case Common::KEYCODE_F4:
+						if (_engine->getLanguage() == Common::FR_FRA && _engine->getGameId() == GID_NEMESIS)
+							result = 2;
+						break;
+					case Common::KEYCODE_n:
+						result = 1;
+						break;
+					default:
+						if (_engine->getLanguage() == Common::FR_FRA && _engine->getGameId() == GID_NEMESIS)
+							result = 1;
+						break;
+					}
 					break;
 				default:
-					if (_engine->getLanguage() == Common::FR_FRA && _engine->getGameId() == GID_NEMESIS)
-						result = 1;
 					break;
-				}
 			}
 		}
-		_renderManager->renderSceneToScreen(true);
+		if(streaming)
+			_renderManager->renderSceneToScreen(true,true,false);
+		else
+			_renderManager->renderSceneToScreen(true);
 		if (_doubleFPS)
 			_system->delayMillis(33);
 		else
@@ -216,12 +237,34 @@ void SubtitleManager::delayedMessage(const Common::String &str, uint16 milsecs)
 	while (_system->getMillis() < stopTime) {
 		Common::Event evnt;
 		while (_engine->getEventManager()->pollEvent(evnt)) {
-			if (evnt.type == Common::EVENT_KEYDOWN &&
-			        (evnt.kbd.keycode == Common::KEYCODE_SPACE ||
-			         evnt.kbd.keycode == Common::KEYCODE_RETURN ||
-			         evnt.kbd.keycode == Common::KEYCODE_ESCAPE))
+			switch (evnt.type) {
+			case Common::EVENT_KEYDOWN:
+				switch (evnt.kbd.keycode) {
+				case Common::KEYCODE_SPACE:
+				case Common::KEYCODE_RETURN:
+				case Common::KEYCODE_ESCAPE:
+					goto skip_delayed_message;
+					break;
+				default:
+					break;
+				}
+				break;
+			case Common::EVENT_CUSTOM_ENGINE_ACTION_START:
+				if ((ZVisionAction)evnt.customType != kZVisionActionQuit)
+					break;
+				// fall through
+			case Common::EVENT_QUIT:
+				if (ConfMan.hasKey("confirm_exit") && ConfMan.getBool("confirm_exit"))
+					_engine->quit(true);
+				else
+					_engine->quit(false);
 				break;
+			default:
+				break;
+			}
 		}
+		skip_delayed_message:
+		
 		_renderManager->renderSceneToScreen(true);
 		if (_doubleFPS)
 			_system->delayMillis(17);
diff --git a/engines/zvision/text/subtitle_manager.h b/engines/zvision/text/subtitle_manager.h
index edae7328403..216ec256a11 100644
--- a/engines/zvision/text/subtitle_manager.h
+++ b/engines/zvision/text/subtitle_manager.h
@@ -117,7 +117,7 @@ public:
 	void destroy(uint16 id);
 	void destroy(uint16 id, int16 delay);
 
-	bool askQuestion(const Common::String &str);
+	bool askQuestion(const Common::String &str, bool streaming = false, bool safeDefault = false);
 	void delayedMessage(const Common::String &str, uint16 milsecs);
 	void timedMessage(const Common::String &str, uint16 milsecs);
 	void showDebugMsg(const Common::String &msg, int16 delay = 3000);
diff --git a/engines/zvision/video/video.cpp b/engines/zvision/video/video.cpp
index 7ccd69418b8..e5c2ffba9c5 100644
--- a/engines/zvision/video/video.cpp
+++ b/engines/zvision/video/video.cpp
@@ -123,7 +123,7 @@ void ZVision::playVideo(Video::VideoDecoder &vid, Common::Rect dstRect, bool ski
 
 	_cutscenesKeymap->setEnabled(true);
 	_gameKeymap->setEnabled(false);
-
+	
 	// Only continue while the video is still playing
 	while (!shouldQuit() && !vid.endOfVideo() && vid.isPlaying()) {
 		// Check for engine quit and video stop key presses
@@ -132,7 +132,14 @@ void ZVision::playVideo(Video::VideoDecoder &vid, Common::Rect dstRect, bool ski
 			case Common::EVENT_CUSTOM_ENGINE_ACTION_START:
 				switch ((ZVisionAction)_event.customType) {
 				case kZVisionActionQuit:
-					quitGame();
+					if (ConfMan.hasKey("confirm_exit") && ConfMan.getBool("confirm_exit")) {
+						if (quit(true, true))
+							vid.stop();
+					}
+					else {
+						quit(false);
+						vid.stop();
+					}
 					break;
 				case kZVisionActionSkipCutscene:
 					if (skippable) {
diff --git a/engines/zvision/zvision.cpp b/engines/zvision/zvision.cpp
index 3904ec547cf..f7ab493fad6 100644
--- a/engines/zvision/zvision.cpp
+++ b/engines/zvision/zvision.cpp
@@ -344,7 +344,7 @@ Common::Error ZVision::run() {
 	}
 
 	// Main loop
-	while (!shouldQuit()) {
+	while (!shouldQuit() && !_breakMainLoop) {
 		debugC(1, kDebugLoop, "\nInitiating new game cycle");
 		debugC(5, kDebugLoop, "Timers");
 		// Timers
@@ -359,7 +359,7 @@ Common::Error ZVision::run() {
 		debugC(5, kDebugLoop, "Rotation");
 		_renderManager->updateRotation();
 		debugC(5, kDebugLoop, "Scripts");
-		_scriptManager->update(deltaTime);
+		_scriptManager->process(deltaTime);
 		debugC(5, kDebugLoop, "Menu");
 		_menu->process(deltaTime);
 		debugC(5, kDebugLoop, "Subtitles");
diff --git a/engines/zvision/zvision.h b/engines/zvision/zvision.h
index 786ea8bb3a5..b212ea169a8 100644
--- a/engines/zvision/zvision.h
+++ b/engines/zvision/zvision.h
@@ -169,6 +169,7 @@ private:
 	bool _doubleFPS;
 	bool _widescreen;
 	bool _videoIsPlaying;
+	bool _breakMainLoop = false;
 
 	uint8 _cheatBuffer[KEYBUF_SIZE];
 
@@ -268,8 +269,8 @@ public:
 	void loadSettings();
 	void saveSettings();
 
-	bool ifQuit();
-
+	bool quit(bool askFirst = true, bool streaming = false);
+	
 	// Engine features
 	bool hasFeature(EngineFeature f) const override;
 	bool canLoadGameStateCurrently(Common::U32String *msg = nullptr) override;




More information about the Scummvm-git-logs mailing list