[Scummvm-git-logs] scummvm master -> 11669e692e8aab983e44bd1984242e5f836c4ef0

sev- noreply at scummvm.org
Sun Nov 15 14:09:37 UTC 2026


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

Summary:
00eaa1a088 ENGINES: COMFY: Add stub
8811510fe8 COMFY: Add stub files and first detection entry
11b5f2a746 COMFY: Implement MIDIPLYR.DLL driver
39a868f0e4 COMFY: Add PIT handling
6785c992ab COMFY: Continue adding PIT stuff
711de8da64 COMFY: Add all known detection entries
2ab5331e5d COMFY: Add internal multilang handling and part of the INI code
b360a20c72 COMFY: Insert some GFX and Palette funcs
dc0d9d1752 COMFY: Start inserting some game timers and MIDI stuff
870ef16d6d COMFY: Port input/keymapper/LPT handling and ImGui interface
5aaa11f69b COMFY: Show first GFX asset on screen
ebb4bf398c COMFY: Implement bulk of the scripting engine
b2ee0458b0 COMFY: Render first scene
093acf1230 COMFY: Implement lang choice
881ed72395 COMFY: Implement sound
462bc777a3 COMFY: Connect ImGui keyboard to engine
a8542b6e56 COMFY: Add ANM system
e776afd164 COMFY: Fix INTRO movies detection and game names
c248786db8 COMFY: Make ImGui keyboard non resizeable
16cebcb434 COMFY: Refactoring
e147d24469 COMFY: Refactoring & fixes
4fe3275074 COMFY: Add COMFYBOARD driver handling
f374a7b855 COMFY: Clean up
59c0d13977 COMFY: More refactoring and clean up
7e49c13268 COMFY: Fix things along the code after audit
1b426a971e COMFY: Clear ImGui callbacks on shutdown
a8b587f214 COMFY: Keep ImGui callbacks for the engine lifetime
5188a94f02 COMFY: Attempt to fix ImGui keyboard exit
9331aa6f53 COMFY: Casts clean up
789f27bd10 COMFY: Add numeric engine version to detection entries
4ae2db1837 COMFY: Fix engine version for one of the entries
e5539f1e84 COMFY: Script and engine version fixes
76328a715b COMFY: COLORS: Fix italian sound decoding
4d98e7e3d9 COMFY: PANTHER: Lots of fixes to make the game bootable
a8764da4bd COMFY: PANTHER: Fix sound
03a2e54953 COMFY: PANTHER: Fix crashes
3a979923cc COMFY: PANTHER: Fix gfx glitches
9346038149 COMFY: Add option to skip intro
4c9415a198 COMFY: Fix gfx regression in older games
e322abce3c COMFY: Remove unused file
3750a8962b COMFY: Fix blocked animations and missing sounds
7639c8321e COMFY: Add actor debugger and refactor ImGui code
5a496b68c7 COMFY: Refactor raw Actor blob to proper struct
b90a829e05 COMFY: Fix dirty rects algorithm for later versions
73cc3da981 COMFY: Implement original memory allocation and asset reading routines
1c12b6c511 COMFY: Make ImGui virtual keyboard toggleable in the options
a8cfb38daa COMFY: Fix exit handling
51d8a8dea7 COMFY: Great clean-up pass
d0f86d3298 COMFY: Another clean-up pass
cc283bb746 COMFY: Yet another clean-up pass
1306cf6243 COMFY: Change how debug window is brought up
ef6e8ad62d COMFY: Rewrite sound engine to be more accurate
02b5495800 COMFY: Add detection for Christmas in ComfyLand
c7d034fe98 COMFY: Clean up detection code
65fa374a2b COMFY: Remove useless _scriptFeatures member
3f519f1373 COMFY: Remove console.cpp/.h
fcfdbbc002 COMFY: Add credits
204f371c5b COMFY: Move midiplyr driver to main folder
d9b78e99eb COMFY: Remove cstdarg dev leftover from script.cpp and rename to script_utils.cpp
4a26af3017 COMFY: Add "hires" to deps in configure.engine
3d646495a6 COMFY: DETECTION: Remove _directoryGlobs and _maxScanDepth assignments
037876745e COMFY: Add ComfyRect equals() method to avoid huge if clauses
5e313745e9 COMFY: Clean up script_vm.cpp further
8d15a1b34c COMFY: Formatting clean-up pass
6701ea6520 COMFY: DETECTION: Avoid showing ImGui options for non ImGui builds
f9488ba346 COMFY: Leftover clean-up edits to be committed
2b2b983666 COMFY: Show a reminder to configure the keymapper at game boot-up
647ad22e36 COMFY: Fix warning
d4db1ed533 COMFY: Forgot to rename a couple of globals
a2c194156f COMFY: KEYMAPPER: Set a nicer default mapping configuration
11669e692e COMFY: Fix opcode O_ACTOR_SET_FRAME_AND_STOP


Commit: 00eaa1a0887abc8d81a4f6ae5fb6f52370e95f7c
    https://github.com/scummvm/scummvm/commit/00eaa1a0887abc8d81a4f6ae5fb6f52370e95f7c
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
ENGINES: COMFY: Add stub

Changed paths:
  A engines/comfy/POTFILES
  A engines/comfy/comfy.cpp
  A engines/comfy/comfy.h
  A engines/comfy/configure.engine
  A engines/comfy/console.cpp
  A engines/comfy/console.h
  A engines/comfy/credits.pl
  A engines/comfy/detection.cpp
  A engines/comfy/detection.h
  A engines/comfy/detection_tables.h
  A engines/comfy/metaengine.cpp
  A engines/comfy/metaengine.h
  A engines/comfy/module.mk


diff --git a/engines/comfy/POTFILES b/engines/comfy/POTFILES
new file mode 100644
index 00000000000..02206a5a535
--- /dev/null
+++ b/engines/comfy/POTFILES
@@ -0,0 +1 @@
+engines/comfy/metaengine.cpp
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
new file mode 100644
index 00000000000..24fbf9ac534
--- /dev/null
+++ b/engines/comfy/comfy.cpp
@@ -0,0 +1,109 @@
+/* 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 "comfy/comfy.h"
+#include "graphics/framelimiter.h"
+#include "comfy/detection.h"
+#include "comfy/console.h"
+#include "common/scummsys.h"
+#include "common/config-manager.h"
+#include "common/debug-channels.h"
+#include "common/events.h"
+#include "common/system.h"
+#include "engines/util.h"
+#include "graphics/paletteman.h"
+
+namespace Comfy {
+
+ComfyEngine *g_engine;
+
+ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Engine(syst),
+	_gameDescription(gameDesc), _randomSource("Comfy") {
+	g_engine = this;
+}
+
+ComfyEngine::~ComfyEngine() {
+	delete _screen;
+}
+
+uint32 ComfyEngine::getFeatures() const {
+	return _gameDescription->flags;
+}
+
+Common::String ComfyEngine::getGameId() const {
+	return _gameDescription->gameId;
+}
+
+Common::Error ComfyEngine::run() {
+	// Initialize 320x200 paletted graphics mode
+	initGraphics(320, 200);
+	_screen = new Graphics::Screen();
+
+	// Set the engine's debugger console
+	setDebugger(new Console());
+
+	// If a savegame was selected from the launcher, load it
+	int saveSlot = ConfMan.getInt("save_slot");
+	if (saveSlot != -1)
+		(void)loadGameState(saveSlot);
+
+	// Draw a series of boxes on screen as a sample
+	for (int i = 0; i < 100; ++i)
+		_screen->frameRect(Common::Rect(i, i, 320 - i, 200 - i), i);
+	_screen->update();
+
+	// Simple event handling loop
+	byte pal[256 * 3] = { 0 };
+	Common::Event e;
+	int offset = 0;
+
+	Graphics::FrameLimiter limiter(g_system, 60);
+	while (!shouldQuit()) {
+		while (g_system->getEventManager()->pollEvent(e)) {
+		}
+
+		// Cycle through a simple palette
+		++offset;
+		for (int i = 0; i < 256; ++i)
+			pal[i * 3 + 1] = (i + offset) % 256;
+		g_system->getPaletteManager()->setPalette(pal, 0, 256);
+		// Delay for a bit. All events loops should have a delay
+		// to prevent the system being unduly loaded
+		limiter.delayBeforeSwap();
+		_screen->update();
+		limiter.startFrame();
+	}
+
+	return Common::kNoError;
+}
+
+Common::Error ComfyEngine::syncGame(Common::Serializer &s) {
+	// The Serializer has methods isLoading() and isSaving()
+	// if you need to specific steps; for example setting
+	// an array size after reading it's length, whereas
+	// for saving it would write the existing array's length
+	int dummy = 0;
+	s.syncAsUint32LE(dummy);
+
+	return Common::kNoError;
+}
+
+} // End of namespace Comfy
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
new file mode 100644
index 00000000000..6c4efca8243
--- /dev/null
+++ b/engines/comfy/comfy.h
@@ -0,0 +1,105 @@
+/* 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 COMFY_H
+#define COMFY_H
+
+#include "common/scummsys.h"
+#include "common/system.h"
+#include "common/error.h"
+#include "common/fs.h"
+#include "common/hash-str.h"
+#include "common/random.h"
+#include "common/serializer.h"
+#include "common/util.h"
+#include "engines/engine.h"
+#include "engines/savestate.h"
+#include "graphics/screen.h"
+
+#include "comfy/detection.h"
+
+namespace Comfy {
+
+struct ComfyGameDescription;
+
+class ComfyEngine : public Engine {
+private:
+	const ADGameDescription *_gameDescription;
+	Common::RandomSource _randomSource;
+protected:
+	// Engine APIs
+	Common::Error run() override;
+public:
+	Graphics::Screen *_screen = nullptr;
+public:
+	ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc);
+	~ComfyEngine() override;
+
+	uint32 getFeatures() const;
+
+	/**
+	 * Returns the game Id
+	 */
+	Common::String getGameId() const;
+
+	/**
+	 * Gets a random number
+	 */
+	uint32 getRandomNumber(uint maxNum) {
+		return _randomSource.getRandomNumber(maxNum);
+	}
+
+	bool hasFeature(EngineFeature f) const override {
+		return
+		    (f == kSupportsLoadingDuringRuntime) ||
+		    (f == kSupportsSavingDuringRuntime) ||
+		    (f == kSupportsReturnToLauncher);
+	};
+
+	bool canLoadGameStateCurrently(Common::U32String *msg = nullptr) override {
+		return true;
+	}
+	bool canSaveGameStateCurrently(Common::U32String *msg = nullptr) override {
+		return true;
+	}
+
+	/**
+	 * Uses a serializer to allow implementing savegame
+	 * loading and saving using a single method
+	 */
+	Common::Error syncGame(Common::Serializer &s);
+
+	Common::Error saveGameStream(Common::WriteStream *stream, bool isAutosave = false) override {
+		Common::Serializer s(nullptr, stream);
+		return syncGame(s);
+	}
+	Common::Error loadGameStream(Common::SeekableReadStream *stream) override {
+		Common::Serializer s(stream, nullptr);
+		return syncGame(s);
+	}
+};
+
+extern ComfyEngine *g_engine;
+#define SHOULD_QUIT ::Comfy::g_engine->shouldQuit()
+
+} // End of namespace Comfy
+
+#endif // COMFY_H
diff --git a/engines/comfy/configure.engine b/engines/comfy/configure.engine
new file mode 100644
index 00000000000..2b5c993f0f4
--- /dev/null
+++ b/engines/comfy/configure.engine
@@ -0,0 +1,3 @@
+# This file is included from the main "configure" script
+# add_engine [name] [desc] [build-by-default] [subengines] [base games] [deps] [components]
+add_engine comfy "Comfy" no "" "" "" ""
diff --git a/engines/comfy/console.cpp b/engines/comfy/console.cpp
new file mode 100644
index 00000000000..f9d4075dfee
--- /dev/null
+++ b/engines/comfy/console.cpp
@@ -0,0 +1,38 @@
+/* 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 "comfy/console.h"
+
+namespace Comfy {
+
+Console::Console() : GUI::Debugger() {
+	registerCmd("test",   WRAP_METHOD(Console, Cmd_test));
+}
+
+Console::~Console() {
+}
+
+bool Console::Cmd_test(int argc, const char **argv) {
+	debugPrintf("Test\n");
+	return true;
+}
+
+} // End of namespace Comfy
diff --git a/engines/comfy/console.h b/engines/comfy/console.h
new file mode 100644
index 00000000000..39e0fe5a79e
--- /dev/null
+++ b/engines/comfy/console.h
@@ -0,0 +1,40 @@
+
+/* 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 COMFY_CONSOLE_H
+#define COMFY_CONSOLE_H
+
+#include "gui/debugger.h"
+
+namespace Comfy {
+
+class Console : public GUI::Debugger {
+private:
+	bool Cmd_test(int argc, const char **argv);
+public:
+	Console();
+	~Console() override;
+};
+
+} // End of namespace Comfy
+
+#endif // COMFY_CONSOLE_H
diff --git a/engines/comfy/credits.pl b/engines/comfy/credits.pl
new file mode 100644
index 00000000000..731f5190b80
--- /dev/null
+++ b/engines/comfy/credits.pl
@@ -0,0 +1,3 @@
+begin_section("Comfy");
+	add_person("Name 1", "Handle 1", "");
+end_section();
diff --git a/engines/comfy/detection.cpp b/engines/comfy/detection.cpp
new file mode 100644
index 00000000000..3a5a8f70d33
--- /dev/null
+++ b/engines/comfy/detection.cpp
@@ -0,0 +1,45 @@
+/* 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 "base/plugins.h"
+#include "common/config-manager.h"
+#include "common/file.h"
+#include "common/md5.h"
+#include "common/str-array.h"
+#include "common/translation.h"
+#include "common/util.h"
+#include "comfy/detection.h"
+#include "comfy/detection_tables.h"
+
+const DebugChannelDef ComfyMetaEngineDetection::debugFlagList[] = {
+	{ Comfy::kDebugGraphics, "Graphics", "Graphics debug level" },
+	{ Comfy::kDebugPath, "Path", "Pathfinding debug level" },
+	{ Comfy::kDebugFilePath, "FilePath", "File path debug level" },
+	{ Comfy::kDebugScan, "Scan", "Scan for unrecognised games" },
+	{ Comfy::kDebugScript, "Script", "Enable debug script dump" },
+	DEBUG_CHANNEL_END
+};
+
+ComfyMetaEngineDetection::ComfyMetaEngineDetection() : AdvancedMetaEngineDetection(
+	Comfy::gameDescriptions, Comfy::comfyGames) {
+}
+
+REGISTER_PLUGIN_STATIC(COMFY_DETECTION, PLUGIN_TYPE_ENGINE_DETECTION, ComfyMetaEngineDetection);
diff --git a/engines/comfy/detection.h b/engines/comfy/detection.h
new file mode 100644
index 00000000000..d2e6cbcfc1a
--- /dev/null
+++ b/engines/comfy/detection.h
@@ -0,0 +1,69 @@
+/* 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 COMFY_DETECTION_H
+#define COMFY_DETECTION_H
+
+#include "engines/advancedDetector.h"
+
+namespace Comfy {
+
+enum ComfyDebugChannels {
+	kDebugGraphics = 1,
+	kDebugPath,
+	kDebugScan,
+	kDebugFilePath,
+	kDebugScript,
+};
+
+extern const PlainGameDescriptor comfyGames[];
+
+extern const ADGameDescription gameDescriptions[];
+
+#define GAMEOPTION_ORIGINAL_SAVELOAD GUIO_GAMEOPTIONS1
+
+} // End of namespace Comfy
+
+class ComfyMetaEngineDetection : public AdvancedMetaEngineDetection<ADGameDescription> {
+	static const DebugChannelDef debugFlagList[];
+
+public:
+	ComfyMetaEngineDetection();
+	~ComfyMetaEngineDetection() override {}
+
+	const char *getName() const override {
+		return "comfy";
+	}
+
+	const char *getEngineName() const override {
+		return "Comfy";
+	}
+
+	const char *getOriginalCopyright() const override {
+		return "Comfy (C)";
+	}
+
+	const DebugChannelDef *getDebugChannels() const override {
+		return debugFlagList;
+	}
+};
+
+#endif // COMFY_DETECTION_H
diff --git a/engines/comfy/detection_tables.h b/engines/comfy/detection_tables.h
new file mode 100644
index 00000000000..7ebe9c8a25f
--- /dev/null
+++ b/engines/comfy/detection_tables.h
@@ -0,0 +1,43 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+const PlainGameDescriptor comfyGames[] = {
+	{ "comfy", "Comfy" },
+	{ 0, 0 }
+};
+
+const ADGameDescription gameDescriptions[] = {
+	{
+		"comfy",
+		nullptr,
+		AD_ENTRY1s("file1.bin", "00000000000000000000000000000000", 11111),
+		Common::EN_ANY,
+		Common::kPlatformDOS,
+		ADGF_UNSTABLE,
+		GUIO1(GUIO_NONE)
+	},
+
+	AD_TABLE_END_MARKER
+};
+
+} // End of namespace Comfy
diff --git a/engines/comfy/metaengine.cpp b/engines/comfy/metaengine.cpp
new file mode 100644
index 00000000000..03e78fe1c26
--- /dev/null
+++ b/engines/comfy/metaengine.cpp
@@ -0,0 +1,69 @@
+/* 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/translation.h"
+
+#include "comfy/metaengine.h"
+#include "comfy/detection.h"
+#include "comfy/comfy.h"
+
+namespace Comfy {
+
+static const ADExtraGuiOptionsMap optionsList[] = {
+	{
+		GAMEOPTION_ORIGINAL_SAVELOAD,
+		{
+			_s("Use original save/load screens"),
+			_s("Use the original save/load screens instead of the ScummVM ones"),
+			"original_menus",
+			false,
+			0,
+			0
+		}
+	},
+	AD_EXTRA_GUI_OPTIONS_TERMINATOR
+};
+
+} // End of namespace Comfy
+
+const char *ComfyMetaEngine::getName() const {
+	return "comfy";
+}
+
+const ADExtraGuiOptionsMap *ComfyMetaEngine::getAdvancedExtraGuiOptions() const {
+	return Comfy::optionsList;
+}
+
+Common::Error ComfyMetaEngine::createInstance(OSystem *syst, Engine **engine, const ADGameDescription *desc) const {
+	*engine = new Comfy::ComfyEngine(syst, desc);
+	return Common::kNoError;
+}
+
+bool ComfyMetaEngine::hasFeature(MetaEngineFeature f) const {
+	return checkExtendedSaves(f) ||
+		(f == kSupportsLoadingDuringStartup);
+}
+
+#if PLUGIN_ENABLED_DYNAMIC(COMFY)
+REGISTER_PLUGIN_DYNAMIC(COMFY, PLUGIN_TYPE_ENGINE, ComfyMetaEngine);
+#else
+REGISTER_PLUGIN_STATIC(COMFY, PLUGIN_TYPE_ENGINE, ComfyMetaEngine);
+#endif
diff --git a/engines/comfy/metaengine.h b/engines/comfy/metaengine.h
new file mode 100644
index 00000000000..5d23b038466
--- /dev/null
+++ b/engines/comfy/metaengine.h
@@ -0,0 +1,43 @@
+/* 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 COMFY_METAENGINE_H
+#define COMFY_METAENGINE_H
+
+#include "engines/advancedDetector.h"
+
+class ComfyMetaEngine : public AdvancedMetaEngine<ADGameDescription> {
+public:
+	const char *getName() const override;
+
+	Common::Error createInstance(OSystem *syst, Engine **engine, const ADGameDescription *desc) const override;
+
+	/**
+	 * Determine whether the engine supports the specified MetaEngine feature.
+	 *
+	 * Used by e.g. the launcher to determine whether to enable the Load button.
+	 */
+	bool hasFeature(MetaEngineFeature f) const override;
+
+	const ADExtraGuiOptionsMap *getAdvancedExtraGuiOptions() const override;
+};
+
+#endif // COMFY_METAENGINE_H
diff --git a/engines/comfy/module.mk b/engines/comfy/module.mk
new file mode 100644
index 00000000000..5b23c4990a3
--- /dev/null
+++ b/engines/comfy/module.mk
@@ -0,0 +1,17 @@
+MODULE := engines/comfy
+
+MODULE_OBJS = \
+	comfy.o \
+	console.o \
+	metaengine.o
+
+# This module can be built as a plugin
+ifeq ($(ENABLE_COMFY), DYNAMIC_PLUGIN)
+PLUGIN := 1
+endif
+
+# Include common rules
+include $(srcdir)/rules.mk
+
+# Detection objects
+DETECT_OBJS += $(MODULE)/detection.o


Commit: 8811510fe8455459af9045d9d824495018743f2d
    https://github.com/scummvm/scummvm/commit/8811510fe8455459af9045d9d824495018743f2d
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Add stub files and first detection entry

Changed paths:
  A engines/comfy/actor.cpp
  A engines/comfy/comfy_keyboard_ui.cpp
  A engines/comfy/entry.cpp
  A engines/comfy/expr.cpp
  A engines/comfy/game.cpp
  A engines/comfy/input.cpp
  A engines/comfy/keybits.cpp
  A engines/comfy/midi.cpp
  A engines/comfy/midiplyr/midiplyr.cpp
  A engines/comfy/midiplyr/midiplyr.h
  A engines/comfy/palette.cpp
  A engines/comfy/scene.cpp
  A engines/comfy/script.cpp
  A engines/comfy/script_ops.cpp
  A engines/comfy/script_vm.cpp
  A engines/comfy/sound.cpp
  A engines/comfy/timer.cpp
  A engines/comfy/video.cpp
    engines/comfy/detection.cpp
    engines/comfy/detection.h
    engines/comfy/detection_tables.h
    engines/comfy/module.mk


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
new file mode 100644
index 00000000000..409cdeb90bd
--- /dev/null
+++ b/engines/comfy/actor.cpp
@@ -0,0 +1,25 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+
+} // End of namespace Comfy
diff --git a/engines/comfy/comfy_keyboard_ui.cpp b/engines/comfy/comfy_keyboard_ui.cpp
new file mode 100644
index 00000000000..409cdeb90bd
--- /dev/null
+++ b/engines/comfy/comfy_keyboard_ui.cpp
@@ -0,0 +1,25 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+
+} // End of namespace Comfy
diff --git a/engines/comfy/detection.cpp b/engines/comfy/detection.cpp
index 3a5a8f70d33..5f1b061d04b 100644
--- a/engines/comfy/detection.cpp
+++ b/engines/comfy/detection.cpp
@@ -38,8 +38,17 @@ const DebugChannelDef ComfyMetaEngineDetection::debugFlagList[] = {
 	DEBUG_CHANNEL_END
 };
 
+static const char *const directoryGlobs[] = {
+	"SETLANG",
+	"ENGLISH",
+	nullptr
+};
+
 ComfyMetaEngineDetection::ComfyMetaEngineDetection() : AdvancedMetaEngineDetection(
 	Comfy::gameDescriptions, Comfy::comfyGames) {
+	_flags = kADFlagMatchFullPaths;
+	_maxScanDepth = 2;
+	_directoryGlobs = directoryGlobs;
 }
 
 REGISTER_PLUGIN_STATIC(COMFY_DETECTION, PLUGIN_TYPE_ENGINE_DETECTION, ComfyMetaEngineDetection);
diff --git a/engines/comfy/detection.h b/engines/comfy/detection.h
index d2e6cbcfc1a..8b9b2e24d04 100644
--- a/engines/comfy/detection.h
+++ b/engines/comfy/detection.h
@@ -58,7 +58,7 @@ public:
 	}
 
 	const char *getOriginalCopyright() const override {
-		return "Comfy (C)";
+		return "Comfy Interactive Movies, Ltd. (C)";
 	}
 
 	const DebugChannelDef *getDebugChannels() const override {
diff --git a/engines/comfy/detection_tables.h b/engines/comfy/detection_tables.h
index 7ebe9c8a25f..1f790140517 100644
--- a/engines/comfy/detection_tables.h
+++ b/engines/comfy/detection_tables.h
@@ -22,15 +22,19 @@
 namespace Comfy {
 
 const PlainGameDescriptor comfyGames[] = {
-	{ "comfy", "Comfy" },
+	{ "comfyland", "Comfy Land" },
 	{ 0, 0 }
 };
 
 const ADGameDescription gameDescriptions[] = {
 	{
-		"comfy",
+		"comfyland",
 		nullptr,
-		AD_ENTRY1s("file1.bin", "00000000000000000000000000000000", 11111),
+		{
+			{"ENGLISH/COMFY.OBJ", 0, "7b4ce03e92a27c2271d3657d3c13084b", 221184},
+			{"SETLANG/PICFILE.DAT", 0, "88dbbc127cd269b286f4d8c0adad0f1b", 29789},
+			AD_LISTEND
+		},
 		Common::EN_ANY,
 		Common::kPlatformDOS,
 		ADGF_UNSTABLE,
diff --git a/engines/comfy/entry.cpp b/engines/comfy/entry.cpp
new file mode 100644
index 00000000000..409cdeb90bd
--- /dev/null
+++ b/engines/comfy/entry.cpp
@@ -0,0 +1,25 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+
+} // End of namespace Comfy
diff --git a/engines/comfy/expr.cpp b/engines/comfy/expr.cpp
new file mode 100644
index 00000000000..409cdeb90bd
--- /dev/null
+++ b/engines/comfy/expr.cpp
@@ -0,0 +1,25 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+
+} // End of namespace Comfy
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
new file mode 100644
index 00000000000..409cdeb90bd
--- /dev/null
+++ b/engines/comfy/game.cpp
@@ -0,0 +1,25 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+
+} // End of namespace Comfy
diff --git a/engines/comfy/input.cpp b/engines/comfy/input.cpp
new file mode 100644
index 00000000000..409cdeb90bd
--- /dev/null
+++ b/engines/comfy/input.cpp
@@ -0,0 +1,25 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+
+} // End of namespace Comfy
diff --git a/engines/comfy/keybits.cpp b/engines/comfy/keybits.cpp
new file mode 100644
index 00000000000..409cdeb90bd
--- /dev/null
+++ b/engines/comfy/keybits.cpp
@@ -0,0 +1,25 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+
+} // End of namespace Comfy
diff --git a/engines/comfy/midi.cpp b/engines/comfy/midi.cpp
new file mode 100644
index 00000000000..409cdeb90bd
--- /dev/null
+++ b/engines/comfy/midi.cpp
@@ -0,0 +1,25 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+
+} // End of namespace Comfy
diff --git a/engines/comfy/midiplyr/midiplyr.cpp b/engines/comfy/midiplyr/midiplyr.cpp
new file mode 100644
index 00000000000..409cdeb90bd
--- /dev/null
+++ b/engines/comfy/midiplyr/midiplyr.cpp
@@ -0,0 +1,25 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+
+} // End of namespace Comfy
diff --git a/engines/comfy/midiplyr/midiplyr.h b/engines/comfy/midiplyr/midiplyr.h
new file mode 100644
index 00000000000..2de37cfb1b0
--- /dev/null
+++ b/engines/comfy/midiplyr/midiplyr.h
@@ -0,0 +1,25 @@
+/* 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 COMFY_MIDIPLYR_MIDIPLYR_H
+#define COMFY_MIDIPLYR_MIDIPLYR_H
+
+#endif // COMFY_MIDIPLYR_MIDIPLYR_H
diff --git a/engines/comfy/module.mk b/engines/comfy/module.mk
index 5b23c4990a3..4545007f2c9 100644
--- a/engines/comfy/module.mk
+++ b/engines/comfy/module.mk
@@ -1,9 +1,26 @@
 MODULE := engines/comfy
 
 MODULE_OBJS = \
+	actor.o \
 	comfy.o \
+	comfy_keyboard_ui.o \
 	console.o \
-	metaengine.o
+	entry.o \
+	expr.o \
+	game.o \
+	input.o \
+	keybits.o \
+	metaengine.o \
+	midi.o \
+	midiplyr/midiplyr.o \
+	palette.o \
+	scene.o \
+	script.o \
+	script_ops.o \
+	script_vm.o \
+	sound.o \
+	timer.o \
+	video.o
 
 # This module can be built as a plugin
 ifeq ($(ENABLE_COMFY), DYNAMIC_PLUGIN)
diff --git a/engines/comfy/palette.cpp b/engines/comfy/palette.cpp
new file mode 100644
index 00000000000..409cdeb90bd
--- /dev/null
+++ b/engines/comfy/palette.cpp
@@ -0,0 +1,25 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+
+} // End of namespace Comfy
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
new file mode 100644
index 00000000000..409cdeb90bd
--- /dev/null
+++ b/engines/comfy/scene.cpp
@@ -0,0 +1,25 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+
+} // End of namespace Comfy
diff --git a/engines/comfy/script.cpp b/engines/comfy/script.cpp
new file mode 100644
index 00000000000..409cdeb90bd
--- /dev/null
+++ b/engines/comfy/script.cpp
@@ -0,0 +1,25 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+
+} // End of namespace Comfy
diff --git a/engines/comfy/script_ops.cpp b/engines/comfy/script_ops.cpp
new file mode 100644
index 00000000000..409cdeb90bd
--- /dev/null
+++ b/engines/comfy/script_ops.cpp
@@ -0,0 +1,25 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+
+} // End of namespace Comfy
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
new file mode 100644
index 00000000000..409cdeb90bd
--- /dev/null
+++ b/engines/comfy/script_vm.cpp
@@ -0,0 +1,25 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+
+} // End of namespace Comfy
diff --git a/engines/comfy/sound.cpp b/engines/comfy/sound.cpp
new file mode 100644
index 00000000000..409cdeb90bd
--- /dev/null
+++ b/engines/comfy/sound.cpp
@@ -0,0 +1,25 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+
+} // End of namespace Comfy
diff --git a/engines/comfy/timer.cpp b/engines/comfy/timer.cpp
new file mode 100644
index 00000000000..409cdeb90bd
--- /dev/null
+++ b/engines/comfy/timer.cpp
@@ -0,0 +1,25 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+
+} // End of namespace Comfy
diff --git a/engines/comfy/video.cpp b/engines/comfy/video.cpp
new file mode 100644
index 00000000000..409cdeb90bd
--- /dev/null
+++ b/engines/comfy/video.cpp
@@ -0,0 +1,25 @@
+/* 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/>.
+ *
+ */
+
+namespace Comfy {
+
+
+} // End of namespace Comfy


Commit: 11b5f2a746bcd020317b2a8529e82740491600c2
    https://github.com/scummvm/scummvm/commit/11b5f2a746bcd020317b2a8529e82740491600c2
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Implement MIDIPLYR.DLL driver

Changed paths:
    engines/comfy/midiplyr/midiplyr.cpp
    engines/comfy/midiplyr/midiplyr.h


diff --git a/engines/comfy/midiplyr/midiplyr.cpp b/engines/comfy/midiplyr/midiplyr.cpp
index 409cdeb90bd..2a205ccc528 100644
--- a/engines/comfy/midiplyr/midiplyr.cpp
+++ b/engines/comfy/midiplyr/midiplyr.cpp
@@ -19,7 +19,817 @@
  *
  */
 
+#include "comfy/midiplyr/midiplyr.h"
+
+#include "audio/mididrv.h"
+#include "common/endian.h"
+#include "common/system.h"
+#include "common/timer.h"
+#include "common/util.h"
+
 namespace Comfy {
 
+MidiPlyrDriver::MidiPlyrDriver(DriverVersion driverVersion) :
+	_driverVersion(driverVersion), _midiDriver(nullptr), _started(false), _timerInstalled(false) {
+	resetState();
+}
+
+MidiPlyrDriver::~MidiPlyrDriver() {
+	musicEnd();
+}
+
+void MidiPlyrDriver::resetState() {
+	_noteCount = 0;
+	_midiDeviceId = 0;
+	_midiDeviceHandle = 0;
+	_deferredCc7QueuedCount = 0;
+	_sendDirectGuard = 0;
+	_seqCurrentTick = 0;
+	_vocBlockNo = 0;
+	_vocUnknown = 0;
+	_comfyboardStopReading = 1;
+	_comfyboardSampleIndex = 0;
+	_comfyboardButtons = 0;
+	_comfyboardSleepUseStopped = 1;
+	_comfyboardPort = 0;
+	_comfyboardXorMask = 0;
+	_comfyboardSavedControl = 0;
+	_timeFracHi = 0;
+	_timeFracLo = 0;
+	_increaseVocCounter = 0;
+	_tempoAcc = 0;
+	_timeFracAcc = 0;
+	_midiOutResult = 0;
+	_midiFileFormat = 0;
+	_ticksPerQuarter = 0;
+	_channelAvailMask = 0xFFFF;
+	_drumsChannel = 9;
+	_midiNoteCountCap = 0;
+	_vocSnapshotHi = 0;
+	_vocSnapshotLo = 0;
+
+	for (uint i = 0; i < MIDIPLYR_DEFERRED_CC7_COUNT_MAX; i++)
+		_deferredCc7[i] = 0xFFFF;
+
+	for (uint i = 0; i < MIDIPLYR_CHANNEL_COUNT; i++) {
+		_deferredCc7Order[i] = 0;
+		_channels[i].inUse = 0;
+		_channels[i].volumePercent = 100;
+	}
+
+	for (uint i = 0; i < MIDIPLYR_NOTE_CAPACITY; i++) {
+		_notes[i].channel = 0;
+		_notes[i].pitch = 0;
+	}
+
+	for (uint i = 0; i < ARRAYSIZE(_comfyboardSamples); i++)
+		_comfyboardSamples[i] = 0;
+
+	for (uint i = 0; i < kTrackCount; i++) {
+		Track &track = _tracks[i];
+		track.state = 0;
+		track.streamBase = nullptr;
+		track.eventDataSize = 0;
+		track.eventCursor = 0;
+		track.rate = 0;
+		track.startTick = 0;
+		track.volume = 0;
+		track.pitch = 0;
+		track.marker = 0;
+		track.midiLoopFlag = 0;
+		track.streamSize = 0;
+		track.streamFault = false;
+
+		for (uint channel = 0; channel < MIDIPLYR_CHANNEL_COUNT; channel++)
+			track.channelState[channel] = MIDIPLYR_FREE_CHANNEL;
+	}
+}
+
+uint32 MidiPlyrDriver::midiFindDevice() {
+	_midiDeviceHandle = MidiDriver::detectDevice(MDT_MIDI | MDT_ADLIB | MDT_PREFER_GM);
+	return _midiDeviceHandle;
+}
+
+bool MidiPlyrDriver::midiOpen() {
+	_midiDriver = MidiDriver::createMidi(midiFindDevice());
+
+	if (!_midiDriver)
+		return false;
+
+	_midiOutResult = _midiDriver->open();
+
+	if (_midiOutResult != 0) {
+		delete _midiDriver;
+		_midiDriver = nullptr;
+		return false;
+	}
+
+	_channelAvailMask = 0xFFFF;
+	_midiNoteCountCap = 0;
+	_midiDeviceId = 0;
+	return true;
+}
+
+void MidiPlyrDriver::midiClose() {
+	if (!_midiDriver)
+		return;
+
+	_midiDriver->stopAllNotes(true);
+	_midiDriver->close();
+	delete _midiDriver;
+	_midiDriver = nullptr;
+}
+
+bool MidiPlyrDriver::musicStart(byte flags) {
+	Common::StackLock lock(_mutex);
+
+	if (_started)
+		return true;
+
+	resetState();
+	_midiFileFormat = flags & 1;
+
+	if (!midiOpen())
+		return false;
+
+	for (uint channel = 0; channel < MIDIPLYR_CHANNEL_COUNT; channel++) {
+		midiSetChannelValue(channel, 100);
+		midiSendControlChange(channel, 100);
+	}
+
+	midiFreeAllChannels();
+
+	if ((flags & 2) == 0) {
+		_timerInstalled = g_system->getTimerManager()->installTimerProc(
+			&timerProc, MIDIPLYR_TIMER_PERIOD, this, "Comfy::MidiPlyrDriver");
+
+		if (!_timerInstalled) {
+			midiClose();
+			return false;
+		}
+	}
+
+	_started = true;
+	return true;
+}
+
+void MidiPlyrDriver::uninstallTimer() {
+	_mutex.lock();
+	bool removeTimer = _timerInstalled;
+	_timerInstalled = false;
+	_mutex.unlock();
+
+	// removeTimerProc() waits for an active callback, which may itself be
+	// waiting for _mutex, so the mutex must be released before this call...
+	if (removeTimer)
+		g_system->getTimerManager()->removeTimerProc(&timerProc);
+}
+
+void MidiPlyrDriver::musicEnd() {
+	uninstallTimer();
+
+	Common::StackLock lock(_mutex);
+
+	if (!_started && !_midiDriver)
+		return;
+
+	musicStopAllInternal(1);
+	midiClose();
+	_started = false;
+}
+
+void MidiPlyrDriver::timerProc(void *refCon) {
+	static_cast<MidiPlyrDriver *>(refCon)->timeCallback();
+}
+
+void MidiPlyrDriver::timeCallback() {
+	Common::StackLock lock(_mutex);
+
+	if (_started)
+		timeCallbackInternal();
+}
+
+void MidiPlyrDriver::timeCallbackInternal() {
+	comfyboardPollTimer();
+
+	if (_tempoAcc != 0xFFFFFFFF)
+		_tempoAcc++;
+
+	if (_increaseVocCounter && _timeFracAcc != 0xFFFFFFFF) {
+		_timeFracAcc++;
+		_timeFracHi = _timeFracAcc >> 16;
+		_timeFracLo = _timeFracAcc;
+	}
+
+	_seqCurrentTick += 100;
+	if (_sendDirectGuard == 0) {
+		_sendDirectGuard = 1;
+		sequencerTick();
+	}
+
+	_sendDirectGuard = 0;
+}
+
+void MidiPlyrDriver::midiSendShortMessage(uint32 message) {
+	if (_midiDriver) {
+		_midiDriver->send(message);
+		_midiOutResult = 0;
+	}
+}
+
+void MidiPlyrDriver::noteTrackAdd(uint16 channel, uint16 pitch) {
+	// The original has no overflow check. Keep the fixed-size representation,
+	// but do not allow malformed data to overwrite adjacent driver state...
+	if (_noteCount >= MIDIPLYR_NOTE_CAPACITY)
+		return;
+
+	_notes[_noteCount].channel = channel;
+	_notes[_noteCount].pitch = pitch;
+	_noteCount++;
+}
+
+void MidiPlyrDriver::noteTrackRemove(uint16 channel, uint16 pitch) {
+	for (uint i = 0; i < _noteCount; i++) {
+		if (_notes[i].channel == channel && _notes[i].pitch == pitch) {
+			_noteCount--;
+			_notes[i] = _notes[_noteCount];
+			return;
+		}
+	}
+}
+
+void MidiPlyrDriver::midiSendNoteOff(uint16 channel, uint16 pitch, uint16 velocity) {
+	if (_driverVersion == kDriverVersion1 && (channel > 15 || pitch > 127))
+		channel--;
+
+	midiSendShortMessage((velocity << 16) | ((pitch & 0xFF) << 8) | ((0x80 + channel) & 0xFFFF));
+	noteTrackRemove(channel, pitch);
+}
+
+void MidiPlyrDriver::midiSendNoteOn(uint16 channel, uint16 pitch, uint16 velocity) {
+	if (_driverVersion == kDriverVersion1 && (channel > 15 || pitch > 127))
+		channel--;
+
+	if (velocity == 0) {
+		midiSendNoteOff(channel, pitch, 0);
+		return;
+	}
+
+	midiSendShortMessage((velocity << 16) | ((pitch & 0xFF) << 8) | ((0x90 + channel) & 0xFFFF));
+	noteTrackAdd(channel, pitch);
+}
+
+void MidiPlyrDriver::midiSendProgramChange(uint16 channel, uint16 program) {
+	if (_driverVersion == kDriverVersion1 && (channel > 15 || program > 127))
+		channel--;
+
+	midiSendShortMessage(((program & 0xFF) << 8) | ((0xC0 + channel) & 0xFFFF));
+}
+
+uint MidiPlyrDriver::deferredCc7Count() const {
+	return _driverVersion == kDriverVersion1 ? MIDIPLYR_DEFERRED_CC7_COUNT_DRV_V1 : MIDIPLYR_DEFERRED_CC7_COUNT_DRV_V2;
+}
+
+void MidiPlyrDriver::midiSendControlChange(uint16 channel, uint16 value) {
+	if (_sendDirectGuard == 0) {
+		if (channel >= deferredCc7Count())
+			return;
+
+		if (_deferredCc7[channel] == 0xFFFF) {
+			if (_deferredCc7QueuedCount >= MIDIPLYR_CHANNEL_COUNT)
+				return;
+
+			_deferredCc7Order[_deferredCc7QueuedCount++] = channel;
+		}
+
+		_deferredCc7[channel] = value;
+		return;
+	}
+
+	if (channel != MIDIPLYR_CC7_FLUSH_SENTINEL) {
+		midiSendShortMessage((value << 16) | (7 << 8) | (0xB0 + channel));
+		return;
+	}
+
+	while (_deferredCc7QueuedCount != 0) {
+		uint16 queuedChannel = _deferredCc7Order[--_deferredCc7QueuedCount];
+		if (queuedChannel >= deferredCc7Count() || _deferredCc7[queuedChannel] == 0xFFFF)
+			continue;
+
+		midiSendShortMessage((_deferredCc7[queuedChannel] << 16) | (7 << 8) | (0xB0 + queuedChannel));
+
+		if (_driverVersion == kDriverVersion2 && _midiOutResult != 0) {
+			_deferredCc7QueuedCount++;
+			break;
+		}
+
+		_deferredCc7[queuedChannel] = 0xFFFF;
+	}
+}
+
+void MidiPlyrDriver::midiSetChannelValue(byte channel, byte value) {
+	if (channel < MIDIPLYR_CHANNEL_COUNT)
+		_channels[channel].volumePercent = value;
+}
+
+byte MidiPlyrDriver::midiGetChannelValue(byte channel) const {
+	return channel < MIDIPLYR_CHANNEL_COUNT ? _channels[channel].volumePercent : 0;
+}
+
+byte MidiPlyrDriver::midiFindFreeChannel() const {
+	for (uint channel = 0; channel < MIDIPLYR_CHANNEL_COUNT; channel++) {
+		if (channel != _drumsChannel && (_channelAvailMask & (1 << channel)) && !_channels[channel].inUse)
+			return channel;
+	}
+
+	return MIDIPLYR_FREE_CHANNEL;
+}
+
+byte MidiPlyrDriver::midiAllocChannel() {
+	byte channel = midiFindFreeChannel();
+
+	if (channel != MIDIPLYR_FREE_CHANNEL)
+		_channels[channel].inUse = 1;
+
+	return channel;
+}
+
+void MidiPlyrDriver::midiFreeChannel(byte channel) {
+	if (channel < MIDIPLYR_CHANNEL_COUNT)
+		_channels[channel].inUse = 0;
+}
+
+void MidiPlyrDriver::midiFreeAllChannels() {
+	for (uint channel = 0; channel < MIDIPLYR_CHANNEL_COUNT; channel++)
+		midiFreeChannel(channel);
+}
+
+void MidiPlyrDriver::midiAllNotesOff(byte channel) {
+	if (channel >= MIDIPLYR_CHANNEL_COUNT)
+		channel--;
+
+	for (uint i = _noteCount; i > 0; i--) {
+		uint noteIndex = i - 1;
+
+		if (_notes[noteIndex].channel == channel)
+			midiSendNoteOff(channel, _notes[noteIndex].pitch, 0);
+	}
+}
+
+void MidiPlyrDriver::musicSetRateInternal(uint16 rate, byte track) {
+	if (track < kTrackCount)
+		_tracks[track].rate = rate;
+}
+
+void MidiPlyrDriver::musicSetRate(uint16 rate, byte track) {
+	Common::StackLock lock(_mutex);
+	musicSetRateInternal(rate, track);
+}
+
+void MidiPlyrDriver::musicSetPitchInternal(uint16 pitch, byte trackIndex) {
+	if (trackIndex >= kTrackCount)
+		return;
+
+	Track &track = _tracks[trackIndex];
+	for (uint i = 0; i < MIDIPLYR_CHANNEL_COUNT; i++) {
+		if (track.channelState[i] != MIDIPLYR_FREE_CHANNEL)
+			track.pitch = pitch;
+	}
+}
+
+void MidiPlyrDriver::musicSetPitch(uint16 pitch, byte track) {
+	Common::StackLock lock(_mutex);
+	musicSetPitchInternal(pitch, track);
+}
+
+void MidiPlyrDriver::musicSetLoop(byte flag, uint16 track) {
+	Common::StackLock lock(_mutex);
+
+	if (_driverVersion == kDriverVersion2 && track < kTrackCount)
+		_tracks[track].midiLoopFlag = flag;
+}
+
+void MidiPlyrDriver::musicPlaySong(const byte *data, uint32 size, uint16 trackIndex) {
+	Common::StackLock lock(_mutex);
+
+	if (trackIndex >= kTrackCount || !data || size < 7)
+		return;
+
+	Track &track = _tracks[trackIndex];
+	uint32 headerSize = _driverVersion == kDriverVersion2 ? 6 : 7;
+	for (uint channel = 0; channel < MIDIPLYR_CHANNEL_COUNT; channel++)
+		track.channelState[channel] = MIDIPLYR_FREE_CHANNEL;
+
+	track.channelState[_drumsChannel] = _drumsChannel;
+	track.streamBase = data + headerSize;
+	track.streamSize = size - headerSize;
+	track.streamFault = false;
+	track.eventCursor = 0;
+	track.marker = 0;
+	track.midiLoopFlag = 0;
+	track.eventDataSize = READ_LE_UINT16(data + 4);
+
+	if (_midiFileFormat == 1)
+		_ticksPerQuarter = READ_LE_UINT16(data + 2);
+	else
+		musicSetRateInternal(READ_LE_UINT16(data + 2), trackIndex);
+
+	musicSetPitchInternal(5000, trackIndex);
+	track.startTick = _seqCurrentTick;
+	track.state = 1;
+	if (_driverVersion == kDriverVersion2) {
+		streamReadVarLen(track);
+
+		if (track.streamFault) {
+			track.state = 0;
+			return;
+		}
+
+		_sendDirectGuard = 1;
+		midiSendControlChange(MIDIPLYR_CC7_FLUSH_SENTINEL, 0);
+		trackAdvance(trackIndex);
+		_sendDirectGuard = 0;
+	} else {
+		trackAdvance(trackIndex);
+	}
+
+	track.state = track.streamFault ? 0 : 2;
+}
+
+void MidiPlyrDriver::musicStopSongInternal(byte fullStop, uint16 trackIndex) {
+	if (trackIndex >= kTrackCount)
+		return;
+
+	Track &track = _tracks[trackIndex];
+	track.state = 0;
+	if (fullStop) {
+		track.marker = 0;
+		track.eventCursor = 0;
+
+		for (uint i = 0; i < MIDIPLYR_CHANNEL_COUNT; i++) {
+			byte channel = track.channelState[i];
+			if (channel != MIDIPLYR_FREE_CHANNEL) {
+				midiFreeChannel(channel);
+				midiSetChannelValue(channel, 100);
+				midiAllNotesOff(channel);
+			}
+		}
+
+		// The original writes one byte past channelState after this loop,
+		// changing the low byte of rate instead of clearing the channel array.
+		// We replicate this bug...
+		track.rate = (track.rate & 0xFF00) | MIDIPLYR_FREE_CHANNEL;
+	} else {
+		for (uint i = 0; i < MIDIPLYR_CHANNEL_COUNT; i++) {
+			if (track.channelState[i] != MIDIPLYR_FREE_CHANNEL)
+				midiAllNotesOff(track.channelState[i]);
+		}
+	}
+}
+
+void MidiPlyrDriver::musicStopSong(byte fullStop, uint16 track) {
+	Common::StackLock lock(_mutex);
+	musicStopSongInternal(fullStop, track);
+}
+
+void MidiPlyrDriver::musicStopAllInternal(byte fullStop) {
+	for (uint track = 0; track < kTrackCount; track++)
+		musicStopSongInternal(fullStop, track);
+}
+
+void MidiPlyrDriver::musicStopAll(byte fullStop) {
+	Common::StackLock lock(_mutex);
+	musicStopAllInternal(fullStop);
+}
+
+void MidiPlyrDriver::musicContinueSong(uint16 trackIndex) {
+	Common::StackLock lock(_mutex);
+
+	if (trackIndex < kTrackCount && _tracks[trackIndex].eventCursor < _tracks[trackIndex].eventDataSize) {
+		_tracks[trackIndex].state = 2;
+		_tracks[trackIndex].startTick = _seqCurrentTick;
+	}
+}
+
+bool MidiPlyrDriver::musicIsSongPlaying(uint16 track) const {
+	Common::StackLock lock(_mutex);
+	return track < kTrackCount && _tracks[track].state == 2;
+}
+
+uint16 MidiPlyrDriver::musicGetClearMarker(uint16 track) {
+	Common::StackLock lock(_mutex);
+
+	if (track >= kTrackCount)
+		return 0;
+
+	uint16 marker = _tracks[track].marker;
+	_tracks[track].marker = 0;
+	return marker;
+}
+
+void MidiPlyrDriver::musicSetVolume(uint16 volume, uint16 trackIndex) {
+	Common::StackLock lock(_mutex);
+
+	if (trackIndex >= kTrackCount)
+		return;
+
+	if (_midiFileFormat != 1)
+		volume = (int16(volume) * 0x55) / 100;
+
+	volume = (int16(volume) * 0x7F) / 100;
+	Track &track = _tracks[trackIndex];
+
+	for (uint i = 0; i < MIDIPLYR_CHANNEL_COUNT; i++) {
+		byte channel = track.channelState[i];
+		if (channel != MIDIPLYR_FREE_CHANNEL)
+			midiSendControlChange(channel, (volume * midiGetChannelValue(channel)) / 100);
+	}
+
+	track.volume = volume;
+}
+
+byte MidiPlyrDriver::streamReadByte(Track &track) {
+	if (!track.streamBase || track.eventCursor >= track.streamSize) {
+		track.streamFault = true;
+		return 0;
+	}
+
+	return track.streamBase[track.eventCursor++];
+}
+
+void MidiPlyrDriver::streamSkipBytes(Track &track, byte count) {
+	for (uint i = 0; i < count; i++)
+		streamReadByte(track);
+}
+
+uint32 MidiPlyrDriver::streamReadVarLen(Track &track) {
+	uint32 value = 0;
+	byte current = 0;
+
+	do {
+		current = streamReadByte(track);
+		value = (value << 7) | (current & 0x7F);
+	} while (!track.streamFault && (current & 0x80));
+
+	return value;
+}
+
+void MidiPlyrDriver::sequencerParseEvent(uint16 trackIndex) {
+	Track &track = _tracks[trackIndex];
+	byte statusByte = streamReadByte(track);
+	byte status = statusByte & 0xF0;
+	byte logicalChannel = statusByte & 0x0F;
+	byte physicalChannel = logicalChannel;
+
+	if (status != 0xF0) {
+		if (track.channelState[logicalChannel] == MIDIPLYR_FREE_CHANNEL) {
+			physicalChannel = midiAllocChannel();
+			track.channelState[logicalChannel] = physicalChannel;
+
+			if (physicalChannel != MIDIPLYR_FREE_CHANNEL)
+				midiSendControlChange(physicalChannel, track.volume);
+		} else {
+			physicalChannel = track.channelState[logicalChannel];
+		}
+	}
+
+	switch (status) {
+	case 0x80: {
+		byte pitch = streamReadByte(track);
+		midiSendNoteOff(physicalChannel, pitch, streamReadByte(track));
+		break;
+	}
+	case 0x90: {
+		byte pitch = streamReadByte(track);
+		midiSendNoteOn(physicalChannel, pitch, streamReadByte(track));
+		break;
+	}
+	case 0xA0:
+		streamReadByte(track);
+		streamReadByte(track);
+		break;
+	case 0xB0: {
+		byte controller = streamReadByte(track);
+		byte value = streamReadByte(track);
+
+		if (controller == 7 && _midiFileFormat == 1) {
+			byte channelValue = (value * 100) / 127;
+			midiSetChannelValue(physicalChannel, channelValue);
+			midiSendControlChange(physicalChannel, (channelValue * track.volume) / 100);
+		} else if (controller == 10) {
+			track.marker = value;
+		}
+
+		break;
+	}
+	case 0xC0:
+		midiSendProgramChange(physicalChannel, streamReadByte(track));
+		break;
+	case 0xD0:
+		streamReadByte(track);
+		break;
+	case 0xE0:
+		streamReadByte(track);
+		streamReadByte(track);
+		break;
+	case 0xF0: {
+		byte event = streamReadByte(track);
+		byte skipCount = 0;
+		switch (event) {
+		case 0x2F:
+			skipCount = streamReadByte(track);
+
+			if (_driverVersion == kDriverVersion2 && track.midiLoopFlag) {
+				track.eventCursor = 0;
+				return;
+			}
+
+			musicStopSongInternal(1, trackIndex);
+			break;
+		case 0x14:
+			skipCount = streamReadByte(track) - 1;
+			streamReadByte(track);
+			break;
+		case 0x15:
+			skipCount = streamReadByte(track) - 2;
+			streamReadByte(track);
+			streamReadByte(track);
+			break;
+		case 0x51:
+			if (_midiFileFormat == 1) {
+				streamReadByte(track);
+				uint32 tempo = (streamReadByte(track) << 16) |
+					(streamReadByte(track) << 8) | streamReadByte(track);
+
+				if (_ticksPerQuarter)
+					musicSetRateInternal(tempo / _ticksPerQuarter, trackIndex);
+			} else {
+				skipCount = streamReadByte(track);
+			}
+
+			break;
+		default:
+			skipCount = streamReadByte(track);
+			break;
+		}
+
+		streamSkipBytes(track, skipCount);
+		break;
+	}
+	default:
+		streamReadByte(track);
+		break;
+	}
+}
+
+void MidiPlyrDriver::trackAdvance(uint16 trackIndex) {
+	if (trackIndex >= kTrackCount)
+		return;
+
+	Track &track = _tracks[trackIndex];
+	while (!track.streamFault && track.state && track.eventCursor < track.eventDataSize &&
+	       track.startTick <= _seqCurrentTick) {
+
+		sequencerParseEvent(trackIndex);
+
+		if (track.streamFault) {
+			track.state = 0;
+			break;
+		}
+
+		uint32 delta = streamReadVarLen(track);
+
+		if (track.streamFault) {
+			track.state = 0;
+			break;
+		}
+
+		if (delta == 0)
+			continue;
+
+		uint32 scaled = (track.rate * delta) / 100;
+		if (track.state == 1)
+			track.startTick = _seqCurrentTick + scaled;
+		else
+			track.startTick += scaled;
+
+		break;
+	}
+}
+
+void MidiPlyrDriver::sequencerTick() {
+	midiSendControlChange(MIDIPLYR_CC7_FLUSH_SENTINEL, 0);
+	bool active = false;
+	for (uint track = 0; track < kTrackCount; track++) {
+		if (_tracks[track].state == 2)
+			trackAdvance(track);
+
+		if (_tracks[track].state)
+			active = true;
+	}
+
+	if (!active)
+		_seqCurrentTick = 0;
+}
+
+void MidiPlyrDriver::setIncreaseVocCounter(byte flag) {
+	Common::StackLock lock(_mutex);
+	_increaseVocCounter = flag;
+}
+
+void MidiPlyrDriver::setVocCounter(uint32 value) {
+	Common::StackLock lock(_mutex);
+	_timeFracAcc = value;
+	_timeFracHi = value >> 16;
+	_timeFracLo = value;
+}
+
+uint32 MidiPlyrDriver::getVocCounter() const {
+	Common::StackLock lock(_mutex);
+	return _timeFracAcc;
+}
+
+void MidiPlyrDriver::setTimeCounter(uint32 value) {
+	Common::StackLock lock(_mutex);
+	_tempoAcc = value;
+}
+
+uint32 MidiPlyrDriver::getTimeCounter() const {
+	Common::StackLock lock(_mutex);
+	return _tempoAcc;
+}
+
+void MidiPlyrDriver::vocSrResetCounters() {
+	Common::StackLock lock(_mutex);
+	_vocBlockNo = 0;
+	_vocUnknown = 0;
+	_vocSnapshotHi = 0;
+	_vocSnapshotLo = 0;
+}
+
+void MidiPlyrDriver::vocSrResetBlockNo() {
+	Common::StackLock lock(_mutex);
+	_vocBlockNo = 0;
+}
+
+void MidiPlyrDriver::vocSrUpdateCountersInternal() {
+	_vocBlockNo++;
+	_vocSnapshotHi = _timeFracHi;
+	_vocSnapshotLo = _timeFracLo;
+}
+
+void MidiPlyrDriver::vocSrUpdateCounters() {
+	Common::StackLock lock(_mutex);
+	vocSrUpdateCountersInternal();
+}
+
+void MidiPlyrDriver::vocSrGetCounters(uint32 &timeFrac, uint16 &blockNo) const {
+	Common::StackLock lock(_mutex);
+	timeFrac = (uint32(_vocSnapshotHi) << 16) | _vocSnapshotLo;
+	blockNo = _vocBlockNo;
+}
+
+uint16 MidiPlyrDriver::getMidiDevId() const {
+	Common::StackLock lock(_mutex);
+	return _midiDeviceId;
+}
+
+uint32 MidiPlyrDriver::comfyboardGetButtons() const {
+	Common::StackLock lock(_mutex);
+	return _comfyboardButtons;
+}
+
+void MidiPlyrDriver::comfyboardStartReading(uint32 xorMask, uint16 port) {
+	Common::StackLock lock(_mutex);
+	_comfyboardPort = port;
+	_comfyboardXorMask = xorMask;
+	_comfyboardButtons = 0;
+	_comfyboardSampleIndex = 0;
+	_comfyboardStopReading = 0;
+}
+
+void MidiPlyrDriver::comfyboardStopReading() {
+	Common::StackLock lock(_mutex);
+	_comfyboardStopReading = 1;
+	_comfyboardSampleIndex = 0;
+	_comfyboardButtons = 0;
+}
+
+void MidiPlyrDriver::comfyboardStartSleepUse() {
+	Common::StackLock lock(_mutex);
+	_comfyboardSleepUseStopped = 0;
+}
+
+void MidiPlyrDriver::comfyboardStopSleepUse() {
+	Common::StackLock lock(_mutex);
+	_comfyboardSleepUseStopped = 1;
+}
+
+void MidiPlyrDriver::comfyboardPollTimer() {
+	if (_driverVersion != kDriverVersion2 || _comfyboardStopReading)
+		return;
+
+	// TODO: Reroute to actual LPT emulated parser...
+}
 
 } // End of namespace Comfy
diff --git a/engines/comfy/midiplyr/midiplyr.h b/engines/comfy/midiplyr/midiplyr.h
index 2de37cfb1b0..3b59f91a064 100644
--- a/engines/comfy/midiplyr/midiplyr.h
+++ b/engines/comfy/midiplyr/midiplyr.h
@@ -22,4 +22,174 @@
 #ifndef COMFY_MIDIPLYR_MIDIPLYR_H
 #define COMFY_MIDIPLYR_MIDIPLYR_H
 
+#include "common/mutex.h"
+#include "common/scummsys.h"
+
+#define MIDIPLYR_CHANNEL_COUNT 16
+#define MIDIPLYR_FREE_CHANNEL 0x10
+#define MIDIPLYR_NOTE_CAPACITY 64
+#define MIDIPLYR_DEFERRED_CC7_COUNT_DRV_V1 102
+#define MIDIPLYR_DEFERRED_CC7_COUNT_DRV_V2 64
+#define MIDIPLYR_DEFERRED_CC7_COUNT_MAX MIDIPLYR_DEFERRED_CC7_COUNT_DRV_V1
+#define MIDIPLYR_CC7_FLUSH_SENTINEL 999
+#define MIDIPLYR_TIMER_PERIOD 10000
+
+class MidiDriver;
+
+namespace Comfy {
+
+class MidiPlyrDriver {
+public:
+	enum DriverVersion {
+		kDriverVersion1, // 1994 MIDIPLYR.DLL
+		kDriverVersion2  // 1999 MIDIPLYR.DLL
+	};
+
+	static const uint kTrackCount = 6;
+
+	explicit MidiPlyrDriver(DriverVersion driverVersion);
+	~MidiPlyrDriver();
+
+	bool musicStart(byte flags);
+	void musicEnd();
+	void musicPlaySong(const byte *data, uint32 size, uint16 track);
+	void musicStopSong(byte fullStop, uint16 track);
+	void musicStopAll(byte fullStop);
+	void musicContinueSong(uint16 track);
+	bool musicIsSongPlaying(uint16 track) const;
+	uint16 musicGetClearMarker(uint16 track);
+	void musicSetVolume(uint16 volume, uint16 track);
+	void musicSetPitch(uint16 pitch, byte track);
+	void musicSetRate(uint16 rate, byte track);
+	void musicSetLoop(byte flag, uint16 track);
+	uint16 getMidiDevId() const;
+
+	void timeCallback();
+	void setTimeCounter(uint32 value);
+	uint32 getTimeCounter() const;
+	void setVocCounter(uint32 value);
+	uint32 getVocCounter() const;
+	void setIncreaseVocCounter(byte flag);
+
+	void vocSrResetCounters();
+	void vocSrResetBlockNo();
+	void vocSrGetCounters(uint32 &timeFrac, uint16 &blockNo) const;
+	void vocSrUpdateCounters();
+
+	uint32 comfyboardGetButtons() const;
+	void comfyboardStartReading(uint32 xorMask, uint16 port);
+	void comfyboardStopReading();
+	void comfyboardStartSleepUse();
+	void comfyboardStopSleepUse();
+
+private:
+	struct Track {
+		uint16 state;
+		const byte *streamBase;
+		uint16 eventDataSize;
+		uint16 eventCursor;
+		byte channelState[MIDIPLYR_CHANNEL_COUNT];
+		uint16 rate;
+		uint32 startTick;
+		byte volume;
+		uint16 pitch;
+		uint16 marker;
+		byte midiLoopFlag;
+		uint32 streamSize;
+		bool streamFault;
+	};
+
+	struct Note {
+		uint16 channel;
+		uint16 pitch;
+	};
+
+	struct ChannelSlot {
+		byte inUse;
+		byte volumePercent;
+	};
+
+	static void timerProc(void *refCon);
+
+	void resetState();
+	void uninstallTimer();
+	uint32 midiFindDevice();
+	bool midiOpen();
+	void midiClose();
+	void midiSendShortMessage(uint32 message);
+	void midiSendNoteOff(uint16 channel, uint16 pitch, uint16 velocity);
+	void midiSendNoteOn(uint16 channel, uint16 pitch, uint16 velocity);
+	void midiSendProgramChange(uint16 channel, uint16 program);
+	void midiSendControlChange(uint16 channel, uint16 value);
+	void midiAllNotesOff(byte channel);
+	byte midiFindFreeChannel() const;
+	byte midiAllocChannel();
+	void midiFreeChannel(byte channel);
+	void midiFreeAllChannels();
+	void midiSetChannelValue(byte channel, byte value);
+	byte midiGetChannelValue(byte channel) const;
+	void noteTrackAdd(uint16 channel, uint16 pitch);
+	void noteTrackRemove(uint16 channel, uint16 pitch);
+	uint deferredCc7Count() const;
+
+	void musicStopSongInternal(byte fullStop, uint16 track);
+	void musicStopAllInternal(byte fullStop);
+	void musicSetRateInternal(uint16 rate, byte track);
+	void musicSetPitchInternal(uint16 pitch, byte track);
+	void trackAdvance(uint16 track);
+	void sequencerTick();
+	void sequencerParseEvent(uint16 track);
+	byte streamReadByte(Track &track);
+	uint32 streamReadVarLen(Track &track);
+	void streamSkipBytes(Track &track, byte count);
+	void timeCallbackInternal();
+	void comfyboardPollTimer();
+	void vocSrUpdateCountersInternal();
+
+	DriverVersion _driverVersion;
+	MidiDriver *_midiDriver;
+	mutable Common::Mutex _mutex;
+	bool _started;
+	bool _timerInstalled;
+
+	byte _noteCount;
+	uint16 _midiDeviceId;
+	uint32 _midiDeviceHandle;
+	uint16 _deferredCc7QueuedCount;
+	uint16 _deferredCc7[MIDIPLYR_DEFERRED_CC7_COUNT_MAX];
+	uint16 _deferredCc7Order[MIDIPLYR_CHANNEL_COUNT];
+	byte _sendDirectGuard;
+	uint32 _seqCurrentTick;
+	uint16 _vocBlockNo;
+	uint32 _vocUnknown;
+
+	byte _comfyboardStopReading;
+	uint16 _comfyboardSampleIndex;
+	uint32 _comfyboardButtons;
+	byte _comfyboardSleepUseStopped;
+	uint16 _comfyboardPort;
+	uint32 _comfyboardXorMask;
+	byte _comfyboardSamples[8];
+	byte _comfyboardSavedControl;
+
+	ChannelSlot _channels[MIDIPLYR_CHANNEL_COUNT];
+	uint16 _timeFracHi;
+	uint16 _timeFracLo;
+	byte _increaseVocCounter;
+	uint32 _tempoAcc;
+	uint32 _timeFracAcc;
+	Note _notes[MIDIPLYR_NOTE_CAPACITY];
+	uint16 _midiOutResult;
+	Track _tracks[kTrackCount];
+	uint16 _midiFileFormat;
+	uint32 _ticksPerQuarter;
+	uint16 _channelAvailMask;
+	uint16 _drumsChannel;
+	uint16 _midiNoteCountCap;
+	uint16 _vocSnapshotHi;
+	uint16 _vocSnapshotLo;
+};
+
+} // End of namespace Comfy
+
 #endif // COMFY_MIDIPLYR_MIDIPLYR_H


Commit: 39a868f0e47bd52c09a0cef7397617e2f76ad031
    https://github.com/scummvm/scummvm/commit/39a868f0e47bd52c09a0cef7397617e2f76ad031
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Add PIT handling

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 24fbf9ac534..a1d3b4fa918 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -20,7 +20,6 @@
  */
 
 #include "comfy/comfy.h"
-#include "graphics/framelimiter.h"
 #include "comfy/detection.h"
 #include "comfy/console.h"
 #include "common/scummsys.h"
@@ -53,46 +52,116 @@ Common::String ComfyEngine::getGameId() const {
 }
 
 Common::Error ComfyEngine::run() {
-	// Initialize 320x200 paletted graphics mode
-	initGraphics(320, 200);
-	_screen = new Graphics::Screen();
+	initGraphics(COMFY_SCREEN_WIDTH, COMFY_SCREEN_HEIGHT);
+	_screen = new Graphics::Screen(COMFY_SCREEN_WIDTH, COMFY_SCREEN_HEIGHT);
+	_screen->clear(0);
+	_screen->update();
 
-	// Set the engine's debugger console
 	setDebugger(new Console());
 
-	// If a savegame was selected from the launcher, load it
 	int saveSlot = ConfMan.getInt("save_slot");
 	if (saveSlot != -1)
 		(void)loadGameState(saveSlot);
 
-	// Draw a series of boxes on screen as a sample
-	for (int i = 0; i < 100; ++i)
-		_screen->frameRect(Common::Rect(i, i, 320 - i, 200 - i), i);
-	_screen->update();
+	gameMainLoop();
+	return Common::kNoError;
+}
 
-	// Simple event handling loop
-	byte pal[256 * 3] = { 0 };
-	Common::Event e;
-	int offset = 0;
+void ComfyEngine::gameMainLoop() {
+	uint32 previousMillis = _system->getMillis();
+	uint64 pitAccumulator = 0;
+	uint64 pitThreshold = uint64(COMFY_PIT_TIMER_DIVISOR) * 1000;
 
-	Graphics::FrameLimiter limiter(g_system, 60);
 	while (!shouldQuit()) {
-		while (g_system->getEventManager()->pollEvent(e)) {
+		processEvents();
+		if (shouldQuit())
+			break;
+
+		uint32 currentMillis = _system->getMillis();
+		pitAccumulator += uint64(currentMillis - previousMillis) * COMFY_PIT_INPUT_FREQUENCY;
+		previousMillis = currentMillis;
+
+		while (pitAccumulator >= pitThreshold && !shouldQuit()) {
+			pitAccumulator -= pitThreshold;
+			gameMainLoopTick();
 		}
 
-		// Cycle through a simple palette
-		++offset;
-		for (int i = 0; i < 256; ++i)
-			pal[i * 3 + 1] = (i + offset) % 256;
-		g_system->getPaletteManager()->setPalette(pal, 0, 256);
-		// Delay for a bit. All events loops should have a delay
-		// to prevent the system being unduly loaded
-		limiter.delayBeforeSwap();
-		_screen->update();
-		limiter.startFrame();
+		if (!shouldQuit() && pitAccumulator < pitThreshold)
+			waitForTimerTick(pitAccumulator);
 	}
+}
 
-	return Common::kNoError;
+void ComfyEngine::waitForTimerTick(uint64 pitAccumulator) {
+	uint64 pitThreshold = uint64(COMFY_PIT_TIMER_DIVISOR) * 1000;
+	uint64 remaining = pitThreshold - pitAccumulator;
+	uint32 delay = (remaining + COMFY_PIT_INPUT_FREQUENCY - 1) / COMFY_PIT_INPUT_FREQUENCY;
+
+	if (delay != 0)
+		_system->delayMillis(delay);
+}
+
+void ComfyEngine::processEvents() {
+	Common::Event event;
+
+	while (_system->getEventManager()->pollEvent(event)) {
+	}
+}
+
+void ComfyEngine::gameMainLoopTick() {
+	uint16 ticks = timerTick();
+
+	midiTrackTickAndRemove();
+	animFileTickCommands();
+	sceneTickEvent();
+	midiPollChannels(ticks);
+	paletteFadeStep(ticks);
+	lptKeyboardScanAndProcess();
+	actorTickTree();
+	renderFrame();
+	processInput();
+	processMusicEvents();
+	processSceneTransition();
+}
+
+uint16 ComfyEngine::timerTick() {
+	return 1;
+}
+
+void ComfyEngine::midiTrackTickAndRemove() {
+}
+
+void ComfyEngine::animFileTickCommands() {
+}
+
+void ComfyEngine::sceneTickEvent() {
+}
+
+void ComfyEngine::midiPollChannels(uint16 ticks) {
+	(void)ticks;
+}
+
+void ComfyEngine::paletteFadeStep(uint16 ticks) {
+	(void)ticks;
+}
+
+void ComfyEngine::lptKeyboardScanAndProcess() {
+}
+
+void ComfyEngine::actorTickTree() {
+}
+
+void ComfyEngine::renderFrame() {
+	_screen->makeAllDirty();
+	_screen->update();
+}
+
+void ComfyEngine::processInput() {
+}
+
+void ComfyEngine::processMusicEvents() {
+}
+
+void ComfyEngine::processSceneTransition() {
 }
 
 Common::Error ComfyEngine::syncGame(Common::Serializer &s) {
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 6c4efca8243..7c2001fd210 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -36,6 +36,11 @@
 
 #include "comfy/detection.h"
 
+#define COMFY_SCREEN_WIDTH 320
+#define COMFY_SCREEN_HEIGHT 200
+#define COMFY_PIT_INPUT_FREQUENCY 1193182
+#define COMFY_PIT_TIMER_DIVISOR 0x2E9B
+
 namespace Comfy {
 
 struct ComfyGameDescription;
@@ -44,11 +49,30 @@ class ComfyEngine : public Engine {
 private:
 	const ADGameDescription *_gameDescription;
 	Common::RandomSource _randomSource;
+	Graphics::Screen *_screen;
+
+	void gameMainLoop();
+	void gameMainLoopTick();
+	void waitForTimerTick(uint64 pitAccumulator);
+	void processEvents();
+
+	uint16 timerTick();
+	void midiTrackTickAndRemove();
+	void animFileTickCommands();
+	void sceneTickEvent();
+	void midiPollChannels(uint16 ticks);
+	void paletteFadeStep(uint16 ticks);
+	void lptKeyboardScanAndProcess();
+	void actorTickTree();
+	void renderFrame();
+	void processInput();
+	void processMusicEvents();
+	void processSceneTransition();
+
 protected:
 	// Engine APIs
 	Common::Error run() override;
-public:
-	Graphics::Screen *_screen = nullptr;
+
 public:
 	ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc);
 	~ComfyEngine() override;


Commit: 6785c992ab8a60b7fbd84c527cb449cf182d8563
    https://github.com/scummvm/scummvm/commit/6785c992ab8a60b7fbd84c527cb449cf182d8563
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Continue adding PIT stuff

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index a1d3b4fa918..52e6e8cee32 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -35,12 +35,15 @@ namespace Comfy {
 ComfyEngine *g_engine;
 
 ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Engine(syst),
-	_gameDescription(gameDesc), _randomSource("Comfy") {
+	_gameDescription(gameDesc), _randomSource("Comfy"), _screen(nullptr),
+	_logicalScreenWidth(COMFY_SCREEN_WIDTH), _logicalScreenHeight(COMFY_SCREEN_HEIGHT),
+	_timerLastMillis(0), _pitAccumulator(0), _gameInitialized(false), _videoInitialized(false),
+	_timerInitialized(false), _lptKeyboardInitialized(false), _mainLoopRunning(false) {
 	g_engine = this;
 }
 
 ComfyEngine::~ComfyEngine() {
-	delete _screen;
+	gameShutdown();
 }
 
 uint32 ComfyEngine::getFeatures() const {
@@ -52,48 +55,113 @@ Common::String ComfyEngine::getGameId() const {
 }
 
 Common::Error ComfyEngine::run() {
-	initGraphics(COMFY_SCREEN_WIDTH, COMFY_SCREEN_HEIGHT);
-	_screen = new Graphics::Screen(COMFY_SCREEN_WIDTH, COMFY_SCREEN_HEIGHT);
-	_screen->clear(0);
-	_screen->update();
-
 	setDebugger(new Console());
 
+	Common::Error result = gameInit();
+	if (result.getCode() != Common::kNoError)
+		return result;
+
 	int saveSlot = ConfMan.getInt("save_slot");
 	if (saveSlot != -1)
 		(void)loadGameState(saveSlot);
 
 	gameMainLoop();
+	gameShutdown();
+	return Common::kNoError;
+}
+
+Common::Error ComfyEngine::gameInit() {
+	if (_gameInitialized)
+		return Common::kNoError;
+
+	videoInit();
+	timerInit();
+	lptKeyboardInit();
+	_gameInitialized = true;
 	return Common::kNoError;
 }
 
+void ComfyEngine::gameShutdown() {
+	if (_lptKeyboardInitialized)
+		lptKeyboardShutdown();
+
+	if (_timerInitialized)
+		timerShutdown();
+
+	if (_videoInitialized)
+		videoShutdown();
+
+	_mainLoopRunning = false;
+	_gameInitialized = false;
+}
+
+void ComfyEngine::videoInit() {
+	if (_videoInitialized)
+		return;
+
+	initGraphics(_logicalScreenWidth, _logicalScreenHeight);
+	_screen = new Graphics::Screen(_logicalScreenWidth, _logicalScreenHeight);
+	_screen->clear(0);
+	_screen->update();
+	_videoInitialized = true;
+}
+
+void ComfyEngine::videoShutdown() {
+	delete _screen;
+	_screen = nullptr;
+	_videoInitialized = false;
+}
+
+void ComfyEngine::timerInit() {
+	if (_timerInitialized)
+		return;
+
+	_timerLastMillis = _system->getMillis();
+	_pitAccumulator = 0;
+	_timerInitialized = true;
+}
+
+void ComfyEngine::timerShutdown() {
+	_timerLastMillis = 0;
+	_pitAccumulator = 0;
+	_timerInitialized = false;
+}
+
+void ComfyEngine::lptKeyboardInit() {
+	_lptKeyboardInitialized = true;
+}
+
+void ComfyEngine::lptKeyboardShutdown() {
+	_lptKeyboardInitialized = false;
+}
+
 void ComfyEngine::gameMainLoop() {
-	uint32 previousMillis = _system->getMillis();
-	uint64 pitAccumulator = 0;
-	uint64 pitThreshold = uint64(COMFY_PIT_TIMER_DIVISOR) * 1000;
+	_mainLoopRunning = true;
 
-	while (!shouldQuit()) {
+	while (_mainLoopRunning && !shouldQuit()) {
 		processEvents();
 		if (shouldQuit())
 			break;
 
 		uint32 currentMillis = _system->getMillis();
-		pitAccumulator += uint64(currentMillis - previousMillis) * COMFY_PIT_INPUT_FREQUENCY;
-		previousMillis = currentMillis;
+		_pitAccumulator += uint64(currentMillis - _timerLastMillis) * COMFY_PIT_INPUT_FREQUENCY;
+		_timerLastMillis = currentMillis;
 
-		while (pitAccumulator >= pitThreshold && !shouldQuit()) {
-			pitAccumulator -= pitThreshold;
+		while (_pitAccumulator >= uint64(COMFY_PIT_TIMER_DIVISOR) * 1000 && !shouldQuit()) {
+			_pitAccumulator -= uint64(COMFY_PIT_TIMER_DIVISOR) * 1000;
 			gameMainLoopTick();
 		}
 
-		if (!shouldQuit() && pitAccumulator < pitThreshold)
-			waitForTimerTick(pitAccumulator);
+		if (!shouldQuit() && _pitAccumulator < uint64(COMFY_PIT_TIMER_DIVISOR) * 1000)
+			waitForTimerTick();
 	}
+
+	_mainLoopRunning = false;
 }
 
-void ComfyEngine::waitForTimerTick(uint64 pitAccumulator) {
+void ComfyEngine::waitForTimerTick() {
 	uint64 pitThreshold = uint64(COMFY_PIT_TIMER_DIVISOR) * 1000;
-	uint64 remaining = pitThreshold - pitAccumulator;
+	uint64 remaining = pitThreshold - _pitAccumulator;
 	uint32 delay = (remaining + COMFY_PIT_INPUT_FREQUENCY - 1) / COMFY_PIT_INPUT_FREQUENCY;
 
 	if (delay != 0)
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 7c2001fd210..4fcd8e26238 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -50,10 +50,27 @@ private:
 	const ADGameDescription *_gameDescription;
 	Common::RandomSource _randomSource;
 	Graphics::Screen *_screen;
-
+	uint16 _logicalScreenWidth;
+	uint16 _logicalScreenHeight;
+	uint32 _timerLastMillis;
+	uint64 _pitAccumulator;
+	bool _gameInitialized;
+	bool _videoInitialized;
+	bool _timerInitialized;
+	bool _lptKeyboardInitialized;
+	bool _mainLoopRunning;
+
+	Common::Error gameInit();
+	void gameShutdown();
+	void videoInit();
+	void videoShutdown();
+	void timerInit();
+	void timerShutdown();
+	void lptKeyboardInit();
+	void lptKeyboardShutdown();
 	void gameMainLoop();
 	void gameMainLoopTick();
-	void waitForTimerTick(uint64 pitAccumulator);
+	void waitForTimerTick();
 	void processEvents();
 
 	uint16 timerTick();


Commit: 711de8da647b1e75ed0e3102882377aecd65335a
    https://github.com/scummvm/scummvm/commit/711de8da647b1e75ed0e3102882377aecd65335a
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Add all known detection entries

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/detection.cpp
    engines/comfy/detection_tables.h


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 52e6e8cee32..897ba9628a3 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -34,9 +34,26 @@ namespace Comfy {
 
 ComfyEngine *g_engine;
 
+static ComfyEngineVersion getEngineVersion(const ADGameDescription *gameDesc) {
+	if (!strcmp(gameDesc->gameId, "comfyland")) {
+		if (gameDesc->extra && !strcmp(gameDesc->extra, "1999"))
+			return kEngineVersion3;
+
+		return kEngineVersion1;
+	}
+
+	if (!strcmp(gameDesc->gameId, "boo") || !strcmp(gameDesc->gameId, "first") ||
+			!strcmp(gameDesc->gameId, "panther"))
+		return kEngineVersion2;
+
+	return kEngineVersion3;
+}
+
 ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Engine(syst),
-	_gameDescription(gameDesc), _randomSource("Comfy"), _screen(nullptr),
-	_logicalScreenWidth(COMFY_SCREEN_WIDTH), _logicalScreenHeight(COMFY_SCREEN_HEIGHT),
+	_gameDescription(gameDesc), _engineVersion(getEngineVersion(gameDesc)),
+	_randomSource("Comfy"), _screen(nullptr),
+	_logicalScreenWidth(!strcmp(gameDesc->gameId, "panther") ? COMFY_PANTHER_SCREEN_WIDTH : COMFY_SCREEN_WIDTH),
+	_logicalScreenHeight(!strcmp(gameDesc->gameId, "panther") ? COMFY_PANTHER_SCREEN_HEIGHT : COMFY_SCREEN_HEIGHT),
 	_timerLastMillis(0), _pitAccumulator(0), _gameInitialized(false), _videoInitialized(false),
 	_timerInitialized(false), _lptKeyboardInitialized(false), _mainLoopRunning(false) {
 	g_engine = this;
@@ -46,10 +63,6 @@ ComfyEngine::~ComfyEngine() {
 	gameShutdown();
 }
 
-uint32 ComfyEngine::getFeatures() const {
-	return _gameDescription->flags;
-}
-
 Common::String ComfyEngine::getGameId() const {
 	return _gameDescription->gameId;
 }
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 4fcd8e26238..46cc3ccc584 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -38,16 +38,23 @@
 
 #define COMFY_SCREEN_WIDTH 320
 #define COMFY_SCREEN_HEIGHT 200
+#define COMFY_PANTHER_SCREEN_WIDTH 640
+#define COMFY_PANTHER_SCREEN_HEIGHT 480
 #define COMFY_PIT_INPUT_FREQUENCY 1193182
 #define COMFY_PIT_TIMER_DIVISOR 0x2E9B
 
 namespace Comfy {
 
-struct ComfyGameDescription;
+enum ComfyEngineVersion {
+	kEngineVersion1, // 1994-1995
+	kEngineVersion2, // 1996-1997
+	kEngineVersion3  // 1999
+};
 
 class ComfyEngine : public Engine {
 private:
 	const ADGameDescription *_gameDescription;
+	ComfyEngineVersion _engineVersion;
 	Common::RandomSource _randomSource;
 	Graphics::Screen *_screen;
 	uint16 _logicalScreenWidth;
@@ -94,8 +101,6 @@ public:
 	ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc);
 	~ComfyEngine() override;
 
-	uint32 getFeatures() const;
-
 	/**
 	 * Returns the game Id
 	 */
diff --git a/engines/comfy/detection.cpp b/engines/comfy/detection.cpp
index 5f1b061d04b..0c8c8665981 100644
--- a/engines/comfy/detection.cpp
+++ b/engines/comfy/detection.cpp
@@ -39,8 +39,15 @@ const DebugChannelDef ComfyMetaEngineDetection::debugFlagList[] = {
 };
 
 static const char *const directoryGlobs[] = {
-	"SETLANG",
+	"BOO",
+	"COLORS",
+	"COMFY1",
+	"CONCERT",
 	"ENGLISH",
+	"FIRST",
+	"FRIENDS",
+	"MATCH",
+	"PANTHER",
 	nullptr
 };
 
diff --git a/engines/comfy/detection_tables.h b/engines/comfy/detection_tables.h
index 1f790140517..370c782ca80 100644
--- a/engines/comfy/detection_tables.h
+++ b/engines/comfy/detection_tables.h
@@ -22,7 +22,14 @@
 namespace Comfy {
 
 const PlainGameDescriptor comfyGames[] = {
-	{ "comfyland", "Comfy Land" },
+	{ "comfyland", "ComfyLand" },
+	{ "boo", "Didi and Boo" },
+	{ "first", "The First Step" },
+	{ "match", "A Purrfect Match" },
+	{ "colors", "Colorful Adventures" },
+	{ "concert", "The Great Concert" },
+	{ "friends", "Playground of Friends" },
+	{ "panther", "The Pink Panther's House of Numbers" },
 	{ 0, 0 }
 };
 
@@ -30,13 +37,107 @@ const ADGameDescription gameDescriptions[] = {
 	{
 		"comfyland",
 		nullptr,
-		{
-			{"ENGLISH/COMFY.OBJ", 0, "7b4ce03e92a27c2271d3657d3c13084b", 221184},
-			{"SETLANG/PICFILE.DAT", 0, "88dbbc127cd269b286f4d8c0adad0f1b", 29789},
-			AD_LISTEND
-		},
-		Common::EN_ANY,
-		Common::kPlatformDOS,
+		AD_ENTRY3s("COMFY1/ENGLISH/COMFY.OBJ",    "7b4ce03e92a27c2271d3657d3c13084b", 221184,
+				   "COMFY1/ENGLISH/MIDIFILE.DAT", "fddbb3593b2c2df638fac22626b890cf", 530316,
+				   "INTRO/COMFY.OBJ",             "b8fb0c9d325ec4db8ce37ef0d08da130", 4096),
+		Common::UNK_LANG,
+		Common::kPlatformWindows,
+		ADGF_UNSTABLE,
+		GUIO1(GUIO_NONE)
+	},
+
+	{
+		"comfyland",
+		"1999",
+		AD_ENTRY5s("COMFY1/ENGLISH/COMFY.OBJ",    "8bbeefa3c59c8e80046f35a9202f6095", 221184,
+				   "COMFY1/ENGLISH/MIDIFILE.DAT", "fddbb3593b2c2df638fac22626b890cf", 530316,
+				   "COMFY1/ENGLISH/ANMFILE.DAT",  "46f4fa67879827e706dc9f4d2eaad3aa", 20,
+				   "INTRO/COMFY.OBJ",             "b8fb0c9d325ec4db8ce37ef0d08da130", 4096,
+				   "KEYBOARD.DAT",                "08abb613ff84fa5347c7dff9128d83e2", 61),
+		Common::UNK_LANG,
+		Common::kPlatformWindows,
+		ADGF_UNSTABLE,
+		GUIO1(GUIO_NONE)
+	},
+
+	{
+		"boo",
+		nullptr,
+		AD_ENTRY3s("BOO/ENGLISH/COMFY.OBJ",    "5d847524a1e1cfce9799a31acca777f3", 301056,
+				   "BOO/ENGLISH/MIDIFILE.DAT", "1fe05885c32470022de11639de4f532f", 141282,
+				   "BOO/ENGLISH/ANMFILE.DAT",  "cbd26fc45b5263ee47e4bffd1bfd00ef", 21219438),
+		Common::UNK_LANG,
+		Common::kPlatformWindows,
+		ADGF_UNSTABLE,
+		GUIO1(GUIO_NONE)
+	},
+
+	{
+		"first",
+		nullptr,
+		AD_ENTRY2s("FIRST/ENGLISH/COMFY.OBJ",    "c187ac3fd5d547f59ff18b98a6a2f10b", 43008,
+				   "FIRST/ENGLISH/MIDIFILE.DAT", "4ab6c35308ed504a8abb96ae3fe81fe4", 1232),
+		Common::UNK_LANG,
+		Common::kPlatformWindows,
+		ADGF_UNSTABLE,
+		GUIO1(GUIO_NONE)
+	},
+
+	{
+		"match",
+		nullptr,
+		AD_ENTRY2s("MATCH/ENGLISH/COMFY.OBJ",    "daf2c1e6d3bc019f026edbe5465df13b", 337920,
+				   "MATCH/ENGLISH/MIDIFILE.DAT", "253d28e78576b2564f60588e2afa1d66", 2640),
+		Common::UNK_LANG,
+		Common::kPlatformWindows,
+		ADGF_UNSTABLE,
+		GUIO1(GUIO_NONE)
+	},
+
+	{
+		"colors",
+		nullptr,
+		AD_ENTRY3s("COLORS/ENGLISH/COMFY.OBJ",    "6679b5e35db4c4312d4cb85076403760", 268288,
+				   "COLORS/ENGLISH/MIDIFILE.DAT", "aac1bd8350dcbc0b6c2e9dd9a7f25ba4", 289982,
+				   "COLORS/ENGLISH/ANMFILE.DAT",  "46f4fa67879827e706dc9f4d2eaad3aa", 20),
+		Common::UNK_LANG,
+		Common::kPlatformWindows,
+		ADGF_UNSTABLE,
+		GUIO1(GUIO_NONE)
+	},
+
+	{
+		"concert",
+		nullptr,
+		AD_ENTRY3s("CONCERT/ENGLISH/COMFY.OBJ",    "c060145864e951fc13ba6106e75f4845", 272384,
+				   "CONCERT/ENGLISH/MIDIFILE.DAT", "182ae9a4a3e49d3f9230c274f9828fdf", 598593,
+				   "CONCERT/ENGLISH/ANMFILE.DAT",  "46f4fa67879827e706dc9f4d2eaad3aa", 20),
+		Common::UNK_LANG,
+		Common::kPlatformWindows,
+		ADGF_UNSTABLE,
+		GUIO1(GUIO_NONE)
+	},
+
+	{
+		"friends",
+		nullptr,
+		AD_ENTRY3s("FRIENDS/ENGLISH/COMFY.OBJ",    "d4c620ba375834094b4151ebef862647", 364544,
+				   "FRIENDS/ENGLISH/MIDIFILE.DAT", "20992cb6b10be823262301ea36253ab8", 239443,
+				   "FRIENDS/ENGLISH/ANMFILE.DAT",  "46f4fa67879827e706dc9f4d2eaad3aa", 20),
+		Common::UNK_LANG,
+		Common::kPlatformWindows,
+		ADGF_UNSTABLE,
+		GUIO1(GUIO_NONE)
+	},
+
+	{
+		"panther",
+		nullptr,
+		AD_ENTRY3s("PANTHER/ENGLISH/COMFY.OBJ",    "05420f4122187233112a9dc374303c15", 65536,
+				   "PANTHER/ENGLISH/MIDIFILE.DAT", "8cbbbbb2ebfc96e6a69a87f010f393e8", 51028,
+				   "PANTHER/ENGLISH/ANMFILE.DAT",  "93ad11d4236610ff946f8a8c320b89a1", 135664335),
+		Common::UNK_LANG,
+		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
 		GUIO1(GUIO_NONE)
 	},


Commit: 2ab5331e5d86045e9ebf2494656441bedb6523fa
    https://github.com/scummvm/scummvm/commit/2ab5331e5d86045e9ebf2494656441bedb6523fa
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Add internal multilang handling and part of the INI code

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/game.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 897ba9628a3..bf3874b97a5 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -51,6 +51,7 @@ static ComfyEngineVersion getEngineVersion(const ADGameDescription *gameDesc) {
 
 ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Engine(syst),
 	_gameDescription(gameDesc), _engineVersion(getEngineVersion(gameDesc)),
+	_language(2), _multiLanguage(true),
 	_randomSource("Comfy"), _screen(nullptr),
 	_logicalScreenWidth(!strcmp(gameDesc->gameId, "panther") ? COMFY_PANTHER_SCREEN_WIDTH : COMFY_SCREEN_WIDTH),
 	_logicalScreenHeight(!strcmp(gameDesc->gameId, "panther") ? COMFY_PANTHER_SCREEN_HEIGHT : COMFY_SCREEN_HEIGHT),
@@ -87,6 +88,10 @@ Common::Error ComfyEngine::gameInit() {
 	if (_gameInitialized)
 		return Common::kNoError;
 
+	gameConfigInit();
+	if (!iniReadGameConfig())
+		return Common::kNoGameDataFoundError;
+
 	videoInit();
 	timerInit();
 	lptKeyboardInit();
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 46cc3ccc584..63b890fa671 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -25,6 +25,7 @@
 #include "common/scummsys.h"
 #include "common/system.h"
 #include "common/error.h"
+#include "common/file.h"
 #include "common/fs.h"
 #include "common/hash-str.h"
 #include "common/random.h"
@@ -55,6 +56,12 @@ class ComfyEngine : public Engine {
 private:
 	const ADGameDescription *_gameDescription;
 	ComfyEngineVersion _engineVersion;
+	Common::Path _gameDirectory;
+	Common::Path _introDirectory;
+	Common::Path _gameDataPath;
+	Common::Path _languageDirectories[16];
+	uint16 _language;
+	bool _multiLanguage;
 	Common::RandomSource _randomSource;
 	Graphics::Screen *_screen;
 	uint16 _logicalScreenWidth;
@@ -69,6 +76,15 @@ private:
 
 	Common::Error gameInit();
 	void gameShutdown();
+	void gameConfigInit();
+	void findLanguageDirectories();
+	bool iniReadGameConfig();
+	bool iniGetGameDataPath(uint16 sceneId);
+	void iniWriteLanguage(uint16 language);
+	Common::Path getLanguageDirectory(uint16 language);
+	void pathSetGameDataDir(const Common::Path &path);
+	Common::Path pathBuild(const Common::Path &filename, bool useGamePath);
+	Common::SeekableReadStream *pathFOpen(const Common::Path &filename, bool useGamePath);
 	void videoInit();
 	void videoShutdown();
 	void timerInit();
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index 409cdeb90bd..a485a2a776d 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -19,7 +19,180 @@
  *
  */
 
+#include "comfy/comfy.h"
+
+#include "common/config-manager.h"
+
 namespace Comfy {
 
+static uint16 getLanguageId(const Common::String &directory) {
+	if (directory.equalsIgnoreCase("HEBREW"))
+		return 1;
+
+	if (directory.equalsIgnoreCase("ENGLISH"))
+		return 2;
+
+	if (directory.equalsIgnoreCase("GERMAN"))
+		return 3;
+
+	if (directory.equalsIgnoreCase("FRENCH"))
+		return 4;
+
+	if (directory.equalsIgnoreCase("SPANISH"))
+		return 5;
+
+	if (directory.equalsIgnoreCase("DUTCH"))
+		return 6;
+
+	if (directory.equalsIgnoreCase("PORTUGES"))
+		return 7;
+
+	if (directory.equalsIgnoreCase("ENGUK"))
+		return 8;
+
+	if (directory.equalsIgnoreCase("ITALIAN"))
+		return 9;
+
+	if (directory.equalsIgnoreCase("DANISH"))
+		return 10;
+
+	if (directory.equalsIgnoreCase("NORWEGIA"))
+		return 11;
+
+	if (directory.equalsIgnoreCase("SWEDISH"))
+		return 12;
+
+	if (directory.equalsIgnoreCase("JAPANESE"))
+		return 14;
+
+	if (directory.equalsIgnoreCase("TURKISH"))
+		return 15;
+
+	return 0;
+}
+
+void ComfyEngine::gameConfigInit() {
+	if (!strcmp(_gameDescription->gameId, "comfyland")) {
+		_gameDirectory = Common::Path("COMFY1");
+		_introDirectory = Common::Path("INTRO");
+	} else if (!strcmp(_gameDescription->gameId, "boo")) {
+		_gameDirectory = Common::Path("BOO");
+		_introDirectory = Common::Path("FINTRO");
+	} else if (!strcmp(_gameDescription->gameId, "first")) {
+		_gameDirectory = Common::Path("FIRST");
+		_introDirectory = Common::Path("FINTRO");
+	} else if (!strcmp(_gameDescription->gameId, "match")) {
+		_gameDirectory = Common::Path("MATCH");
+		_introDirectory = Common::Path("MINTRO");
+	} else if (!strcmp(_gameDescription->gameId, "colors")) {
+		_gameDirectory = Common::Path("COLORS");
+		_introDirectory = Common::Path("FINTRO");
+	} else if (!strcmp(_gameDescription->gameId, "concert")) {
+		_gameDirectory = Common::Path("CONCERT");
+		_introDirectory = Common::Path("INTRO");
+	} else if (!strcmp(_gameDescription->gameId, "friends")) {
+		_gameDirectory = Common::Path("FRIENDS");
+		_introDirectory = Common::Path("FINTRO");
+	} else if (!strcmp(_gameDescription->gameId, "panther")) {
+		_gameDirectory = Common::Path("PANTHER");
+		_introDirectory = Common::Path("MINTRO");
+	}
+
+	findLanguageDirectories();
+	ConfMan.registerDefault("comfy_language", 2);
+}
+
+void ComfyEngine::findLanguageDirectories() {
+	for (uint i = 0; i < ARRAYSIZE(_languageDirectories); i++)
+		_languageDirectories[i] = Common::Path();
+
+	Common::FSNode root(ConfMan.getPath("path"));
+	Common::FSList gameDirectories;
+	if (!root.getChildren(gameDirectories, Common::FSNode::kListDirectoriesOnly))
+		return;
+
+	Common::FSNode gameDirectory;
+	for (Common::FSList::iterator it = gameDirectories.begin(); it != gameDirectories.end(); it++) {
+		if (it->getName().equalsIgnoreCase(_gameDirectory.toString())) {
+			gameDirectory = *it;
+			break;
+		}
+	}
+
+	if (!gameDirectory.exists())
+		return;
+
+	Common::FSList directories;
+	if (!gameDirectory.getChildren(directories, Common::FSNode::kListDirectoriesOnly))
+		return;
+
+	for (Common::FSList::iterator it = directories.begin(); it != directories.end(); it++) {
+		uint16 language = getLanguageId(it->getName());
+		if (language)
+			_languageDirectories[language] = Common::Path(it->getName());
+	}
+}
+
+bool ComfyEngine::iniReadGameConfig() {
+	_language = ConfMan.getInt("comfy_language");
+	_multiLanguage = true;
+	return !_gameDirectory.empty();
+}
+
+bool ComfyEngine::iniGetGameDataPath(uint16 sceneId) {
+	if (sceneId == 0) {
+		if (_introDirectory.empty())
+			return false;
+
+		pathSetGameDataDir(_introDirectory);
+		return true;
+	}
+
+	if (sceneId == 0x63) {
+		pathSetGameDataDir(_gameDirectory.join("SETLANG"));
+		return true;
+	}
+
+	Common::Path languageDirectory = getLanguageDirectory(sceneId);
+	if (languageDirectory.empty())
+		return false;
+
+	pathSetGameDataDir(_gameDirectory.join(languageDirectory));
+	return true;
+}
+
+void ComfyEngine::iniWriteLanguage(uint16 language) {
+	_language = language;
+	ConfMan.setInt("comfy_language", language);
+	ConfMan.flushToDisk();
+}
+
+Common::Path ComfyEngine::getLanguageDirectory(uint16 language) {
+	if (language >= ARRAYSIZE(_languageDirectories))
+		return Common::Path();
+
+	return _languageDirectories[language];
+}
+
+void ComfyEngine::pathSetGameDataDir(const Common::Path &path) {
+	_gameDataPath = path;
+}
+
+Common::Path ComfyEngine::pathBuild(const Common::Path &filename, bool useGamePath) {
+	if (useGamePath && !_gameDataPath.empty())
+		return _gameDataPath.join(filename);
+
+	return filename;
+}
+
+Common::SeekableReadStream *ComfyEngine::pathFOpen(const Common::Path &filename, bool useGamePath) {
+	Common::File *file = new Common::File();
+	if (!file->open(pathBuild(filename, useGamePath))) {
+		delete file;
+		return nullptr;
+	}
+
+	return file;
+}
 
 } // End of namespace Comfy


Commit: b360a20c72a161e7c1f487c408e39550c80acec2
    https://github.com/scummvm/scummvm/commit/b360a20c72a161e7c1f487c408e39550c80acec2
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Insert some GFX and Palette funcs

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/game.cpp
    engines/comfy/palette.cpp
    engines/comfy/video.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index bf3874b97a5..8d8c777280c 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -52,11 +52,18 @@ static ComfyEngineVersion getEngineVersion(const ADGameDescription *gameDesc) {
 ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Engine(syst),
 	_gameDescription(gameDesc), _engineVersion(getEngineVersion(gameDesc)),
 	_language(2), _multiLanguage(true),
-	_randomSource("Comfy"), _screen(nullptr),
+	_randomSource("Comfy"), _screen(nullptr), _framebufPtr(nullptr), _presentBuffer(nullptr),
 	_logicalScreenWidth(!strcmp(gameDesc->gameId, "panther") ? COMFY_PANTHER_SCREEN_WIDTH : COMFY_SCREEN_WIDTH),
 	_logicalScreenHeight(!strcmp(gameDesc->gameId, "panther") ? COMFY_PANTHER_SCREEN_HEIGHT : COMFY_SCREEN_HEIGHT),
+	_resolutionChangeCount(0), _renderDirtyCount(0), _renderInterleaved(false),
+	_colorDatStream(nullptr), _paletteDataPtr(nullptr), _vsyncPending(0), _fadeMax(0), _fadeStep(0),
+	_palettePage(0), _paletteFading(false),
 	_timerLastMillis(0), _pitAccumulator(0), _gameInitialized(false), _videoInitialized(false),
 	_timerInitialized(false), _lptKeyboardInitialized(false), _mainLoopRunning(false) {
+	memset(_paletteFadeSource, 0, sizeof(_paletteFadeSource));
+	memset(_paletteTarget, 0, sizeof(_paletteTarget));
+	memset(_paletteDisplay, 0, sizeof(_paletteDisplay));
+	memset(_logicalPalette, 0, sizeof(_logicalPalette));
 	g_engine = this;
 }
 
@@ -113,23 +120,6 @@ void ComfyEngine::gameShutdown() {
 	_gameInitialized = false;
 }
 
-void ComfyEngine::videoInit() {
-	if (_videoInitialized)
-		return;
-
-	initGraphics(_logicalScreenWidth, _logicalScreenHeight);
-	_screen = new Graphics::Screen(_logicalScreenWidth, _logicalScreenHeight);
-	_screen->clear(0);
-	_screen->update();
-	_videoInitialized = true;
-}
-
-void ComfyEngine::videoShutdown() {
-	delete _screen;
-	_screen = nullptr;
-	_videoInitialized = false;
-}
-
 void ComfyEngine::timerInit() {
 	if (_timerInitialized)
 		return;
@@ -203,6 +193,7 @@ void ComfyEngine::gameMainLoopTick() {
 	paletteFadeStep(ticks);
 	lptKeyboardScanAndProcess();
 	actorTickTree();
+	paletteVsyncFlip();
 	renderFrame();
 	processInput();
 	processMusicEvents();
@@ -226,10 +217,6 @@ void ComfyEngine::midiPollChannels(uint16 ticks) {
 	(void)ticks;
 }
 
-void ComfyEngine::paletteFadeStep(uint16 ticks) {
-	(void)ticks;
-}
-
 void ComfyEngine::lptKeyboardScanAndProcess() {
 }
 
@@ -237,8 +224,7 @@ void ComfyEngine::actorTickTree() {
 }
 
 void ComfyEngine::renderFrame() {
-	_screen->makeAllDirty();
-	_screen->update();
+	videoPresentFrame();
 }
 
 void ComfyEngine::processInput() {
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 63b890fa671..b8471c516dc 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -43,6 +43,8 @@
 #define COMFY_PANTHER_SCREEN_HEIGHT 480
 #define COMFY_PIT_INPUT_FREQUENCY 1193182
 #define COMFY_PIT_TIMER_DIVISOR 0x2E9B
+#define COMFY_RESOLUTION_CHANGE_CAPACITY 100
+#define COMFY_PALETTE_BYTES 0x300
 
 namespace Comfy {
 
@@ -54,6 +56,14 @@ enum ComfyEngineVersion {
 
 class ComfyEngine : public Engine {
 private:
+	struct VideoRectRecord {
+		int16 left;
+		int16 top;
+		int16 right;
+		int16 bottom;
+		uint16 area;
+	};
+
 	const ADGameDescription *_gameDescription;
 	ComfyEngineVersion _engineVersion;
 	Common::Path _gameDirectory;
@@ -64,8 +74,25 @@ private:
 	bool _multiLanguage;
 	Common::RandomSource _randomSource;
 	Graphics::Screen *_screen;
+	byte *_framebufPtr;
+	byte *_presentBuffer;
 	uint16 _logicalScreenWidth;
 	uint16 _logicalScreenHeight;
+	VideoRectRecord _resolutionChanges[COMFY_RESOLUTION_CHANGE_CAPACITY];
+	uint16 _resolutionChangeCount;
+	uint16 _renderDirtyCount;
+	bool _renderInterleaved;
+	Common::SeekableReadStream *_colorDatStream;
+	byte _paletteFadeSource[COMFY_PALETTE_BYTES];
+	byte _paletteTarget[COMFY_PALETTE_BYTES];
+	byte _paletteDisplay[COMFY_PALETTE_BYTES];
+	byte _logicalPalette[256 * 4];
+	byte *_paletteDataPtr;
+	uint16 _vsyncPending;
+	uint16 _fadeMax;
+	uint16 _fadeStep;
+	byte _palettePage;
+	bool _paletteFading;
 	uint32 _timerLastMillis;
 	uint64 _pitAccumulator;
 	bool _gameInitialized;
@@ -87,6 +114,24 @@ private:
 	Common::SeekableReadStream *pathFOpen(const Common::Path &filename, bool useGamePath);
 	void videoInit();
 	void videoShutdown();
+	void videoSetResolution();
+	void videoFindBestMode(VideoRectRecord record);
+	void videoPresentFrame();
+	void renderSetDirty();
+	void renderFlushDirty();
+	void framebufCopyAll(byte *destination, byte *source);
+	void framebufClear(uint16 color);
+	uint32 framebufferBytes();
+	void colorDatOpen();
+	void colorDatClose();
+	void colorDatReadEntry(uint16 paletteId);
+	void vsyncSetPalettePtr(byte *palette);
+	void paletteInterpolate(uint16 step, uint16 maximum);
+	void paletteLoadWithFade(uint16 paletteId, uint16 fadeTicks);
+	void paletteApplyBrightness(uint16 brightness);
+	void paletteVsyncFlip();
+	void paletteConvertRgbToLogical(byte *source, byte *destination);
+	void paletteRealize(byte *rawPalette);
 	void timerInit();
 	void timerShutdown();
 	void lptKeyboardInit();
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index a485a2a776d..0cc46a0167b 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -100,9 +100,12 @@ void ComfyEngine::gameConfigInit() {
 
 	findLanguageDirectories();
 	ConfMan.registerDefault("comfy_language", 2);
+	ConfMan.registerDefault("comfy_screen_update_interleaved", false);
 }
 
 void ComfyEngine::findLanguageDirectories() {
+	uint languageCount = 0;
+	_multiLanguage = false;
 	for (uint i = 0; i < ARRAYSIZE(_languageDirectories); i++)
 		_languageDirectories[i] = Common::Path();
 
@@ -128,14 +131,18 @@ void ComfyEngine::findLanguageDirectories() {
 
 	for (Common::FSList::iterator it = directories.begin(); it != directories.end(); it++) {
 		uint16 language = getLanguageId(it->getName());
-		if (language)
+		if (language) {
 			_languageDirectories[language] = Common::Path(it->getName());
+			languageCount++;
+		}
 	}
+
+	_multiLanguage = languageCount > 1;
 }
 
 bool ComfyEngine::iniReadGameConfig() {
 	_language = ConfMan.getInt("comfy_language");
-	_multiLanguage = true;
+	_renderInterleaved = ConfMan.getBool("comfy_screen_update_interleaved");
 	return !_gameDirectory.empty();
 }
 
diff --git a/engines/comfy/palette.cpp b/engines/comfy/palette.cpp
index 409cdeb90bd..db98fcae6ba 100644
--- a/engines/comfy/palette.cpp
+++ b/engines/comfy/palette.cpp
@@ -19,7 +19,142 @@
  *
  */
 
+#include "comfy/comfy.h"
+
+#include "common/textconsole.h"
+#include "graphics/paletteman.h"
+
 namespace Comfy {
 
+void ComfyEngine::colorDatOpen() {
+	if (_colorDatStream)
+		return;
+
+	_colorDatStream = pathFOpen(Common::Path("COLORS.DAT"), true);
+	if (!_colorDatStream)
+		error("Could not open COLORS.DAT");
+}
+
+void ComfyEngine::colorDatClose() {
+	delete _colorDatStream;
+	_colorDatStream = nullptr;
+}
+
+void ComfyEngine::colorDatReadEntry(uint16 paletteId) {
+	colorDatOpen();
+	uint16 offset = uint16(paletteId * COMFY_PALETTE_BYTES);
+	if (!_colorDatStream->seek(offset))
+		error("Could not seek to palette %u in COLORS.DAT", uint(paletteId));
+
+	if (_colorDatStream->read(_paletteTarget, COMFY_PALETTE_BYTES) != COMFY_PALETTE_BYTES)
+		error("COLORS.DAT is truncated while reading palette %u", uint(paletteId));
+
+	if (_engineVersion == kEngineVersion3) {
+		// Version 3 forces color 0 to black immediately after reading the palette...
+		_paletteTarget[0] = 0;
+		_paletteTarget[1] = 0;
+		_paletteTarget[2] = 0;
+	}
+}
+
+void ComfyEngine::vsyncSetPalettePtr(byte *palette) {
+	_vsyncPending = 2;
+	_paletteDataPtr = palette;
+}
+
+void ComfyEngine::paletteInterpolate(uint16 step, uint16 maximum) {
+	if (!maximum)
+		return;
+
+	int16 remaining = int16(maximum - step);
+	for (uint i = 0; i < COMFY_PALETTE_BYTES; i++) {
+		int32 from = _paletteFadeSource[i];
+		int32 to = _paletteTarget[i];
+		_paletteDisplay[i] = byte((from * remaining + to * int16(step)) / int16(maximum));
+	}
+}
+
+void ComfyEngine::paletteFadeStep(uint16 delta) {
+	if (!_paletteFading)
+		return;
+
+	_fadeStep = uint16(_fadeStep + delta);
+	if (int16(_fadeStep) >= int16(_fadeMax)) {
+		_fadeStep = _fadeMax;
+		memcpy(_paletteFadeSource, _paletteTarget, COMFY_PALETTE_BYTES);
+		memcpy(_paletteDisplay, _paletteTarget, COMFY_PALETTE_BYTES);
+		_paletteFading = false;
+	} else {
+		paletteInterpolate(_fadeStep, _fadeMax);
+	}
+
+	vsyncSetPalettePtr(_paletteDisplay);
+}
+
+void ComfyEngine::paletteLoadWithFade(uint16 paletteId, uint16 fadeTicks) {
+	colorDatReadEntry(paletteId);
+	_palettePage = 'S';
+	if (_paletteFading)
+		memcpy(_paletteFadeSource, _paletteDisplay, COMFY_PALETTE_BYTES);
+
+	if (!fadeTicks) {
+		_paletteFading = false;
+		memcpy(_paletteDisplay, _paletteTarget, COMFY_PALETTE_BYTES);
+		memcpy(_paletteFadeSource, _paletteTarget, COMFY_PALETTE_BYTES);
+		vsyncSetPalettePtr(_paletteDisplay);
+	} else {
+		_paletteFading = true;
+		_fadeMax = fadeTicks;
+		_fadeStep = 0;
+	}
+}
+
+void ComfyEngine::paletteApplyBrightness(uint16 brightness) {
+	if (_paletteFading)
+		_paletteFading = false;
+
+	uint16 inverse = uint16(0x100 - brightness);
+	memcpy(_paletteFadeSource, _paletteDisplay, COMFY_PALETTE_BYTES);
+	memcpy(_paletteDisplay, _paletteFadeSource + inverse * 3, brightness * 3);
+	memcpy(_paletteDisplay + brightness * 3, _paletteFadeSource, inverse * 3);
+	vsyncSetPalettePtr(_paletteDisplay);
+}
+
+void ComfyEngine::paletteConvertRgbToLogical(byte *source, byte *destination) {
+	for (uint i = 0; i < 256; i++) {
+		destination[i * 4 + 2] = byte(source[i * 3] << 2);
+		destination[i * 4 + 1] = byte(source[i * 3 + 1] << 2);
+		destination[i * 4] = byte(source[i * 3 + 2] << 2);
+	}
+}
+
+void ComfyEngine::paletteRealize(byte *rawPalette) {
+	if (rawPalette)
+		paletteConvertRgbToLogical(rawPalette, _logicalPalette);
+
+	_logicalPalette[255 * 4 + 2] = 0xFF;
+	_logicalPalette[255 * 4 + 1] = 0xFF;
+	_logicalPalette[255 * 4] = 0xFF;
+	_logicalPalette[2] = 0;
+	_logicalPalette[1] = 0;
+	_logicalPalette[0] = 0;
+
+	byte palette[COMFY_PALETTE_BYTES];
+	for (uint i = 0; i < 256; i++) {
+		palette[i * 3] = _logicalPalette[i * 4 + 2];
+		palette[i * 3 + 1] = _logicalPalette[i * 4 + 1];
+		palette[i * 3 + 2] = _logicalPalette[i * 4];
+	}
+
+	_system->getPaletteManager()->setPalette(palette, 0, 256);
+}
+
+void ComfyEngine::paletteVsyncFlip() {
+	if (!_vsyncPending)
+		return;
+
+	paletteRealize(_paletteDataPtr);
+	_vsyncPending = 0;
+}
 
 } // End of namespace Comfy
diff --git a/engines/comfy/video.cpp b/engines/comfy/video.cpp
index 409cdeb90bd..f38dbcc3677 100644
--- a/engines/comfy/video.cpp
+++ b/engines/comfy/video.cpp
@@ -19,7 +19,157 @@
  *
  */
 
+#include "comfy/comfy.h"
+
+#include "engines/util.h"
+
 namespace Comfy {
 
+uint32 ComfyEngine::framebufferBytes() {
+	return uint32(_logicalScreenWidth) * _logicalScreenHeight;
+}
+
+void ComfyEngine::videoInit() {
+	if (_videoInitialized)
+		return;
+
+	initGraphics(_logicalScreenWidth, _logicalScreenHeight);
+	_screen = new Graphics::Screen(_logicalScreenWidth, _logicalScreenHeight);
+	_framebufPtr = new byte[framebufferBytes()]();
+	_presentBuffer = new byte[framebufferBytes()]();
+	_resolutionChangeCount = 0;
+	_renderDirtyCount = 0;
+	videoSetResolution();
+	videoPresentFrame();
+	_videoInitialized = true;
+}
+
+void ComfyEngine::videoShutdown() {
+	colorDatClose();
+	delete[] _presentBuffer;
+	_presentBuffer = nullptr;
+	delete[] _framebufPtr;
+	_framebufPtr = nullptr;
+	delete _screen;
+	_screen = nullptr;
+	_resolutionChangeCount = 0;
+	_renderDirtyCount = 0;
+	_videoInitialized = false;
+}
+
+void ComfyEngine::videoSetResolution() {
+	VideoRectRecord record;
+	record.left = 0;
+	record.top = 0;
+	record.right = _logicalScreenWidth;
+	record.bottom = _logicalScreenHeight;
+	record.area = MIN<uint32>(framebufferBytes(), 0xFFFF);
+	videoFindBestMode(record);
+}
+
+void ComfyEngine::renderSetDirty() {
+	_renderDirtyCount = 1;
+}
+
+void ComfyEngine::renderFlushDirty() {
+	_resolutionChangeCount = 0;
+	if (_renderDirtyCount) {
+		_renderDirtyCount--;
+		videoSetResolution();
+	}
+}
+
+void ComfyEngine::videoFindBestMode(VideoRectRecord record) {
+	record.left = CLIP<int16>(record.left, 0, _logicalScreenWidth);
+	record.top = CLIP<int16>(record.top, 0, _logicalScreenHeight);
+	record.right = CLIP<int16>(record.right, 0, _logicalScreenWidth);
+	record.bottom = CLIP<int16>(record.bottom, 0, _logicalScreenHeight);
+
+	if (_resolutionChangeCount >= COMFY_RESOLUTION_CHANGE_CAPACITY) {
+		renderFlushDirty();
+		videoSetResolution();
+		return;
+	}
+
+	for (int i = _resolutionChangeCount - 1; i >= 0; i--) {
+		VideoRectRecord &existing = _resolutionChanges[i];
+		if (existing.right < record.left && existing.left <= record.right &&
+				existing.bottom >= record.top && existing.top <= record.bottom)
+			continue;
+
+		VideoRectRecord merged;
+		merged.left = MIN(existing.left, record.left) / 2 * 2;
+		merged.right = (MAX(existing.right, record.right) + 1) / 2 * 2;
+		merged.top = MIN(existing.top, record.top) / 2 * 2;
+		merged.bottom = (MAX(existing.bottom, record.bottom) + 1) / 2 * 2;
+		merged.area = uint16((merged.right - merged.left) * (merged.bottom - merged.top));
+
+		if (uint32(existing.area) + record.area >= merged.area) {
+			existing = merged;
+			return;
+		}
+	}
+
+	_resolutionChanges[_resolutionChangeCount] = record;
+	_resolutionChangeCount++;
+}
+
+void ComfyEngine::framebufCopyAll(byte *destination, byte *source) {
+	memcpy(destination, source, framebufferBytes());
+}
+
+void ComfyEngine::framebufClear(uint16 color) {
+	memset(_framebufPtr, byte(color), framebufferBytes());
+}
+
+void ComfyEngine::videoPresentFrame() {
+	if (!_screen || !_framebufPtr || !_presentBuffer)
+		return;
+
+	if (_renderInterleaved && framebufferBytes() == 0xFA00) {
+		uint32 byteOffset = 0;
+		for (uint16 i = 0; i < 0x3E80;) {
+			memcpy(_presentBuffer + byteOffset, _framebufPtr + byteOffset, 4);
+			byteOffset += 4;
+			if ((i % 0x4E20) > 0x4268)
+				i++;
+
+			i++;
+		}
+
+		_screen->copyRectToSurface(_presentBuffer, _logicalScreenWidth, 0, 0,
+			_logicalScreenWidth, _logicalScreenHeight);
+	} else {
+		uint32 dirtyArea = 0;
+		for (uint i = 0; i < _resolutionChangeCount; i++)
+			dirtyArea += _resolutionChanges[i].area;
+
+		if (dirtyArea > framebufferBytes() - 1000) {
+			framebufCopyAll(_presentBuffer, _framebufPtr);
+			_screen->copyRectToSurface(_presentBuffer, _logicalScreenWidth, 0, 0,
+				_logicalScreenWidth, _logicalScreenHeight);
+		} else {
+			for (uint i = 0; i < _resolutionChangeCount; i++) {
+				VideoRectRecord &record = _resolutionChanges[i];
+				int16 width = record.right - record.left;
+				int16 height = record.bottom - record.top;
+				if (width <= 0 || height <= 0)
+					continue;
+
+				for (int16 y = record.top; y < record.bottom; y++) {
+					byte *source = _framebufPtr + uint32(y) * _logicalScreenWidth + record.left;
+					byte *destination = _presentBuffer + uint32(y) * _logicalScreenWidth + record.left;
+					memcpy(destination, source, width);
+				}
+
+				byte *source = _presentBuffer + uint32(record.top) * _logicalScreenWidth + record.left;
+				_screen->copyRectToSurface(source, _logicalScreenWidth, record.left, record.top, width, height);
+			}
+		}
+	}
+
+	_screen->update();
+	renderFlushDirty();
+}
 
 } // End of namespace Comfy


Commit: dc0d9d1752d05df6ace9b8fb652a3b377a855d93
    https://github.com/scummvm/scummvm/commit/dc0d9d1752d05df6ace9b8fb652a3b377a855d93
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Start inserting some game timers and MIDI stuff

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/midi.cpp
    engines/comfy/timer.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 8d8c777280c..8356ff0d27c 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -58,6 +58,9 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Eng
 	_resolutionChangeCount(0), _renderDirtyCount(0), _renderInterleaved(false),
 	_colorDatStream(nullptr), _paletteDataPtr(nullptr), _vsyncPending(0), _fadeMax(0), _fadeStep(0),
 	_palettePage(0), _paletteFading(false),
+	_timerCurrent(1), _timer0(1), _timer1(1), _timer2(1),
+	_midiTimeCounter(0), _midiInstanceEventTime(0), _midiEventBaseTime(0),
+	_midiTimeScale(0x400), _midiTimeDelta(0), _midiCounterAdjustment(0), _midiPlyrDriver(nullptr),
 	_timerLastMillis(0), _pitAccumulator(0), _gameInitialized(false), _videoInitialized(false),
 	_timerInitialized(false), _lptKeyboardInitialized(false), _mainLoopRunning(false) {
 	memset(_paletteFadeSource, 0, sizeof(_paletteFadeSource));
@@ -99,6 +102,9 @@ Common::Error ComfyEngine::gameInit() {
 	if (!iniReadGameConfig())
 		return Common::kNoGameDataFoundError;
 
+	if (!iniGetGameDataPath(0) || !midiPlyrStart())
+		return Common::kNoGameDataFoundError;
+
 	videoInit();
 	timerInit();
 	lptKeyboardInit();
@@ -107,6 +113,8 @@ Common::Error ComfyEngine::gameInit() {
 }
 
 void ComfyEngine::gameShutdown() {
+	midiPlyrStop();
+
 	if (_lptKeyboardInitialized)
 		lptKeyboardShutdown();
 
@@ -200,10 +208,6 @@ void ComfyEngine::gameMainLoopTick() {
 	processSceneTransition();
 }
 
-uint16 ComfyEngine::timerTick() {
-	return 1;
-}
-
 void ComfyEngine::midiTrackTickAndRemove() {
 }
 
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index b8471c516dc..9f0e8a8c0b4 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -48,6 +48,8 @@
 
 namespace Comfy {
 
+class MidiPlyrDriver;
+
 enum ComfyEngineVersion {
 	kEngineVersion1, // 1994-1995
 	kEngineVersion2, // 1996-1997
@@ -93,6 +95,17 @@ private:
 	uint16 _fadeStep;
 	byte _palettePage;
 	bool _paletteFading;
+	int16 _timerCurrent;
+	int16 _timer0;
+	int16 _timer1;
+	int16 _timer2;
+	uint32 _midiTimeCounter;
+	uint32 _midiInstanceEventTime;
+	int32 _midiEventBaseTime;
+	int32 _midiTimeScale;
+	int16 _midiTimeDelta;
+	int16 _midiCounterAdjustment;
+	MidiPlyrDriver *_midiPlyrDriver;
 	uint32 _timerLastMillis;
 	uint64 _pitAccumulator;
 	bool _gameInitialized;
@@ -132,6 +145,11 @@ private:
 	void paletteVsyncFlip();
 	void paletteConvertRgbToLogical(byte *source, byte *destination);
 	void paletteRealize(byte *rawPalette);
+	uint16 midiTick();
+	void midiSetTimeScale(int16 delta);
+	int16 midiGetCounterAdjustment();
+	bool midiPlyrStart();
+	void midiPlyrStop();
 	void timerInit();
 	void timerShutdown();
 	void lptKeyboardInit();
diff --git a/engines/comfy/midi.cpp b/engines/comfy/midi.cpp
index 409cdeb90bd..af4485ab6f6 100644
--- a/engines/comfy/midi.cpp
+++ b/engines/comfy/midi.cpp
@@ -19,7 +19,126 @@
  *
  */
 
+#include "comfy/comfy.h"
+#include "comfy/midiplyr/midiplyr.h"
+
+#include "common/ptr.h"
+
 namespace Comfy {
 
+uint16 ComfyEngine::midiTick() {
+	if (!_midiPlyrDriver)
+		return 0;
+
+	uint32 previousCounter = _midiInstanceEventTime;
+	if (_engineVersion == kEngineVersion3) {
+		int16 adjustment = midiGetCounterAdjustment();
+		if (adjustment) {
+			_midiPlyrDriver->setVocCounter(uint32(int32(_midiPlyrDriver->getVocCounter()) + adjustment));
+			_midiPlyrDriver->setTimeCounter(uint32(int32(_midiPlyrDriver->getTimeCounter()) + adjustment));
+		}
+	}
+
+	do {
+		_midiTimeCounter = _midiPlyrDriver->getTimeCounter();
+		if ((_engineVersion == kEngineVersion3 && _midiTimeCounter <= previousCounter) ||
+				(_engineVersion != kEngineVersion3 && _midiTimeCounter == previousCounter))
+			_system->delayMillis(1);
+	} while ((_engineVersion == kEngineVersion3 && _midiTimeCounter <= previousCounter) ||
+		(_engineVersion != kEngineVersion3 && _midiTimeCounter == previousCounter));
+
+	_midiInstanceEventTime = _midiTimeCounter;
+	_midiEventBaseTime = int32(_midiInstanceEventTime);
+
+	int16 delta = int16(uint16(_midiInstanceEventTime - previousCounter));
+	if (delta < 1)
+		delta = 1;
+
+	if (_midiTimeScale != 0x400) {
+		_midiTimeDelta = int16((int32(delta) * _midiTimeScale) >> 10);
+		if (!_midiTimeDelta)
+			_midiTimeDelta = 1;
+
+		if (_midiTimeDelta != delta) {
+			_midiTimeCounter = uint32(int32(_midiTimeCounter) + _midiTimeDelta - delta);
+			_midiPlyrDriver->setTimeCounter(_midiTimeCounter);
+
+			_midiInstanceEventTime = uint32(int32(_midiInstanceEventTime) + _midiTimeDelta - delta);
+			_midiEventBaseTime = int32(_midiInstanceEventTime);
+			delta = _midiTimeDelta;
+		}
+	}
+
+	return uint16(delta);
+}
+
+bool ComfyEngine::midiPlyrStart() {
+	Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(Common::Path("MIDIFILE.DAT"), true));
+	if (!stream)
+		return false;
+
+	byte signature[2];
+	if (stream->read(signature, sizeof(signature)) != sizeof(signature))
+		return false;
+
+	byte flags;
+	if (signature[0] == 'C' && signature[1] == 'M')
+		flags = 0;
+	else if (signature[0] == 'C' && signature[1] == 'm')
+		flags = 1;
+	else
+		return false;
+
+	midiPlyrStop();
+	MidiPlyrDriver::DriverVersion version = _engineVersion == kEngineVersion3 ?
+		MidiPlyrDriver::kDriverVersion2 : MidiPlyrDriver::kDriverVersion1;
+	_midiPlyrDriver = new MidiPlyrDriver(version);
+	if (!_midiPlyrDriver->musicStart(flags)) {
+		delete _midiPlyrDriver;
+		_midiPlyrDriver = nullptr;
+		return false;
+	}
+
+	_midiTimeCounter = 0;
+	_midiInstanceEventTime = 0;
+	_midiPlyrDriver->setTimeCounter(0);
+	return true;
+}
+
+void ComfyEngine::midiPlyrStop() {
+	if (!_midiPlyrDriver)
+		return;
+
+	_midiPlyrDriver->musicEnd();
+	delete _midiPlyrDriver;
+	_midiPlyrDriver = nullptr;
+}
+
+int16 ComfyEngine::midiGetCounterAdjustment() {
+	if (!_midiCounterAdjustment)
+		return 0;
+
+	int16 adjustment = _midiCounterAdjustment > 0 ? 1 : -1;
+	int16 magnitude = _midiCounterAdjustment < 0 ? -_midiCounterAdjustment : _midiCounterAdjustment;
+	if (magnitude > 5)
+		adjustment *= 2;
+
+	_midiCounterAdjustment -= adjustment;
+	return adjustment;
+}
+
+void ComfyEngine::midiSetTimeScale(int16 delta) {
+	if (!delta) {
+		_midiTimeScale = 0x400;
+		return;
+	}
+
+	_midiTimeScale = (int32(delta) * _midiTimeScale) >> 10;
+	if (_midiTimeScale < 100)
+		_midiTimeScale = 100;
+
+	if (_midiTimeScale > 10000)
+		_midiTimeScale = 10000;
+}
 
 } // End of namespace Comfy
diff --git a/engines/comfy/timer.cpp b/engines/comfy/timer.cpp
index 409cdeb90bd..4346abdef6a 100644
--- a/engines/comfy/timer.cpp
+++ b/engines/comfy/timer.cpp
@@ -19,7 +19,16 @@
  *
  */
 
+#include "comfy/comfy.h"
+
 namespace Comfy {
 
+uint16 ComfyEngine::timerTick() {
+	_timer2 = _timer1;
+	_timer1 = _timer0;
+	_timer0 = _timerCurrent;
+	_timerCurrent = int16(midiTick());
+	return uint16(_timerCurrent);
+}
 
 } // End of namespace Comfy


Commit: 870ef16d6d090c2c3a5ea9ec4cb4751a4b3dde50
    https://github.com/scummvm/scummvm/commit/870ef16d6d090c2c3a5ea9ec4cb4751a4b3dde50
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Port input/keymapper/LPT handling and ImGui interface

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/comfy_keyboard_ui.cpp
    engines/comfy/configure.engine
    engines/comfy/detection.h
    engines/comfy/game.cpp
    engines/comfy/input.cpp
    engines/comfy/keybits.cpp
    engines/comfy/metaengine.cpp
    engines/comfy/metaengine.h
    engines/comfy/midi.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 8356ff0d27c..3fe8cf29de4 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -61,12 +61,19 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Eng
 	_timerCurrent(1), _timer0(1), _timer1(1), _timer2(1),
 	_midiTimeCounter(0), _midiInstanceEventTime(0), _midiEventBaseTime(0),
 	_midiTimeScale(0x400), _midiTimeDelta(0), _midiCounterAdjustment(0), _midiPlyrDriver(nullptr),
-	_timerLastMillis(0), _pitAccumulator(0), _gameInitialized(false), _videoInitialized(false),
+	_keyBits(nullptr), _keyBitsSize(0),
+	_keyboardMapLoaded(false), _keyboardActiveMask(0), _keyboardLatchedMask(0),
+	_keymapperActiveMask(0), _keymapperLatchedMask(0), _toyKeyboardActiveMask(0),
+	_toyKeyboardLatchedMask(0), _toyKeyboardHoldMask(0), _lptPrevScanState(0), _inputDeviceMode(0),
+	_keyboardUiInitialized(false), _keyboardUiVisible(true),
+	_gameInitialized(false), _videoInitialized(false),
 	_timerInitialized(false), _lptKeyboardInitialized(false), _mainLoopRunning(false) {
 	memset(_paletteFadeSource, 0, sizeof(_paletteFadeSource));
 	memset(_paletteTarget, 0, sizeof(_paletteTarget));
 	memset(_paletteDisplay, 0, sizeof(_paletteDisplay));
 	memset(_logicalPalette, 0, sizeof(_logicalPalette));
+	memset(&_inputQueue, 0, sizeof(_inputQueue));
+	memset(_keyboardKeyToBit, 0xFF, sizeof(_keyboardKeyToBit));
 	g_engine = this;
 }
 
@@ -113,11 +120,12 @@ Common::Error ComfyEngine::gameInit() {
 }
 
 void ComfyEngine::gameShutdown() {
-	midiPlyrStop();
-
 	if (_lptKeyboardInitialized)
 		lptKeyboardShutdown();
 
+	midiPlyrStop();
+	keyBitFree();
+
 	if (_timerInitialized)
 		timerShutdown();
 
@@ -132,25 +140,13 @@ void ComfyEngine::timerInit() {
 	if (_timerInitialized)
 		return;
 
-	_timerLastMillis = _system->getMillis();
-	_pitAccumulator = 0;
 	_timerInitialized = true;
 }
 
 void ComfyEngine::timerShutdown() {
-	_timerLastMillis = 0;
-	_pitAccumulator = 0;
 	_timerInitialized = false;
 }
 
-void ComfyEngine::lptKeyboardInit() {
-	_lptKeyboardInitialized = true;
-}
-
-void ComfyEngine::lptKeyboardShutdown() {
-	_lptKeyboardInitialized = false;
-}
-
 void ComfyEngine::gameMainLoop() {
 	_mainLoopRunning = true;
 
@@ -159,35 +155,50 @@ void ComfyEngine::gameMainLoop() {
 		if (shouldQuit())
 			break;
 
-		uint32 currentMillis = _system->getMillis();
-		_pitAccumulator += uint64(currentMillis - _timerLastMillis) * COMFY_PIT_INPUT_FREQUENCY;
-		_timerLastMillis = currentMillis;
-
-		while (_pitAccumulator >= uint64(COMFY_PIT_TIMER_DIVISOR) * 1000 && !shouldQuit()) {
-			_pitAccumulator -= uint64(COMFY_PIT_TIMER_DIVISOR) * 1000;
-			gameMainLoopTick();
-		}
-
-		if (!shouldQuit() && _pitAccumulator < uint64(COMFY_PIT_TIMER_DIVISOR) * 1000)
-			waitForTimerTick();
+		gameMainLoopTick();
 	}
 
 	_mainLoopRunning = false;
 }
 
-void ComfyEngine::waitForTimerTick() {
-	uint64 pitThreshold = uint64(COMFY_PIT_TIMER_DIVISOR) * 1000;
-	uint64 remaining = pitThreshold - _pitAccumulator;
-	uint32 delay = (remaining + COMFY_PIT_INPUT_FREQUENCY - 1) / COMFY_PIT_INPUT_FREQUENCY;
-
-	if (delay != 0)
-		_system->delayMillis(delay);
-}
-
 void ComfyEngine::processEvents() {
 	Common::Event event;
 
-	while (_system->getEventManager()->pollEvent(event)) {
+	while (!shouldQuit() && _system->getEventManager()->pollEvent(event)) {
+		switch (event.type) {
+		case Common::EVENT_QUIT:
+		case Common::EVENT_RETURN_TO_LAUNCHER:
+			return;
+		case Common::EVENT_CUSTOM_ENGINE_ACTION_START:
+			if (event.customType >= kActionKeyboardContact0 && event.customType <= kActionKeyboardContactLast)
+				setKeyboardContact(event.customType - kActionKeyboardContact0, true, true);
+			break;
+		case Common::EVENT_CUSTOM_ENGINE_ACTION_END:
+			if (event.customType >= kActionKeyboardContact0 && event.customType <= kActionKeyboardContactLast)
+				setKeyboardContact(event.customType - kActionKeyboardContact0, false, true);
+			break;
+		case Common::EVENT_KEYDOWN:
+			if (!event.kbdRepeat) {
+				hostKeyboardSetKeyState(hostKeyboardVirtualKey(event.kbd.keycode), true);
+				if (event.kbd.keycode == Common::KEYCODE_UP)
+					inputQueuePushKey(0x48);
+				else if (event.kbd.keycode == Common::KEYCODE_DOWN)
+					inputQueuePushKey(0x50);
+				else if (event.kbd.keycode == Common::KEYCODE_LEFT)
+					inputQueuePushKey(0x4B);
+				else if (event.kbd.keycode == Common::KEYCODE_RIGHT)
+					inputQueuePushKey(0x4D);
+				else if (event.kbd.ascii)
+					inputQueuePushChar(event.kbd.ascii);
+			}
+			break;
+		case Common::EVENT_KEYUP:
+			hostKeyboardSetKeyState(hostKeyboardVirtualKey(event.kbd.keycode), false);
+			break;
+		default:
+			debug("EVent %d", event.type);
+			break;
+		}
 	}
 }
 
@@ -221,9 +232,6 @@ void ComfyEngine::midiPollChannels(uint16 ticks) {
 	(void)ticks;
 }
 
-void ComfyEngine::lptKeyboardScanAndProcess() {
-}
-
 void ComfyEngine::actorTickTree() {
 }
 
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 9f0e8a8c0b4..aeaa46a7fc0 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -28,6 +28,7 @@
 #include "common/file.h"
 #include "common/fs.h"
 #include "common/hash-str.h"
+#include "common/keyboard.h"
 #include "common/random.h"
 #include "common/serializer.h"
 #include "common/util.h"
@@ -45,6 +46,8 @@
 #define COMFY_PIT_TIMER_DIVISOR 0x2E9B
 #define COMFY_RESOLUTION_CHANGE_CAPACITY 100
 #define COMFY_PALETTE_BYTES 0x300
+#define COMFY_INPUT_QUEUE_CAPACITY 20
+#define COMFY_KEYBOARD_CONTACT_COUNT 24
 
 namespace Comfy {
 
@@ -66,6 +69,13 @@ private:
 		uint16 area;
 	};
 
+	struct InputQueue {
+		uint16 words[COMFY_INPUT_QUEUE_CAPACITY];
+		uint16 readIndex;
+		uint16 writeIndex;
+		uint16 tailIndex;
+	};
+
 	const ADGameDescription *_gameDescription;
 	ComfyEngineVersion _engineVersion;
 	Common::Path _gameDirectory;
@@ -106,8 +116,22 @@ private:
 	int16 _midiTimeDelta;
 	int16 _midiCounterAdjustment;
 	MidiPlyrDriver *_midiPlyrDriver;
-	uint32 _timerLastMillis;
-	uint64 _pitAccumulator;
+	byte *_keyBits;
+	uint32 _keyBitsSize;
+	InputQueue _inputQueue;
+	byte _keyboardKeyToBit[256];
+	bool _keyboardMapLoaded;
+	uint32 _keyboardActiveMask;
+	uint32 _keyboardLatchedMask;
+	uint32 _keymapperActiveMask;
+	uint32 _keymapperLatchedMask;
+	uint32 _toyKeyboardActiveMask;
+	uint32 _toyKeyboardLatchedMask;
+	uint32 _toyKeyboardHoldMask;
+	uint32 _lptPrevScanState;
+	uint16 _inputDeviceMode;
+	bool _keyboardUiInitialized;
+	bool _keyboardUiVisible;
 	bool _gameInitialized;
 	bool _videoInitialized;
 	bool _timerInitialized;
@@ -150,13 +174,36 @@ private:
 	int16 midiGetCounterAdjustment();
 	bool midiPlyrStart();
 	void midiPlyrStop();
+	bool keyBitAllocate(uint16 keyBitCount);
+	void keyBitFree();
+	bool keyBitTest(uint16 bitIndex);
+	void keyBitCopyRange(uint16 destination, uint16 count, uint32 source);
+	void keyBitSet(uint16 bitIndex);
+	void keyBitClear(uint16 bitIndex);
+	void inputQueuePushKey(uint16 key);
+	void inputQueuePushChar(uint16 key);
+	bool inputQueueHasItems();
+	uint16 inputQueueDequeue();
+	void inputQueueReset();
+	uint16 lptReadKeyOrNext();
+	void lptKeyToFlags(uint16 key);
+	void hostKeyboardResetMap();
+	bool hostKeyboardLoadDatMap();
+	void hostKeyboardSetKeyState(uint16 key, bool pressed);
+	uint16 hostKeyboardVirtualKey(Common::KeyCode key);
+	uint32 lptKeyboardScan();
+	void lptKeyboardDispatchEvents(uint32 scanState);
+	void setKeyboardContact(uint16 contact, bool pressed, bool keymapper);
+	void keyboardUiRender();
+	static void keyboardUiInitCallback();
+	static void keyboardUiRenderCallback();
+	static void keyboardUiCleanupCallback();
 	void timerInit();
 	void timerShutdown();
 	void lptKeyboardInit();
 	void lptKeyboardShutdown();
 	void gameMainLoop();
 	void gameMainLoopTick();
-	void waitForTimerTick();
 	void processEvents();
 
 	uint16 timerTick();
@@ -196,7 +243,8 @@ public:
 		return
 		    (f == kSupportsLoadingDuringRuntime) ||
 		    (f == kSupportsSavingDuringRuntime) ||
-		    (f == kSupportsReturnToLauncher);
+		    (f == kSupportsReturnToLauncher) ||
+		    (f == kSupportsQuitDialogOverride);
 	};
 
 	bool canLoadGameStateCurrently(Common::U32String *msg = nullptr) override {
diff --git a/engines/comfy/comfy_keyboard_ui.cpp b/engines/comfy/comfy_keyboard_ui.cpp
index 409cdeb90bd..f09b64d700b 100644
--- a/engines/comfy/comfy_keyboard_ui.cpp
+++ b/engines/comfy/comfy_keyboard_ui.cpp
@@ -19,7 +19,214 @@
  *
  */
 
+#include "comfy/comfy.h"
+
+#ifdef USE_IMGUI
+#include "backends/imgui/imgui.h"
+#endif
+
 namespace Comfy {
 
+#ifdef USE_IMGUI
+static ImVec4 keyboardColor(byte red, byte green, byte blue) {
+	return ImVec4(red / 255.0f, green / 255.0f, blue / 255.0f, 1.0f);
+}
+
+static ImVec4 keyboardHoverColor(ImVec4 color) {
+	color.x += (1.0f - color.x) * 0.15f;
+	color.y += (1.0f - color.y) * 0.15f;
+	color.z += (1.0f - color.z) * 0.15f;
+	return color;
+}
+
+static ImVec4 keyboardActiveColor(ImVec4 color) {
+	color.x *= 0.82f;
+	color.y *= 0.82f;
+	color.z *= 0.82f;
+	return color;
+}
+
+static void keyboardPushButtonColor(ImVec4 color) {
+	ImGui::PushStyleColor(ImGuiCol_Button, color);
+	ImGui::PushStyleColor(ImGuiCol_ButtonHovered, keyboardHoverColor(color));
+	ImGui::PushStyleColor(ImGuiCol_ButtonActive, keyboardActiveColor(color));
+}
+
+static void keyboardDrawMomentary(const char *label, uint bit, ImVec2 size, ImVec4 color,
+		uint32 &activeMask, uint32 &latchedMask, uint32 &holdMask) {
+	uint32 mask = 1 << bit;
+	bool held = (holdMask & mask) != 0;
+	bool wasActive = (activeMask & mask) != 0;
+	keyboardPushButtonColor(held ? keyboardHoverColor(color) : color);
+	ImGui::Button(label, size);
+	bool active = ImGui::IsItemActive();
+	bool rightClicked = ImGui::IsItemClicked(ImGuiMouseButton_Right);
+	ImGui::PopStyleColor(3);
+
+	if (active) {
+		activeMask |= mask;
+		latchedMask &= ~mask;
+		if (holdMask & mask)
+			holdMask &= ~mask;
+		else if (holdMask) {
+			latchedMask |= holdMask;
+			holdMask = 0;
+		}
+	} else {
+		activeMask &= ~mask;
+		if (wasActive)
+			latchedMask |= mask;
+	}
+
+	if (rightClicked) {
+		if (held) {
+			holdMask &= ~mask;
+			latchedMask |= mask;
+		} else {
+			holdMask = mask;
+		}
+	}
+
+	if (held) {
+		ImDrawList *draw = ImGui::GetWindowDrawList();
+		draw->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255, 255, 255, 230),
+			4.0f, 0, 3.0f);
+	}
+}
+
+static void keyboardDrawToggle(const char *label, uint bit, ImVec2 size, ImVec4 offColor, ImVec4 onColor,
+		uint32 &activeMask, uint32 &latchedMask) {
+	uint32 mask = 1 << bit;
+	bool active = (activeMask & mask) != 0;
+	keyboardPushButtonColor(active ? onColor : offColor);
+	bool clicked = ImGui::Button(label, size);
+	ImGui::PopStyleColor(3);
+
+	if (clicked) {
+		if (active) {
+			activeMask &= ~mask;
+			latchedMask |= mask;
+		} else {
+			activeMask |= mask;
+			latchedMask &= ~mask;
+		}
+	}
+}
+#endif
+
+void ComfyEngine::keyboardUiInitCallback() {
+#ifdef USE_IMGUI
+	ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
+#endif
+}
+
+void ComfyEngine::keyboardUiRenderCallback() {
+	if (g_engine)
+		g_engine->keyboardUiRender();
+}
+
+void ComfyEngine::keyboardUiCleanupCallback() {
+#ifdef USE_IMGUI
+	ImGui::GetIO().ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
+#endif
+}
+
+void ComfyEngine::keyboardUiRender() {
+#ifdef USE_IMGUI
+	if (!_keyboardUiVisible)
+		return;
+
+	ImGui::SetNextWindowSize(ImVec2(780.0f, 520.0f), ImGuiCond_FirstUseEver);
+	if (!ImGui::Begin("Comfy Keyboard", &_keyboardUiVisible)) {
+		ImGui::End();
+		return;
+	}
+
+	ImVec4 shell = keyboardColor(232, 228, 208);
+	ImVec4 panel = keyboardColor(36, 40, 47);
+	ImVec4 red = keyboardColor(199, 31, 27);
+	ImVec4 handset = keyboardColor(211, 48, 38);
+	ImVec4 blue = keyboardColor(31, 59, 139);
+	ImVec4 blueDark = keyboardColor(23, 43, 104);
+	ImVec4 green = keyboardColor(41, 123, 58);
+	ImVec4 fuchsia = keyboardColor(157, 58, 137);
+	ImVec4 orange = keyboardColor(234, 112, 29);
+	ImVec4 yellow = keyboardColor(230, 190, 34);
+
+	ImGui::BeginChild("toy_keyboard_body", ImVec2(730.0f, 430.0f), true, ImGuiWindowFlags_NoScrollbar);
+	ImDrawList *draw = ImGui::GetWindowDrawList();
+	ImVec2 origin = ImGui::GetCursorScreenPos();
+	draw->AddRectFilled(origin, ImVec2(origin.x + 700.0f, origin.y + 390.0f),
+		ImGui::ColorConvertFloat4ToU32(shell), 20.0f);
+	draw->AddRect(origin, ImVec2(origin.x + 700.0f, origin.y + 390.0f), IM_COL32(110, 110, 105, 255),
+		20.0f, 0, 2.0f);
+
+	ImGui::SetCursorPos(ImVec2(24.0f, 46.0f));
+	keyboardDrawToggle("HANDSET", 13, ImVec2(92.0f, 258.0f), handset, keyboardColor(248, 70, 54),
+		_toyKeyboardActiveMask, _toyKeyboardLatchedMask);
+
+	static const char *phoneLabels[] = {"SNAILY", "BUDDY", "JUMPY", "PHILLY", "COMFY"};
+	static const uint phoneBits[] = {4, 16, 10, 22, 20};
+	for (uint i = 0; i < ARRAYSIZE(phoneBits); i++) {
+		ImGui::SetCursorPos(ImVec2(136.0f, 44.0f + i * 58.0f));
+		keyboardDrawMomentary(phoneLabels[i], phoneBits[i], ImVec2(74.0f, 42.0f), red,
+			_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
+	}
+
+	ImGui::SetCursorPos(ImVec2(302.0f, 22.0f));
+	keyboardDrawMomentary("ROLL", 1, ImVec2(214.0f, 44.0f), green,
+		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
+
+	ImGui::SetCursorPos(ImVec2(628.0f, 24.0f));
+	keyboardDrawMomentary("STOP", 12, ImVec2(58.0f, 58.0f), blueDark,
+		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
+
+	ImGui::SetCursorPos(ImVec2(702.0f, 82.0f));
+	keyboardDrawToggle("ON\nOFF", 7, ImVec2(22.0f, 78.0f), keyboardColor(86, 91, 95),
+		keyboardColor(40, 160, 72), _toyKeyboardActiveMask, _toyKeyboardLatchedMask);
+
+	ImGui::SetCursorPos(ImVec2(604.0f, 132.0f));
+	keyboardDrawMomentary("SUN", 0, ImVec2(80.0f, 42.0f), blue,
+		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
+	ImGui::SetCursorPos(ImVec2(604.0f, 188.0f));
+	keyboardDrawMomentary("MOON", 9, ImVec2(80.0f, 42.0f), blue,
+		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
+	ImGui::SetCursorPos(ImVec2(604.0f, 244.0f));
+	keyboardDrawMomentary("CLOUD", 21, ImVec2(80.0f, 42.0f), blue,
+		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
+
+	ImGui::SetCursorPos(ImVec2(286.0f, 124.0f));
+	keyboardDrawMomentary("TRUMPET", 15, ImVec2(86.0f, 66.0f), blue,
+		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
+	ImGui::SetCursorPos(ImVec2(402.0f, 112.0f));
+	keyboardDrawMomentary("DRUMS", 3, ImVec2(86.0f, 66.0f), blue,
+		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
+	ImGui::SetCursorPos(ImVec2(518.0f, 124.0f));
+	keyboardDrawMomentary("FLUTE", 18, ImVec2(74.0f, 66.0f), blue,
+		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
+	ImGui::SetCursorPos(ImVec2(384.0f, 192.0f));
+	keyboardDrawMomentary("PIANO", 6, ImVec2(126.0f, 56.0f), blue,
+		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
+	ImGui::SetCursorPos(ImVec2(354.0f, 276.0f));
+	keyboardDrawMomentary("MUSIC", 23, ImVec2(180.0f, 58.0f), blue,
+		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
+
+	static const char *colorLabels[] = {"FUCHSIA", "ORANGE", "GREEN", "BLUE", "YELLOW", "RED"};
+	static const uint colorBits[] = {5, 8, 17, 14, 11, 2};
+	ImVec4 colorValues[] = {fuchsia, orange, green, blue, yellow, red};
+	for (uint i = 0; i < ARRAYSIZE(colorBits); i++) {
+		ImGui::SetCursorPos(ImVec2(226.0f + i * 72.0f, 346.0f));
+		keyboardDrawMomentary(colorLabels[i], colorBits[i], ImVec2(62.0f, 32.0f), colorValues[i],
+			_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
+	}
+
+	ImGui::SetCursorPos(ImVec2(230.0f, 88.0f));
+	ImGui::TextColored(green, "Comfy Keyboard");
+	ImGui::SetCursorPos(ImVec2(20.0f, 346.0f));
+	ImGui::TextColored(panel, "scan 0x%06X", (_toyKeyboardActiveMask | _toyKeyboardHoldMask) & 0x00FFFFFF);
+	ImGui::EndChild();
+	ImGui::End();
+#endif
+}
 
 } // End of namespace Comfy
diff --git a/engines/comfy/configure.engine b/engines/comfy/configure.engine
index 2b5c993f0f4..0cb27a516e5 100644
--- a/engines/comfy/configure.engine
+++ b/engines/comfy/configure.engine
@@ -1,3 +1,3 @@
 # This file is included from the main "configure" script
 # add_engine [name] [desc] [build-by-default] [subengines] [base games] [deps] [components]
-add_engine comfy "Comfy" no "" "" "" ""
+add_engine comfy "Comfy" no "" "" "" "imgui"
diff --git a/engines/comfy/detection.h b/engines/comfy/detection.h
index 8b9b2e24d04..542d8c8ed39 100644
--- a/engines/comfy/detection.h
+++ b/engines/comfy/detection.h
@@ -26,6 +26,12 @@
 
 namespace Comfy {
 
+enum ComfyAction {
+	kActionNone,
+	kActionKeyboardContact0,
+	kActionKeyboardContactLast = kActionKeyboardContact0 + 23
+};
+
 enum ComfyDebugChannels {
 	kDebugGraphics = 1,
 	kDebugPath,
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index 0cc46a0167b..fd732d9dc4b 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -101,6 +101,7 @@ void ComfyEngine::gameConfigInit() {
 	findLanguageDirectories();
 	ConfMan.registerDefault("comfy_language", 2);
 	ConfMan.registerDefault("comfy_screen_update_interleaved", false);
+	ConfMan.registerDefault("comfy_input_device", 0);
 }
 
 void ComfyEngine::findLanguageDirectories() {
@@ -143,6 +144,10 @@ void ComfyEngine::findLanguageDirectories() {
 bool ComfyEngine::iniReadGameConfig() {
 	_language = ConfMan.getInt("comfy_language");
 	_renderInterleaved = ConfMan.getBool("comfy_screen_update_interleaved");
+	_inputDeviceMode = ConfMan.getInt("comfy_input_device");
+	if (_inputDeviceMode > 2)
+		_inputDeviceMode = 0;
+
 	return !_gameDirectory.empty();
 }
 
diff --git a/engines/comfy/input.cpp b/engines/comfy/input.cpp
index 409cdeb90bd..9f24532e259 100644
--- a/engines/comfy/input.cpp
+++ b/engines/comfy/input.cpp
@@ -19,7 +19,306 @@
  *
  */
 
+#include "comfy/comfy.h"
+#include "comfy/midiplyr/midiplyr.h"
+
+#include "common/ptr.h"
+
 namespace Comfy {
 
+void ComfyEngine::inputQueuePushKey(uint16 key) {
+	_inputQueue.words[_inputQueue.writeIndex % COMFY_INPUT_QUEUE_CAPACITY] = 0;
+	_inputQueue.writeIndex = (_inputQueue.writeIndex + 1) % COMFY_INPUT_QUEUE_CAPACITY;
+	_inputQueue.words[_inputQueue.writeIndex % COMFY_INPUT_QUEUE_CAPACITY] = key;
+	_inputQueue.writeIndex = (_inputQueue.writeIndex + 1) % COMFY_INPUT_QUEUE_CAPACITY;
+}
+
+void ComfyEngine::inputQueuePushChar(uint16 key) {
+	_inputQueue.words[_inputQueue.writeIndex % COMFY_INPUT_QUEUE_CAPACITY] = key;
+	_inputQueue.writeIndex = (_inputQueue.writeIndex + 1) % COMFY_INPUT_QUEUE_CAPACITY;
+}
+
+bool ComfyEngine::inputQueueHasItems() {
+	return _inputQueue.writeIndex != _inputQueue.readIndex;
+}
+
+uint16 ComfyEngine::inputQueueDequeue() {
+	if (!inputQueueHasItems())
+		return 0xFFFF;
+
+	uint16 value = _inputQueue.words[_inputQueue.readIndex % COMFY_INPUT_QUEUE_CAPACITY];
+	_inputQueue.readIndex = (_inputQueue.readIndex + 1) % COMFY_INPUT_QUEUE_CAPACITY;
+	return value;
+}
+
+void ComfyEngine::inputQueueReset() {
+	_inputQueue.tailIndex = 0;
+}
+
+uint16 ComfyEngine::lptReadKeyOrNext() {
+	uint16 key = inputQueueDequeue();
+	if (!key)
+		key = inputQueueDequeue() + 0x100;
+
+	return key;
+}
+
+void ComfyEngine::lptKeyToFlags(uint16 key) {
+	uint32 flags = 0;
+	uint16 next = key;
+
+	for (;;) {
+		uint16 current = next != 0xFFFF ? next : lptReadKeyOrNext();
+		next = 0xFFFF;
+
+		switch (current) {
+		case 331:
+			flags |= 0x01;
+			break;
+		case 333:
+			flags |= 0x02;
+			break;
+		case 328:
+			flags |= 0x04;
+			break;
+		case 336:
+			flags |= 0x08;
+			break;
+		case 13:
+			flags |= 0x10;
+			break;
+		case 27:
+			flags |= 0x20;
+			break;
+		default:
+			break;
+		}
+
+		if (!inputQueueHasItems()) {
+			keyBitCopyRange(0x38, 8, flags);
+			return;
+		}
+	}
+}
+
+void ComfyEngine::hostKeyboardResetMap() {
+	memset(_keyboardKeyToBit, 0xFF, sizeof(_keyboardKeyToBit));
+	_keyboardMapLoaded = false;
+	_keyboardActiveMask = 0;
+	_keyboardLatchedMask = 0;
+}
+
+bool ComfyEngine::hostKeyboardLoadDatMap() {
+	hostKeyboardResetMap();
+	Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(Common::Path("KEYBOARD.DAT"), false));
+	if (!stream)
+		stream.reset(pathFOpen(Common::Path("KEYBOARD.DAT"), true));
+
+	if (!stream)
+		return false;
+
+	byte value;
+	do {
+		if (stream->read(&value, 1) != 1)
+			return false;
+	} while (value);
+
+	bool loaded = false;
+	while (stream->pos() < stream->size()) {
+		byte key;
+		byte bit;
+		if (stream->read(&key, 1) != 1 || stream->read(&bit, 1) != 1 || bit >= COMFY_KEYBOARD_CONTACT_COUNT) {
+			hostKeyboardResetMap();
+			return false;
+		}
+
+		_keyboardKeyToBit[key] = bit;
+		loaded = true;
+	}
+
+	_keyboardMapLoaded = loaded;
+	return loaded;
+}
+
+void ComfyEngine::hostKeyboardSetKeyState(uint16 key, bool pressed) {
+	if (!_keyboardMapLoaded || key > 0xFF)
+		return;
+
+	byte bit = _keyboardKeyToBit[key];
+	if (bit >= COMFY_KEYBOARD_CONTACT_COUNT)
+		return;
+
+	uint32 mask = 1 << bit;
+	if (pressed) {
+		_keyboardActiveMask |= mask;
+		_keyboardLatchedMask &= ~mask;
+	} else {
+		_keyboardLatchedMask |= mask;
+	}
+}
+
+uint16 ComfyEngine::hostKeyboardVirtualKey(Common::KeyCode key) {
+	if (key >= Common::KEYCODE_a && key <= Common::KEYCODE_z)
+		return 'A' + key - Common::KEYCODE_a;
+
+	if (key >= Common::KEYCODE_0 && key <= Common::KEYCODE_9)
+		return '0' + key - Common::KEYCODE_0;
+
+	switch (key) {
+	case Common::KEYCODE_UP:
+		return 0x26;
+	case Common::KEYCODE_DOWN:
+		return 0x28;
+	case Common::KEYCODE_LEFT:
+		return 0x25;
+	case Common::KEYCODE_RIGHT:
+		return 0x27;
+	case Common::KEYCODE_RETURN:
+	case Common::KEYCODE_KP_ENTER:
+		return 0x0D;
+	case Common::KEYCODE_ESCAPE:
+		return 0x1B;
+	case Common::KEYCODE_SPACE:
+		return 0x20;
+	default:
+		return key <= 0xFF ? key : 0xFFFF;
+	}
+}
+
+void ComfyEngine::setKeyboardContact(uint16 contact, bool pressed, bool keymapper) {
+	if (contact >= COMFY_KEYBOARD_CONTACT_COUNT)
+		return;
+
+	uint32 mask = 1 << contact;
+	uint32 *activeMask = keymapper ? &_keymapperActiveMask : &_toyKeyboardActiveMask;
+	uint32 *latchedMask = keymapper ? &_keymapperLatchedMask : &_toyKeyboardLatchedMask;
+	if (pressed) {
+		*activeMask |= mask;
+		*latchedMask &= ~mask;
+	} else {
+		*activeMask &= ~mask;
+		*latchedMask |= mask;
+	}
+}
+
+uint32 ComfyEngine::lptKeyboardScan() {
+	// The original wrote eight successive column strobes to the LPT data port, waited 100 busy-loop
+	// iterations after each write, and sampled three bits from the status port. Concatenating those
+	// eight 3-bit samples produced the 24-contact scan word. ScummVM supplies that same word from the
+	// keymapper, KEYBOARD.DAT mappings, and the toy-keyboard UI instead of accessing an I/O port.
+	uint32 keyboardReleased = (_keyboardLatchedMask | _keymapperLatchedMask) & 0x00FFFFFF;
+	uint32 keyboardState = (_keyboardActiveMask | _keymapperActiveMask | keyboardReleased) & 0x00FFFFFF;
+	uint32 comfyboardState = (_toyKeyboardActiveMask | _toyKeyboardHoldMask |
+		_toyKeyboardLatchedMask) & 0x00FFFFFF;
+	if (_midiPlyrDriver)
+		comfyboardState |= _midiPlyrDriver->comfyboardGetButtons() & 0x00FFFFFF;
+
+	uint32 scanState;
+	if (_engineVersion == kEngineVersion3 && _inputDeviceMode == 1)
+		scanState = comfyboardState;
+	else if (_engineVersion == kEngineVersion3 && _inputDeviceMode == 2)
+		scanState = keyboardState;
+	else
+		scanState = comfyboardState | keyboardState;
+
+	_keyboardActiveMask &= ~_keyboardLatchedMask;
+	_keymapperActiveMask &= ~_keymapperLatchedMask;
+	_toyKeyboardActiveMask &= ~_toyKeyboardLatchedMask;
+	_keyboardLatchedMask = 0;
+	_keymapperLatchedMask = 0;
+	_toyKeyboardLatchedMask = 0;
+	return scanState;
+}
+
+void ComfyEngine::lptKeyboardDispatchEvents(uint32 scanState) {
+	keyBitCopyRange(8, 0x18, scanState);
+
+	uint32 pressedThisFrame = (~_lptPrevScanState & scanState) & 0x00FFFFFF;
+	keyBitCopyRange(0x20, 0x18, pressedThisFrame);
+
+	if (pressedThisFrame & 0x00FFDFFF)
+		keyBitSet(6);
+	else
+		keyBitClear(6);
+
+	if ((scanState & 0x2000) != (_lptPrevScanState & 0x2000))
+		keyBitSet(0x41);
+	else
+		keyBitClear(0x41);
+
+	if ((_lptPrevScanState & 0x2000) && ((~scanState & 0x00FFFFFF) & 0x2000))
+		keyBitSet(0x44);
+	else
+		keyBitClear(0x44);
+
+	if (keyBitTest(0x15))
+		keyBitClear(0x45);
+	else
+		keyBitSet(0x45);
+
+	if ((_lptPrevScanState & 0x80) && ((~scanState & 0x00FFFFFF) & 0x80))
+		keyBitSet(0x43);
+	else
+		keyBitClear(0x43);
+
+	if (pressedThisFrame & 0x24924)
+		keyBitSet(7);
+	else
+		keyBitClear(7);
+
+	_lptPrevScanState = scanState;
+}
+
+void ComfyEngine::lptKeyboardInit() {
+	if (_lptKeyboardInitialized)
+		return;
+
+	inputQueueReset();
+	hostKeyboardLoadDatMap();
+	_lptPrevScanState = 0;
+	_lptKeyboardInitialized = true;
+	_keyboardUiVisible = true;
+	if (_midiPlyrDriver) {
+		if (_engineVersion == kEngineVersion3 && !_inputDeviceMode)
+			_midiPlyrDriver->comfyboardStartSleepUse();
+
+		_midiPlyrDriver->comfyboardStartReading(0x006D96DB, 0);
+	}
+
+#ifdef USE_IMGUI
+	ImGuiCallbacks callbacks;
+	callbacks.init = &keyboardUiInitCallback;
+	callbacks.render = &keyboardUiRenderCallback;
+	callbacks.cleanup = &keyboardUiCleanupCallback;
+	_system->setImGuiCallbacks(callbacks);
+	_keyboardUiInitialized = true;
+#endif
+}
+
+void ComfyEngine::lptKeyboardScanAndProcess() {
+	if (_lptKeyboardInitialized)
+		lptKeyboardDispatchEvents(lptKeyboardScan());
+}
+
+void ComfyEngine::lptKeyboardShutdown() {
+#ifdef USE_IMGUI
+	if (_keyboardUiInitialized)
+		_system->setImGuiCallbacks(ImGuiCallbacks());
+#endif
+
+	_keyboardUiInitialized = false;
+	if (_midiPlyrDriver) {
+		_midiPlyrDriver->comfyboardStopReading();
+		_midiPlyrDriver->comfyboardStopSleepUse();
+	}
+
+	hostKeyboardResetMap();
+	_keymapperActiveMask = 0;
+	_keymapperLatchedMask = 0;
+	_toyKeyboardActiveMask = 0;
+	_toyKeyboardLatchedMask = 0;
+	_toyKeyboardHoldMask = 0;
+	_lptKeyboardInitialized = false;
+}
 
 } // End of namespace Comfy
diff --git a/engines/comfy/keybits.cpp b/engines/comfy/keybits.cpp
index 409cdeb90bd..3b3ef38c078 100644
--- a/engines/comfy/keybits.cpp
+++ b/engines/comfy/keybits.cpp
@@ -19,7 +19,60 @@
  *
  */
 
+#include "comfy/comfy.h"
+
+#include "common/endian.h"
+
 namespace Comfy {
 
+bool ComfyEngine::keyBitAllocate(uint16 keyBitCount) {
+	keyBitFree();
+
+	_keyBitsSize = uint16(keyBitCount + 1) / 8 + 1;
+	_keyBits = new byte[_keyBitsSize]();
+	return true;
+}
+
+void ComfyEngine::keyBitFree() {
+	delete[] _keyBits;
+	_keyBits = nullptr;
+	_keyBitsSize = 0;
+}
+
+bool ComfyEngine::keyBitTest(uint16 bitIndex) {
+	uint32 byteIndex = bitIndex / 8;
+	if (!_keyBits || byteIndex >= _keyBitsSize)
+		return false;
+
+	return (_keyBits[byteIndex] & (1 << (bitIndex & 7))) != 0;
+}
+
+void ComfyEngine::keyBitCopyRange(uint16 destination, uint16 count, uint32 source) {
+	uint32 destinationByte = destination / 8;
+	uint32 byteCount = count / 8;
+	if (!_keyBits || byteCount > sizeof(source) || destinationByte + byteCount > _keyBitsSize)
+		return;
+
+	byte sourceBytes[sizeof(source)];
+	WRITE_LE_UINT32(sourceBytes, source);
+	memcpy(_keyBits + destinationByte, sourceBytes, byteCount);
+}
+
+void ComfyEngine::keyBitSet(uint16 bitIndex) {
+	uint32 byteIndex = bitIndex / 8;
+	if (!_keyBits || byteIndex >= _keyBitsSize)
+		return;
+
+	_keyBits[byteIndex] |= 1 << (bitIndex & 7);
+}
+
+void ComfyEngine::keyBitClear(uint16 bitIndex) {
+	uint32 byteIndex = bitIndex / 8;
+	if (!_keyBits || byteIndex >= _keyBitsSize)
+		return;
+
+	_keyBits[byteIndex] &= ~(1 << (bitIndex & 7));
+}
+
 
 } // End of namespace Comfy
diff --git a/engines/comfy/metaengine.cpp b/engines/comfy/metaengine.cpp
index 03e78fe1c26..683698b2c6e 100644
--- a/engines/comfy/metaengine.cpp
+++ b/engines/comfy/metaengine.cpp
@@ -21,6 +21,9 @@
 
 #include "common/translation.h"
 
+#include "backends/keymapper/action.h"
+#include "backends/keymapper/keymap.h"
+
 #include "comfy/metaengine.h"
 #include "comfy/detection.h"
 #include "comfy/comfy.h"
@@ -62,6 +65,37 @@ bool ComfyMetaEngine::hasFeature(MetaEngineFeature f) const {
 		(f == kSupportsLoadingDuringStartup);
 }
 
+Common::KeymapArray ComfyMetaEngine::initKeymaps(const char *target) const {
+	using namespace Common;
+
+	static const char *actionIds[COMFY_KEYBOARD_CONTACT_COUNT] = {
+		"SUN", "ROLL", "RED", "DRUM", "SNAILY", "FUCHSIA", "PIANO", "POWER",
+		"ORANGE", "MOON", "JUMPY", "YELLOW", "STOP", "HANDSET", "BLUE", "TRUMPET",
+		"BUDDY", "GREEN", "FLUTE", "CONTACT19", "COMFY", "CLOUD", "PHILLY", "MUSIC"
+	};
+	static const char *actionNames[COMFY_KEYBOARD_CONTACT_COUNT] = {
+		_s("Sun"), _s("Rolling cylinder"), _s("Red"), _s("Drum"), _s("Snaily phone"), _s("Fuchsia"),
+		_s("Piano"), _s("Power"), _s("Orange"), _s("Moon"), _s("Jumpy phone"), _s("Yellow"),
+		_s("Stop"), _s("Handset"), _s("Blue"), _s("Trumpet"), _s("Buddy phone"), _s("Green"),
+		_s("Flute"), _s("Keyboard contact 19"), _s("Comfy phone"), _s("Rainy cloud"),
+		_s("Philly phone"), _s("Music")
+	};
+	static const char *defaultMappings[COMFY_KEYBOARD_CONTACT_COUNT] = {
+		"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "q", "w",
+		"e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f"
+	};
+
+	Keymap *keymap = new Keymap(Keymap::kKeymapTypeGame, "comfy-keyboard", _s("Comfy Keyboard"));
+	for (uint i = 0; i < COMFY_KEYBOARD_CONTACT_COUNT; i++) {
+		Action *action = new Action(actionIds[i], _(actionNames[i]));
+		action->setCustomEngineActionEvent(Comfy::kActionKeyboardContact0 + i);
+		action->addDefaultInputMapping(defaultMappings[i]);
+		keymap->addAction(action);
+	}
+
+	return Keymap::arrayOf(keymap);
+}
+
 #if PLUGIN_ENABLED_DYNAMIC(COMFY)
 REGISTER_PLUGIN_DYNAMIC(COMFY, PLUGIN_TYPE_ENGINE, ComfyMetaEngine);
 #else
diff --git a/engines/comfy/metaengine.h b/engines/comfy/metaengine.h
index 5d23b038466..2aa0f0aaa59 100644
--- a/engines/comfy/metaengine.h
+++ b/engines/comfy/metaengine.h
@@ -38,6 +38,7 @@ public:
 	bool hasFeature(MetaEngineFeature f) const override;
 
 	const ADExtraGuiOptionsMap *getAdvancedExtraGuiOptions() const override;
+	Common::KeymapArray initKeymaps(const char *target) const override;
 };
 
 #endif // COMFY_METAENGINE_H
diff --git a/engines/comfy/midi.cpp b/engines/comfy/midi.cpp
index af4485ab6f6..0b3fa24c39d 100644
--- a/engines/comfy/midi.cpp
+++ b/engines/comfy/midi.cpp
@@ -42,8 +42,13 @@ uint16 ComfyEngine::midiTick() {
 	do {
 		_midiTimeCounter = _midiPlyrDriver->getTimeCounter();
 		if ((_engineVersion == kEngineVersion3 && _midiTimeCounter <= previousCounter) ||
-				(_engineVersion != kEngineVersion3 && _midiTimeCounter == previousCounter))
+				(_engineVersion != kEngineVersion3 && _midiTimeCounter == previousCounter)) {
+			processEvents();
+			if (shouldQuit())
+				return 0;
+
 			_system->delayMillis(1);
+		}
 	} while ((_engineVersion == kEngineVersion3 && _midiTimeCounter <= previousCounter) ||
 		(_engineVersion != kEngineVersion3 && _midiTimeCounter == previousCounter));
 


Commit: 5aaa11f69b5be27d7d6c7ffd0775d17e7b28f879
    https://github.com/scummvm/scummvm/commit/5aaa11f69b5be27d7d6c7ffd0775d17e7b28f879
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Show first GFX asset on screen

Also fix some ImGui stuff

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/comfy_keyboard_ui.cpp
    engines/comfy/game.cpp
    engines/comfy/input.cpp
    engines/comfy/metaengine.cpp
    engines/comfy/scene.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index 409cdeb90bd..9c59ec4336a 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -19,7 +19,232 @@
  *
  */
 
+#include "comfy/comfy.h"
+
+#include "common/endian.h"
+
 namespace Comfy {
 
+bool ComfyEngine::spriteDecompressTile(SpriteResource &sprite, const byte *source, uint32 sourceSize) {
+	uint32 outputSize = sprite.header.tiledSize;
+	if (!source || !sourceSize || !sprite.header.width || !sprite.header.height || !outputSize)
+		return false;
+
+	sprite.pixels.resize(outputSize);
+	uint32 sourcePos = 0;
+	uint32 outputPos = 0;
+	uint16 skipCount = 0;
+	uint16 fillCount = 0;
+	uint16 literalCount = 0;
+	byte fillValue = 0;
+	bool literalFromFill = false;
+
+	for (uint row = 0; row < sprite.header.height; row++) {
+		if (outputPos + 2 > outputSize)
+			return false;
+
+		uint32 rowStart = outputPos;
+		outputPos += 2;
+		uint16 pixelsLeft = sprite.header.width;
+		uint32 literalPacketPos = 0;
+		uint16 literalPacketLength = 0;
+
+		while (pixelsLeft) {
+			if (!skipCount && !fillCount && !literalCount) {
+				if (sourcePos >= sourceSize)
+					return false;
+
+				byte op = source[sourcePos++];
+				if (op & 0x40) {
+					skipCount = op - 0x40;
+					while (sourcePos < sourceSize && (source[sourcePos] & 0x40))
+						skipCount += source[sourcePos++] - 0x40;
+				} else if (op & 0x80) {
+					fillCount = op - 0x80;
+					if (sourcePos >= sourceSize)
+						return false;
+
+					fillValue = source[sourcePos++];
+					while (sourcePos < sourceSize && (source[sourcePos] & 0xC0) == 0xC0)
+						fillCount += source[sourcePos++] - 0xC0;
+				} else {
+					literalCount = op;
+					literalFromFill = false;
+				}
+
+				continue;
+			}
+
+			if (literalCount) {
+				if (!literalPacketLength || literalPacketLength == 0x3F) {
+					if (outputPos >= outputSize)
+						return false;
+
+					literalPacketPos = outputPos++;
+					literalPacketLength = 0;
+				}
+
+				uint16 count = MIN<uint16>(pixelsLeft, literalCount);
+				count = MIN<uint16>(count, 0x3F - literalPacketLength);
+				if (outputPos + count > outputSize || (!literalFromFill && sourcePos + count > sourceSize))
+					return false;
+
+				if (literalFromFill)
+					memset(&sprite.pixels[outputPos], fillValue, count);
+				else {
+					memcpy(&sprite.pixels[outputPos], source + sourcePos, count);
+					sourcePos += count;
+				}
+
+				outputPos += count;
+				pixelsLeft -= count;
+				literalCount -= count;
+				literalPacketLength += count;
+				sprite.pixels[literalPacketPos] = literalPacketLength;
+			} else if (skipCount) {
+				uint16 count = MIN<uint16>(pixelsLeft, skipCount);
+				count = MIN<uint16>(count, 0x3F);
+				if (outputPos >= outputSize)
+					return false;
+
+				sprite.pixels[outputPos++] = count + 0x40;
+				pixelsLeft -= count;
+				skipCount -= count;
+				literalPacketLength = 0;
+			} else {
+				uint16 count = MIN<uint16>(pixelsLeft, fillCount);
+				count = MIN<uint16>(count, 0x3F);
+				fillCount -= count;
+				if (count < 8) {
+					literalCount = count;
+					literalFromFill = true;
+					continue;
+				}
+
+				if (outputPos + 2 > outputSize)
+					return false;
+
+				sprite.pixels[outputPos++] = count + 0x80;
+				sprite.pixels[outputPos++] = fillValue;
+				pixelsLeft -= count;
+				literalPacketLength = 0;
+			}
+		}
+
+		WRITE_LE_UINT16(&sprite.pixels[rowStart], outputPos - rowStart);
+	}
+
+	return outputPos == outputSize;
+}
+
+bool ComfyEngine::spriteLoad(uint16 spriteId) {
+	if (spriteId >= _spriteResources.size())
+		return false;
+
+	SpriteResource &sprite = _spriteResources[spriteId];
+	if (sprite.loaded)
+		return true;
+
+	SpriteObjectHeader &header = sprite.header;
+	if (!header.dataSize || header.fileOffset > _picFileData.size() ||
+			header.dataSize > _picFileData.size() - header.fileOffset)
+		return false;
+
+	byte *source = &_picFileData[header.fileOffset];
+	if (header.width == _logicalScreenWidth && header.height == _logicalScreenHeight) {
+		sprite.pixels.resize(header.dataSize);
+		memcpy(&sprite.pixels[0], source, header.dataSize);
+	} else if (!spriteDecompressTile(sprite, source, header.dataSize)) {
+		sprite.pixels.clear();
+		return false;
+	}
+
+	sprite.loaded = true;
+	return true;
+}
+
+void ComfyEngine::spriteBlitRle(const byte *source, uint32 sourceSize) {
+	if (!_framebufPtr || !source)
+		return;
+
+	uint32 sourcePos = 0;
+	uint32 outputPos = 0;
+	uint32 outputSize = framebufferBytes();
+	byte previousFill = 0;
+	while (outputPos < outputSize && sourcePos < sourceSize) {
+		byte op = source[sourcePos++];
+		uint32 count = MIN<uint32>(op & 0x3F, outputSize - outputPos);
+		if ((op & 0xC0) == 0) {
+			if (sourcePos + count > sourceSize)
+				return;
+
+			memcpy(_framebufPtr + outputPos, source + sourcePos, count);
+			sourcePos += count;
+		} else if ((op & 0xC0) == 0xC0) {
+			memset(_framebufPtr + outputPos, previousFill, count);
+		} else {
+			if (sourcePos >= sourceSize)
+				return;
+
+			previousFill = source[sourcePos++];
+			memset(_framebufPtr + outputPos, previousFill, count);
+		}
+
+		outputPos += count;
+	}
+}
+
+void ComfyEngine::spriteBlitClipped(uint16 spriteId, int16 x, int16 y) {
+	if (!spriteLoad(spriteId))
+		return;
+
+	SpriteResource &sprite = _spriteResources[spriteId];
+	if (sprite.header.width == _logicalScreenWidth && sprite.header.height == _logicalScreenHeight) {
+		spriteBlitRle(&sprite.pixels[0], sprite.pixels.size());
+		renderSetDirty();
+		return;
+	}
+
+	uint32 rowPos = 0;
+	for (uint row = 0; row < sprite.header.height && rowPos + 2 <= sprite.pixels.size(); row++) {
+		uint16 rowSize = READ_LE_UINT16(&sprite.pixels[rowPos]);
+		if (rowSize < 2 || rowPos + rowSize > sprite.pixels.size())
+			return;
+
+		int16 drawY = y + row;
+		uint32 packetPos = rowPos + 2;
+		int16 drawX = x;
+		while (packetPos < rowPos + rowSize) {
+			byte op = sprite.pixels[packetPos++];
+			uint16 count = op & 0x3F;
+			if (op & 0x80) {
+				if (packetPos >= rowPos + rowSize)
+					return;
+
+				byte value = sprite.pixels[packetPos++];
+				for (uint i = 0; i < count; i++, drawX++) {
+					if (drawX >= 0 && drawX < int16(_logicalScreenWidth) && drawY >= 0 && drawY < int16(_logicalScreenHeight))
+						_framebufPtr[drawY * _logicalScreenWidth + drawX] = value;
+				}
+			} else if (op & 0x40) {
+				drawX += count;
+			} else {
+				if (packetPos + count > rowPos + rowSize)
+					return;
+
+				for (uint i = 0; i < count; i++, drawX++) {
+					byte value = sprite.pixels[packetPos++];
+					if (drawX >= 0 && drawX < int16(_logicalScreenWidth) && drawY >= 0 && drawY < int16(_logicalScreenHeight))
+						_framebufPtr[drawY * _logicalScreenWidth + drawX] = value;
+				}
+			}
+		}
+
+		rowPos += rowSize;
+	}
+
+	renderSetDirty();
+}
+
 
 } // End of namespace Comfy
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 3fe8cf29de4..ad79f592a57 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -66,6 +66,8 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Eng
 	_keymapperActiveMask(0), _keymapperLatchedMask(0), _toyKeyboardActiveMask(0),
 	_toyKeyboardLatchedMask(0), _toyKeyboardHoldMask(0), _lptPrevScanState(0), _inputDeviceMode(0),
 	_keyboardUiInitialized(false), _keyboardUiVisible(true),
+	_stringCount(0), _sceneCount(0), _keyBitCount(0), _resourceHandleCount(0), _midiEntryCount(0),
+	_picDataSize(0), _usesAnimFile(false), _sceneOpen(false),
 	_gameInitialized(false), _videoInitialized(false),
 	_timerInitialized(false), _lptKeyboardInitialized(false), _mainLoopRunning(false) {
 	memset(_paletteFadeSource, 0, sizeof(_paletteFadeSource));
@@ -109,10 +111,13 @@ Common::Error ComfyEngine::gameInit() {
 	if (!iniReadGameConfig())
 		return Common::kNoGameDataFoundError;
 
-	if (!iniGetGameDataPath(0) || !midiPlyrStart())
+	if (!iniGetGameDataPath(0))
 		return Common::kNoGameDataFoundError;
 
 	videoInit();
+	if (!assetsLoad() || !sceneOpen())
+		return Common::kNoGameDataFoundError;
+
 	timerInit();
 	lptKeyboardInit();
 	_gameInitialized = true;
@@ -123,8 +128,10 @@ void ComfyEngine::gameShutdown() {
 	if (_lptKeyboardInitialized)
 		lptKeyboardShutdown();
 
+	sceneClose();
+	assetsUnload();
+
 	midiPlyrStop();
-	keyBitFree();
 
 	if (_timerInitialized)
 		timerShutdown();
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index aeaa46a7fc0..b6a5cdcc944 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -31,6 +31,7 @@
 #include "common/keyboard.h"
 #include "common/random.h"
 #include "common/serializer.h"
+#include "common/array.h"
 #include "common/util.h"
 #include "engines/engine.h"
 #include "engines/savestate.h"
@@ -59,6 +60,12 @@ enum ComfyEngineVersion {
 	kEngineVersion3  // 1999
 };
 
+#ifdef USE_IMGUI
+void onImGuiInit();
+void onImGuiRender();
+void onImGuiCleanup();
+#endif
+
 class ComfyEngine : public Engine {
 private:
 	struct VideoRectRecord {
@@ -76,6 +83,23 @@ private:
 		uint16 tailIndex;
 	};
 
+	struct SpriteObjectHeader {
+		uint32 fileOffset;
+		uint16 dataSize;
+		uint16 width;
+		uint16 height;
+		int16 hotspotX;
+		int16 hotspotY;
+		byte reserved;
+		uint16 tiledSize;
+	};
+
+	struct SpriteResource {
+		SpriteObjectHeader header;
+		Common::Array<byte> pixels;
+		bool loaded;
+	};
+
 	const ADGameDescription *_gameDescription;
 	ComfyEngineVersion _engineVersion;
 	Common::Path _gameDirectory;
@@ -132,6 +156,19 @@ private:
 	uint16 _inputDeviceMode;
 	bool _keyboardUiInitialized;
 	bool _keyboardUiVisible;
+	Common::Array<byte> _comfyObjData;
+	Common::Array<byte> _picFileData;
+	Common::Array<byte> _midiFileData;
+	Common::Array<SpriteObjectHeader> _spriteHeaders;
+	Common::Array<SpriteResource> _spriteResources;
+	uint16 _stringCount;
+	uint16 _sceneCount;
+	uint16 _keyBitCount;
+	uint16 _resourceHandleCount;
+	uint16 _midiEntryCount;
+	uint32 _picDataSize;
+	bool _usesAnimFile;
+	bool _sceneOpen;
 	bool _gameInitialized;
 	bool _videoInitialized;
 	bool _timerInitialized;
@@ -194,10 +231,18 @@ private:
 	uint32 lptKeyboardScan();
 	void lptKeyboardDispatchEvents(uint32 scanState);
 	void setKeyboardContact(uint16 contact, bool pressed, bool keymapper);
-	void keyboardUiRender();
-	static void keyboardUiInitCallback();
-	static void keyboardUiRenderCallback();
-	static void keyboardUiCleanupCallback();
+	bool readAssetFile(const Common::Path &filename, Common::Array<byte> &data);
+	bool assetsLoad();
+	void assetsUnload();
+	bool comfyObjOpen();
+	bool picFileOpen();
+	bool midiFileOpen();
+	bool spriteLoad(uint16 spriteId);
+	bool spriteDecompressTile(SpriteResource &sprite, const byte *source, uint32 sourceSize);
+	void spriteBlitClipped(uint16 spriteId, int16 x, int16 y);
+	void spriteBlitRle(const byte *source, uint32 sourceSize);
+	bool sceneOpen();
+	void sceneClose();
 	void timerInit();
 	void timerShutdown();
 	void lptKeyboardInit();
diff --git a/engines/comfy/comfy_keyboard_ui.cpp b/engines/comfy/comfy_keyboard_ui.cpp
index f09b64d700b..df09c73257b 100644
--- a/engines/comfy/comfy_keyboard_ui.cpp
+++ b/engines/comfy/comfy_keyboard_ui.cpp
@@ -28,35 +28,50 @@
 namespace Comfy {
 
 #ifdef USE_IMGUI
-static ImVec4 keyboardColor(byte red, byte green, byte blue) {
-	return ImVec4(red / 255.0f, green / 255.0f, blue / 255.0f, 1.0f);
+
+typedef struct ImGuiState {
+	ComfyEngine *_engine = nullptr;
+	uint32 _activeMask = 0;
+	uint32 _latchedMask = 0;
+	uint32 _holdMask = 0;
+	bool _visible = true;
+} ImGuiState;
+
+ImGuiState *_state = nullptr;
+
+static ImU32 keyboardColor(byte red, byte green, byte blue) {
+	return IM_COL32(red, green, blue, 255);
 }
 
-static ImVec4 keyboardHoverColor(ImVec4 color) {
-	color.x += (1.0f - color.x) * 0.15f;
-	color.y += (1.0f - color.y) * 0.15f;
-	color.z += (1.0f - color.z) * 0.15f;
-	return color;
+static ImU32 keyboardHoverColor(ImU32 color) {
+	ImVec4 colorVec = ImGui::ColorConvertU32ToFloat4(color);
+	colorVec.x += ((1 - colorVec.x) * 0.15F);
+	colorVec.y += ((1 - colorVec.y) * 0.15F);
+	colorVec.z += ((1 - colorVec.z) * 0.15F);
+
+	return ImGui::ColorConvertFloat4ToU32(colorVec);
 }
 
-static ImVec4 keyboardActiveColor(ImVec4 color) {
-	color.x *= 0.82f;
-	color.y *= 0.82f;
-	color.z *= 0.82f;
-	return color;
+static ImU32 keyboardActiveColor(ImU32 color) {
+	ImVec4 colorVec = ImGui::ColorConvertU32ToFloat4(color);
+	colorVec.x *= 0.82F;
+	colorVec.y *= 0.82F;
+	colorVec.z *= 0.82F;
+
+	return ImGui::ColorConvertFloat4ToU32(colorVec);
 }
 
-static void keyboardPushButtonColor(ImVec4 color) {
+static void keyboardPushButtonColor(ImU32 color) {
 	ImGui::PushStyleColor(ImGuiCol_Button, color);
 	ImGui::PushStyleColor(ImGuiCol_ButtonHovered, keyboardHoverColor(color));
 	ImGui::PushStyleColor(ImGuiCol_ButtonActive, keyboardActiveColor(color));
 }
 
-static void keyboardDrawMomentary(const char *label, uint bit, ImVec2 size, ImVec4 color,
-		uint32 &activeMask, uint32 &latchedMask, uint32 &holdMask) {
+static void keyboardDrawMomentary(const char *label, uint bit, ImVec2 size, ImU32 color) {
 	uint32 mask = 1 << bit;
-	bool held = (holdMask & mask) != 0;
-	bool wasActive = (activeMask & mask) != 0;
+	bool held = (_state->_holdMask & mask) != 0;
+	bool wasActive = (_state->_activeMask & mask) != 0;
+
 	keyboardPushButtonColor(held ? keyboardHoverColor(color) : color);
 	ImGui::Button(label, size);
 	bool active = ImGui::IsItemActive();
@@ -64,169 +79,161 @@ static void keyboardDrawMomentary(const char *label, uint bit, ImVec2 size, ImVe
 	ImGui::PopStyleColor(3);
 
 	if (active) {
-		activeMask |= mask;
-		latchedMask &= ~mask;
-		if (holdMask & mask)
-			holdMask &= ~mask;
-		else if (holdMask) {
-			latchedMask |= holdMask;
-			holdMask = 0;
+		_state->_activeMask |= mask;
+		_state->_latchedMask &= ~mask;
+
+		if (_state->_holdMask & mask) {
+			_state->_holdMask &= ~mask;
+		} else if (_state->_holdMask) {
+			_state->_latchedMask |= _state->_holdMask;
+			_state->_holdMask = 0;
 		}
 	} else {
-		activeMask &= ~mask;
+		_state->_activeMask &= ~mask;
+
 		if (wasActive)
-			latchedMask |= mask;
+			_state->_latchedMask |= mask;
 	}
 
 	if (rightClicked) {
 		if (held) {
-			holdMask &= ~mask;
-			latchedMask |= mask;
+			_state->_holdMask &= ~mask;
+			_state->_latchedMask |= mask;
 		} else {
-			holdMask = mask;
+			_state->_holdMask = mask;
 		}
 	}
 
 	if (held) {
 		ImDrawList *draw = ImGui::GetWindowDrawList();
-		draw->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255, 255, 255, 230),
-			4.0f, 0, 3.0f);
+		draw->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255, 255, 255, 230), 4, 0, 3);
 	}
 }
 
-static void keyboardDrawToggle(const char *label, uint bit, ImVec2 size, ImVec4 offColor, ImVec4 onColor,
-		uint32 &activeMask, uint32 &latchedMask) {
+static void keyboardDrawToggle(const char *label, uint bit, ImVec2 size, ImU32 offColor, ImU32 onColor) {
 	uint32 mask = 1 << bit;
-	bool active = (activeMask & mask) != 0;
+	bool active = (_state->_activeMask & mask) != 0;
+
 	keyboardPushButtonColor(active ? onColor : offColor);
 	bool clicked = ImGui::Button(label, size);
 	ImGui::PopStyleColor(3);
 
 	if (clicked) {
 		if (active) {
-			activeMask &= ~mask;
-			latchedMask |= mask;
+			_state->_activeMask &= ~mask;
+			_state->_latchedMask |= mask;
 		} else {
-			activeMask |= mask;
-			latchedMask &= ~mask;
+			_state->_activeMask |= mask;
+			_state->_latchedMask &= ~mask;
 		}
 	}
 }
-#endif
 
-void ComfyEngine::keyboardUiInitCallback() {
-#ifdef USE_IMGUI
-	ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
-#endif
-}
+void onImGuiInit() {
+	ImGuiIO &io = ImGui::GetIO();
+	io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
 
-void ComfyEngine::keyboardUiRenderCallback() {
-	if (g_engine)
-		g_engine->keyboardUiRender();
+	_state = new ImGuiState();
+	_state->_engine = (ComfyEngine *)g_engine;
 }
 
-void ComfyEngine::keyboardUiCleanupCallback() {
-#ifdef USE_IMGUI
-	ImGui::GetIO().ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
-#endif
-}
-
-void ComfyEngine::keyboardUiRender() {
-#ifdef USE_IMGUI
-	if (!_keyboardUiVisible)
+void onImGuiRender() {
+	if (_state->_engine->shouldQuit() || !_state || !_state->_engine || !_state->_visible)
 		return;
 
-	ImGui::SetNextWindowSize(ImVec2(780.0f, 520.0f), ImGuiCond_FirstUseEver);
-	if (!ImGui::Begin("Comfy Keyboard", &_keyboardUiVisible)) {
-		ImGui::End();
-		return;
-	}
+	ImGui::GetIO().ConfigFlags &= ~(ImGuiConfigFlags_NoMouseCursorChange | ImGuiConfigFlags_NoMouse);
 
-	ImVec4 shell = keyboardColor(232, 228, 208);
-	ImVec4 panel = keyboardColor(36, 40, 47);
-	ImVec4 red = keyboardColor(199, 31, 27);
-	ImVec4 handset = keyboardColor(211, 48, 38);
-	ImVec4 blue = keyboardColor(31, 59, 139);
-	ImVec4 blueDark = keyboardColor(23, 43, 104);
-	ImVec4 green = keyboardColor(41, 123, 58);
-	ImVec4 fuchsia = keyboardColor(157, 58, 137);
-	ImVec4 orange = keyboardColor(234, 112, 29);
-	ImVec4 yellow = keyboardColor(230, 190, 34);
-
-	ImGui::BeginChild("toy_keyboard_body", ImVec2(730.0f, 430.0f), true, ImGuiWindowFlags_NoScrollbar);
-	ImDrawList *draw = ImGui::GetWindowDrawList();
-	ImVec2 origin = ImGui::GetCursorScreenPos();
-	draw->AddRectFilled(origin, ImVec2(origin.x + 700.0f, origin.y + 390.0f),
-		ImGui::ColorConvertFloat4ToU32(shell), 20.0f);
-	draw->AddRect(origin, ImVec2(origin.x + 700.0f, origin.y + 390.0f), IM_COL32(110, 110, 105, 255),
-		20.0f, 0, 2.0f);
-
-	ImGui::SetCursorPos(ImVec2(24.0f, 46.0f));
-	keyboardDrawToggle("HANDSET", 13, ImVec2(92.0f, 258.0f), handset, keyboardColor(248, 70, 54),
-		_toyKeyboardActiveMask, _toyKeyboardLatchedMask);
-
-	static const char *phoneLabels[] = {"SNAILY", "BUDDY", "JUMPY", "PHILLY", "COMFY"};
-	static const uint phoneBits[] = {4, 16, 10, 22, 20};
-	for (uint i = 0; i < ARRAYSIZE(phoneBits); i++) {
-		ImGui::SetCursorPos(ImVec2(136.0f, 44.0f + i * 58.0f));
-		keyboardDrawMomentary(phoneLabels[i], phoneBits[i], ImVec2(74.0f, 42.0f), red,
-			_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
-	}
+	ImGui::SetNextWindowSize(ImVec2(780, 520), ImGuiCond_FirstUseEver);
+
+	if (ImGui::Begin("Comfy Keyboard", &_state->_visible)) {
+		ImU32 shell = keyboardColor(232, 228, 208);
+		ImU32 red = keyboardColor(199, 31, 27);
+		ImU32 handset = keyboardColor(211, 48, 38);
+		ImU32 blue = keyboardColor(31, 59, 139);
+		ImU32 blueDark = keyboardColor(23, 43, 104);
+		ImU32 green = keyboardColor(41, 123, 58);
+		ImU32 purple = keyboardColor(157, 58, 137);
+		ImU32 orange = keyboardColor(234, 112, 29);
+		ImU32 yellow = keyboardColor(230, 190, 34);
+
+		ImGui::BeginChild("toy_keyboard_body", ImVec2(730, 430), ImGuiChildFlags_AlwaysUseWindowPadding, ImGuiWindowFlags_NoScrollbar);
+
+		ImDrawList *draw = ImGui::GetWindowDrawList();
+		ImVec2 origin = ImGui::GetCursorScreenPos();
+
+		draw->AddRectFilled(origin, ImVec2(origin.x + 700, origin.y + 390), shell, 20);
+		draw->AddRect(origin, ImVec2(origin.x + 700, origin.y + 390), keyboardColor(110, 110, 105), 20, 0, 2);
 
-	ImGui::SetCursorPos(ImVec2(302.0f, 22.0f));
-	keyboardDrawMomentary("ROLL", 1, ImVec2(214.0f, 44.0f), green,
-		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
-
-	ImGui::SetCursorPos(ImVec2(628.0f, 24.0f));
-	keyboardDrawMomentary("STOP", 12, ImVec2(58.0f, 58.0f), blueDark,
-		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
-
-	ImGui::SetCursorPos(ImVec2(702.0f, 82.0f));
-	keyboardDrawToggle("ON\nOFF", 7, ImVec2(22.0f, 78.0f), keyboardColor(86, 91, 95),
-		keyboardColor(40, 160, 72), _toyKeyboardActiveMask, _toyKeyboardLatchedMask);
-
-	ImGui::SetCursorPos(ImVec2(604.0f, 132.0f));
-	keyboardDrawMomentary("SUN", 0, ImVec2(80.0f, 42.0f), blue,
-		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
-	ImGui::SetCursorPos(ImVec2(604.0f, 188.0f));
-	keyboardDrawMomentary("MOON", 9, ImVec2(80.0f, 42.0f), blue,
-		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
-	ImGui::SetCursorPos(ImVec2(604.0f, 244.0f));
-	keyboardDrawMomentary("CLOUD", 21, ImVec2(80.0f, 42.0f), blue,
-		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
-
-	ImGui::SetCursorPos(ImVec2(286.0f, 124.0f));
-	keyboardDrawMomentary("TRUMPET", 15, ImVec2(86.0f, 66.0f), blue,
-		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
-	ImGui::SetCursorPos(ImVec2(402.0f, 112.0f));
-	keyboardDrawMomentary("DRUMS", 3, ImVec2(86.0f, 66.0f), blue,
-		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
-	ImGui::SetCursorPos(ImVec2(518.0f, 124.0f));
-	keyboardDrawMomentary("FLUTE", 18, ImVec2(74.0f, 66.0f), blue,
-		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
-	ImGui::SetCursorPos(ImVec2(384.0f, 192.0f));
-	keyboardDrawMomentary("PIANO", 6, ImVec2(126.0f, 56.0f), blue,
-		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
-	ImGui::SetCursorPos(ImVec2(354.0f, 276.0f));
-	keyboardDrawMomentary("MUSIC", 23, ImVec2(180.0f, 58.0f), blue,
-		_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
-
-	static const char *colorLabels[] = {"FUCHSIA", "ORANGE", "GREEN", "BLUE", "YELLOW", "RED"};
-	static const uint colorBits[] = {5, 8, 17, 14, 11, 2};
-	ImVec4 colorValues[] = {fuchsia, orange, green, blue, yellow, red};
-	for (uint i = 0; i < ARRAYSIZE(colorBits); i++) {
-		ImGui::SetCursorPos(ImVec2(226.0f + i * 72.0f, 346.0f));
-		keyboardDrawMomentary(colorLabels[i], colorBits[i], ImVec2(62.0f, 32.0f), colorValues[i],
-			_toyKeyboardActiveMask, _toyKeyboardLatchedMask, _toyKeyboardHoldMask);
+		ImGui::SetCursorPos(ImVec2(24, 46));
+		keyboardDrawToggle("HANDSET", 13, ImVec2(92, 258), handset, keyboardColor(248, 70, 54));
+
+		static const char *phoneLabels[] = {"SNAILY", "BUDDY", "JUMPY", "FEELY", "COMFY"};
+		static const uint phoneBits[] = {4, 16, 10, 22, 20};
+
+		for (uint i = 0; i < ARRAYSIZE(phoneBits); i++) {
+			ImGui::SetCursorPos(ImVec2(136, 44 + i * 58));
+			keyboardDrawMomentary(phoneLabels[i], phoneBits[i], ImVec2(74, 42), red);
+		}
+
+		ImGui::SetCursorPos(ImVec2(302, 22));
+		keyboardDrawMomentary("ROLL", 1, ImVec2(214, 44), green);
+
+		ImGui::SetCursorPos(ImVec2(628, 24));
+		keyboardDrawMomentary("STOP", 12, ImVec2(58, 58), blueDark);
+
+		ImGui::SetCursorPos(ImVec2(702, 82));
+		keyboardDrawToggle("ON\nOFF", 7, ImVec2(22, 78), keyboardColor(86, 91, 95), keyboardColor(40, 160, 72));
+
+		ImGui::SetCursorPos(ImVec2(604, 132));
+		keyboardDrawMomentary("SUN", 0, ImVec2(80, 42), blue);
+
+		ImGui::SetCursorPos(ImVec2(604, 188));
+		keyboardDrawMomentary("MOON", 9, ImVec2(80, 42), blue);
+
+		ImGui::SetCursorPos(ImVec2(604, 244));
+		keyboardDrawMomentary("CLOUD", 21, ImVec2(80, 42), blue);
+
+		ImGui::SetCursorPos(ImVec2(286, 124));
+		keyboardDrawMomentary("TRUMPET", 15, ImVec2(86, 66), blue);
+
+		ImGui::SetCursorPos(ImVec2(402, 112));
+		keyboardDrawMomentary("DRUMS", 3, ImVec2(86, 66), blue);
+
+		ImGui::SetCursorPos(ImVec2(518, 124));
+		keyboardDrawMomentary("FLUTE", 18, ImVec2(74, 66), blue);
+
+		ImGui::SetCursorPos(ImVec2(384, 192));
+		keyboardDrawMomentary("PIANO", 6, ImVec2(126, 56), blue);
+
+		ImGui::SetCursorPos(ImVec2(354, 276));
+		keyboardDrawMomentary("MUSIC", 23, ImVec2(180, 58), blue);
+
+		static const char *colorLabels[] = {"PURPLE", "ORANGE", "GREEN", "BLUE", "YELLOW", "RED"};
+		static const uint colorBits[] = {5, 8, 17, 14, 11, 2};
+		ImU32 colorValues[] = {purple, orange, green, blue, yellow, red};
+
+		for (uint i = 0; i < ARRAYSIZE(colorBits); i++) {
+			ImGui::SetCursorPos(ImVec2(226 + i * 72, 346));
+			keyboardDrawMomentary(colorLabels[i], colorBits[i], ImVec2(62, 32), colorValues[i]);
+		}
+
+		ImGui::SetCursorPos(ImVec2(230, 88));
+		ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(green), "Comfy Keyboard");
+
+		ImGui::SetCursorPos(ImVec2(20, 346));
+		ImGui::Text("scan 0x%06X", (_state->_activeMask | _state->_holdMask) & 0x00FFFFFF);
+
+		ImGui::EndChild();
 	}
 
-	ImGui::SetCursorPos(ImVec2(230.0f, 88.0f));
-	ImGui::TextColored(green, "Comfy Keyboard");
-	ImGui::SetCursorPos(ImVec2(20.0f, 346.0f));
-	ImGui::TextColored(panel, "scan 0x%06X", (_toyKeyboardActiveMask | _toyKeyboardHoldMask) & 0x00FFFFFF);
-	ImGui::EndChild();
 	ImGui::End();
-#endif
 }
 
+void onImGuiCleanup() {
+	delete _state;
+	_state = nullptr;
+}
+
+#endif // USE_IMGUI
+
 } // End of namespace Comfy
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index fd732d9dc4b..2919d59b450 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -22,6 +22,8 @@
 #include "comfy/comfy.h"
 
 #include "common/config-manager.h"
+#include "common/endian.h"
+#include "common/ptr.h"
 
 namespace Comfy {
 
@@ -207,4 +209,104 @@ Common::SeekableReadStream *ComfyEngine::pathFOpen(const Common::Path &filename,
 	return file;
 }
 
+bool ComfyEngine::readAssetFile(const Common::Path &filename, Common::Array<byte> &data) {
+	Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(filename, true));
+	if (!stream || stream->size() < 0 || uint64(stream->size()) > UINT32_MAX)
+		return false;
+
+	uint32 size = stream->size();
+	data.resize(size);
+	if (size && stream->read(&data[0], size) != size) {
+		data.clear();
+		return false;
+	}
+
+	return true;
+}
+
+bool ComfyEngine::comfyObjOpen() {
+	if (!readAssetFile(Common::Path("COMFY.OBJ"), _comfyObjData) || _comfyObjData.size() < 0x14)
+		return false;
+
+	_stringCount = READ_LE_UINT16(&_comfyObjData[0x08]);
+	_sceneCount = READ_LE_UINT16(&_comfyObjData[0x0A]);
+	_keyBitCount = READ_LE_UINT16(&_comfyObjData[0x0C]);
+	_picDataSize = READ_LE_UINT32(&_comfyObjData[0x0E]);
+	_resourceHandleCount = READ_LE_UINT16(&_comfyObjData[0x12]);
+	_usesAnimFile = (_resourceHandleCount & 0x8000) != 0;
+	_resourceHandleCount &= 0x7FFF;
+	return keyBitAllocate(_keyBitCount);
+}
+
+bool ComfyEngine::picFileOpen() {
+	if (!readAssetFile(Common::Path("PICFILE.DAT"), _picFileData) || _picFileData.size() < 2)
+		return false;
+
+	uint16 count = READ_LE_UINT16(&_picFileData[0]);
+	uint32 tableSize = 2 + uint32(count) * 0x11;
+	if (tableSize > _picFileData.size())
+		return false;
+
+	_spriteHeaders.resize(count);
+	_spriteResources.resize(count);
+	for (uint i = 0; i < count; i++) {
+		byte *entry = &_picFileData[2 + i * 0x11];
+		SpriteObjectHeader &header = _spriteHeaders[i];
+		header.fileOffset = READ_LE_UINT32(entry);
+		header.dataSize = READ_LE_UINT16(entry + 0x04);
+		header.width = READ_LE_UINT16(entry + 0x06);
+		header.height = READ_LE_UINT16(entry + 0x08);
+		header.hotspotX = int16(READ_LE_UINT16(entry + 0x0A));
+		header.hotspotY = int16(READ_LE_UINT16(entry + 0x0C));
+		header.reserved = entry[0x0E];
+		header.tiledSize = READ_LE_UINT16(entry + 0x0F);
+		_spriteResources[i].header = header;
+		_spriteResources[i].pixels.clear();
+		_spriteResources[i].loaded = false;
+
+		if (header.fileOffset > _picFileData.size() ||
+				header.dataSize > _picFileData.size() - header.fileOffset)
+			return false;
+	}
+
+	return true;
+}
+
+bool ComfyEngine::midiFileOpen() {
+	if (!readAssetFile(Common::Path("MIDIFILE.DAT"), _midiFileData) || _midiFileData.size() < 4)
+		return false;
+
+	if (_midiFileData[0] != 'C' || (_midiFileData[1] != 'M' && _midiFileData[1] != 'm'))
+		return false;
+
+	_midiEntryCount = READ_LE_UINT16(&_midiFileData[2]);
+	return true;
+}
+
+bool ComfyEngine::assetsLoad() {
+	assetsUnload();
+	if (!comfyObjOpen() || !picFileOpen() || !midiFileOpen()) {
+		assetsUnload();
+		return false;
+	}
+
+	return true;
+}
+
+void ComfyEngine::assetsUnload() {
+	keyBitFree();
+	_comfyObjData.clear();
+	_picFileData.clear();
+	_midiFileData.clear();
+	_spriteHeaders.clear();
+	_spriteResources.clear();
+	_stringCount = 0;
+	_sceneCount = 0;
+	_keyBitCount = 0;
+	_resourceHandleCount = 0;
+	_midiEntryCount = 0;
+	_picDataSize = 0;
+	_usesAnimFile = false;
+}
+
 } // End of namespace Comfy
diff --git a/engines/comfy/input.cpp b/engines/comfy/input.cpp
index 9f24532e259..0301ab5812b 100644
--- a/engines/comfy/input.cpp
+++ b/engines/comfy/input.cpp
@@ -286,11 +286,11 @@ void ComfyEngine::lptKeyboardInit() {
 	}
 
 #ifdef USE_IMGUI
-	ImGuiCallbacks callbacks;
-	callbacks.init = &keyboardUiInitCallback;
-	callbacks.render = &keyboardUiRenderCallback;
-	callbacks.cleanup = &keyboardUiCleanupCallback;
-	_system->setImGuiCallbacks(callbacks);
+	ImGuiCallbacks imGuiCallbacks;
+	imGuiCallbacks.init = onImGuiInit;
+	imGuiCallbacks.render = onImGuiRender;
+	imGuiCallbacks.cleanup = onImGuiCleanup;
+	_system->setImGuiCallbacks(imGuiCallbacks);
 	_keyboardUiInitialized = true;
 #endif
 }
diff --git a/engines/comfy/metaengine.cpp b/engines/comfy/metaengine.cpp
index 683698b2c6e..9c1df853030 100644
--- a/engines/comfy/metaengine.cpp
+++ b/engines/comfy/metaengine.cpp
@@ -69,16 +69,16 @@ Common::KeymapArray ComfyMetaEngine::initKeymaps(const char *target) const {
 	using namespace Common;
 
 	static const char *actionIds[COMFY_KEYBOARD_CONTACT_COUNT] = {
-		"SUN", "ROLL", "RED", "DRUM", "SNAILY", "FUCHSIA", "PIANO", "POWER",
+		"SUN", "ROLL", "RED", "DRUM", "SNAILY", "PURPLE", "PIANO", "POWER",
 		"ORANGE", "MOON", "JUMPY", "YELLOW", "STOP", "HANDSET", "BLUE", "TRUMPET",
-		"BUDDY", "GREEN", "FLUTE", "CONTACT19", "COMFY", "CLOUD", "PHILLY", "MUSIC"
+		"BUDDY", "GREEN", "FLUTE", "CONTACT19", "COMFY", "CLOUD", "FEELY", "MUSIC"
 	};
 	static const char *actionNames[COMFY_KEYBOARD_CONTACT_COUNT] = {
-		_s("Sun"), _s("Rolling cylinder"), _s("Red"), _s("Drum"), _s("Snaily phone"), _s("Fuchsia"),
+		_s("Sun"), _s("Rolling cylinder"), _s("Red"), _s("Drum"), _s("Snaily phone"), _s("Purple"),
 		_s("Piano"), _s("Power"), _s("Orange"), _s("Moon"), _s("Jumpy phone"), _s("Yellow"),
 		_s("Stop"), _s("Handset"), _s("Blue"), _s("Trumpet"), _s("Buddy phone"), _s("Green"),
 		_s("Flute"), _s("Keyboard contact 19"), _s("Comfy phone"), _s("Rainy cloud"),
-		_s("Philly phone"), _s("Music")
+		_s("Feely phone"), _s("Music")
 	};
 	static const char *defaultMappings[COMFY_KEYBOARD_CONTACT_COUNT] = {
 		"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "q", "w",
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index 409cdeb90bd..7bfe7d34061 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -19,7 +19,46 @@
  *
  */
 
+#include "comfy/comfy.h"
+
 namespace Comfy {
 
+bool ComfyEngine::sceneOpen() {
+	if (_sceneOpen)
+		sceneClose();
+
+	if (_comfyObjData.empty() || _picFileData.empty() || _midiFileData.empty() || !midiPlyrStart())
+		return false;
+
+	paletteLoadWithFade(0, 0);
+	framebufClear(0);
+	int16 y = 0;
+	for (uint spriteId = 1; spriteId < _spriteHeaders.size() && y < int16(_logicalScreenHeight); spriteId++) {
+		SpriteObjectHeader &header = _spriteHeaders[spriteId];
+		if (header.width != _logicalScreenWidth || !header.height || y + header.height > _logicalScreenHeight)
+			continue;
+
+		spriteBlitClipped(spriteId, 0, y);
+		y += header.height;
+	}
+
+	_sceneOpen = true;
+	renderSetDirty();
+	return true;
+}
+
+void ComfyEngine::sceneClose() {
+	if (!_sceneOpen)
+		return;
+
+	midiPlyrStop();
+	for (uint i = 0; i < _spriteResources.size(); i++) {
+		_spriteResources[i].pixels.clear();
+		_spriteResources[i].loaded = false;
+	}
+
+	_sceneOpen = false;
+}
+
 
 } // End of namespace Comfy


Commit: ebb4bf398cdba5862a58a184675e129767ef2b09
    https://github.com/scummvm/scummvm/commit/ebb4bf398cdba5862a58a184675e129767ef2b09
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Implement bulk of the scripting engine

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/expr.cpp
    engines/comfy/game.cpp
    engines/comfy/scene.cpp
    engines/comfy/script.cpp
    engines/comfy/script_vm.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index 9c59ec4336a..329bed0ddaf 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -137,14 +137,17 @@ bool ComfyEngine::spriteDecompressTile(SpriteResource &sprite, const byte *sourc
 	return outputPos == outputSize;
 }
 
-bool ComfyEngine::spriteLoad(uint16 spriteId) {
-	if (spriteId >= _spriteResources.size())
+bool ComfyEngine::spriteLoad(int16 spriteId) {
+	if (spriteId <= 0 || uint16(spriteId) >= _spriteResources.size())
 		return false;
 
 	SpriteResource &sprite = _spriteResources[spriteId];
-	if (sprite.loaded)
+	if (sprite.loaded && _objectCacheEntries[spriteId].slotSize != 0xFFFF)
 		return true;
 
+	sprite.loaded = false;
+	sprite.pixels.clear();
+
 	SpriteObjectHeader &header = sprite.header;
 	if (!header.dataSize || header.fileOffset > _picFileData.size() ||
 			header.dataSize > _picFileData.size() - header.fileOffset)
@@ -160,9 +163,59 @@ bool ComfyEngine::spriteLoad(uint16 spriteId) {
 	}
 
 	sprite.loaded = true;
+	uint32 slotSize = (sprite.pixels.size() + (sprite.pixels.size() & 1) + 0x0C);
+	if (slotSize <= _scenePoolData.size()) {
+		if (_scenePoolCursor > _scenePoolData.size() - slotSize) {
+			_scenePoolCursor = 0;
+			_scenePoolEvictCursor = 0;
+			for (uint i = 0; i < _objectCacheEntries.size(); i++)
+				_objectCacheEntries[i].slotSize = 0xFFFF;
+
+			for (uint i = 0; i < _frameCacheEntries.size(); i++)
+				_frameCacheEntries[i].slotSize = 0xFFFF;
+		}
+
+		SpriteCacheEntry &entry = _objectCacheEntries[spriteId];
+		entry.poolOffset = _scenePoolCursor;
+		entry.slotSize = slotSize;
+		WRITE_LE_UINT16(&_scenePoolData[_scenePoolCursor], uint16(spriteId));
+		WRITE_LE_UINT16(&_scenePoolData[_scenePoolCursor + 2], slotSize);
+		memcpy(&_scenePoolData[_scenePoolCursor + 0x0C], &sprite.pixels[0], sprite.pixels.size());
+		_scenePoolCursor += slotSize;
+	}
+
 	return true;
 }
 
+ComfyEngine::SpriteResource *ComfyEngine::spriteGet(int16 spriteId) {
+	if (spriteId > 0)
+		return spriteLoad(spriteId) ? &_spriteResources[spriteId] : nullptr;
+
+	if (!spriteId)
+		return nullptr;
+
+	uint16 tile = uint16(-spriteId) - 1;
+	uint32 offset = uint32(tile) * COMFY_TILE_SIZE;
+	if (offset >= _picDataSize || offset >= _comfyObjData.size())
+		return nullptr;
+
+	uint32 size = MIN<uint32>(COMFY_TILE_SIZE, MIN<uint32>(_picDataSize - offset, _comfyObjData.size() - offset));
+	_frameSpriteResource.id = spriteId;
+	memset(&_frameSpriteResource.header, 0, sizeof(_frameSpriteResource.header));
+	_frameSpriteResource.header.dataSize = size;
+	_frameSpriteResource.header.tiledSize = size;
+	_frameSpriteResource.pixels.resize(size);
+	memcpy(&_frameSpriteResource.pixels[0], &_comfyObjData[offset], size);
+	_frameSpriteResource.loaded = true;
+	if (uint16(-spriteId) < _frameCacheEntries.size()) {
+		SpriteCacheEntry &entry = _frameCacheEntries[-spriteId];
+		entry.poolOffset = offset;
+		entry.slotSize = uint16(size + (size & 1) + 0x0C);
+	}
+
+	return &_frameSpriteResource;
+}
+
 void ComfyEngine::spriteBlitRle(const byte *source, uint32 sourceSize) {
 	if (!_framebufPtr || !source)
 		return;
@@ -194,11 +247,12 @@ void ComfyEngine::spriteBlitRle(const byte *source, uint32 sourceSize) {
 	}
 }
 
-void ComfyEngine::spriteBlitClipped(uint16 spriteId, int16 x, int16 y) {
-	if (!spriteLoad(spriteId))
+void ComfyEngine::spriteBlitClipped(int16 spriteId, int16 x, int16 y) {
+	SpriteResource *loadedSprite = spriteGet(spriteId);
+	if (!loadedSprite)
 		return;
 
-	SpriteResource &sprite = _spriteResources[spriteId];
+	SpriteResource &sprite = *loadedSprite;
 	if (sprite.header.width == _logicalScreenWidth && sprite.header.height == _logicalScreenHeight) {
 		spriteBlitRle(&sprite.pixels[0], sprite.pixels.size());
 		renderSetDirty();
@@ -223,8 +277,9 @@ void ComfyEngine::spriteBlitClipped(uint16 spriteId, int16 x, int16 y) {
 
 				byte value = sprite.pixels[packetPos++];
 				for (uint i = 0; i < count; i++, drawX++) {
-					if (drawX >= 0 && drawX < int16(_logicalScreenWidth) && drawY >= 0 && drawY < int16(_logicalScreenHeight))
-						_framebufPtr[drawY * _logicalScreenWidth + drawX] = value;
+					int16 screenX = _mirrorMode ? int16(_logicalScreenWidth - 1 - drawX) : drawX;
+					if (screenX >= 0 && screenX < int16(_logicalScreenWidth) && drawY >= 0 && drawY < int16(_logicalScreenHeight))
+						_framebufPtr[drawY * _logicalScreenWidth + screenX] = value;
 				}
 			} else if (op & 0x40) {
 				drawX += count;
@@ -234,8 +289,9 @@ void ComfyEngine::spriteBlitClipped(uint16 spriteId, int16 x, int16 y) {
 
 				for (uint i = 0; i < count; i++, drawX++) {
 					byte value = sprite.pixels[packetPos++];
-					if (drawX >= 0 && drawX < int16(_logicalScreenWidth) && drawY >= 0 && drawY < int16(_logicalScreenHeight))
-						_framebufPtr[drawY * _logicalScreenWidth + drawX] = value;
+					int16 screenX = _mirrorMode ? int16(_logicalScreenWidth - 1 - drawX) : drawX;
+					if (screenX >= 0 && screenX < int16(_logicalScreenWidth) && drawY >= 0 && drawY < int16(_logicalScreenHeight))
+						_framebufPtr[drawY * _logicalScreenWidth + screenX] = value;
 				}
 			}
 		}
@@ -246,5 +302,442 @@ void ComfyEngine::spriteBlitClipped(uint16 spriteId, int16 x, int16 y) {
 	renderSetDirty();
 }
 
+uint32 ComfyEngine::actorReadDword(Actor &actor, uint offset) {
+	if (offset + 4 > COMFY_ACTOR_SIZE) {
+		_scriptFault = true;
+		return 0;
+	}
+
+	return READ_LE_UINT32(actor.raw + offset);
+}
+
+uint16 ComfyEngine::actorReadWord(Actor &actor, uint offset) {
+	if (offset + 2 > COMFY_ACTOR_SIZE) {
+		_scriptFault = true;
+		return 0;
+	}
+
+	return READ_LE_UINT16(actor.raw + offset);
+}
+
+byte ComfyEngine::actorReadByte(Actor &actor, uint offset) {
+	if (offset >= COMFY_ACTOR_SIZE) {
+		_scriptFault = true;
+		return 0;
+	}
+
+	return actor.raw[offset];
+}
+
+void ComfyEngine::actorWriteDword(Actor &actor, uint offset, uint32 value) {
+	if (offset + 4 <= COMFY_ACTOR_SIZE)
+		WRITE_LE_UINT32(actor.raw + offset, value);
+	else
+		_scriptFault = true;
+}
+
+void ComfyEngine::actorWriteWord(Actor &actor, uint offset, uint16 value) {
+	if (offset + 2 <= COMFY_ACTOR_SIZE)
+		WRITE_LE_UINT16(actor.raw + offset, value);
+	else
+		_scriptFault = true;
+}
+
+void ComfyEngine::actorWriteByte(Actor &actor, uint offset, byte value) {
+	if (offset < COMFY_ACTOR_SIZE)
+		actor.raw[offset] = value;
+	else
+		_scriptFault = true;
+}
+
+ComfyEngine::Actor *ComfyEngine::actorGet(uint16 actorIndex) {
+	return actorIndex < _actors.size() ? &_actors[actorIndex] : nullptr;
+}
+
+ComfyEngine::Actor *ComfyEngine::actorResolve(uint16 sceneOrActor, uint16 fallbackActor) {
+	if (!sceneOrActor)
+		return actorGet(fallbackActor);
+
+	return sceneOrActor < _sceneHandles.size() ? actorGet(_sceneHandles[sceneOrActor]) : nullptr;
+}
+
+uint16 ComfyEngine::actorAllocate(uint16 sceneSlot) {
+	Actor *root = actorGet(0);
+	uint16 actorIndex = root ? actorReadWord(*root, kActorNextLink) : 0;
+	if (!actorIndex || sceneSlot >= _sceneHandles.size())
+		return 0;
+
+	Actor *actor = actorGet(actorIndex);
+	actorWriteWord(*root, kActorNextLink, actorReadWord(*actor, kActorNextLink));
+	_sceneHandles[sceneSlot] = actorIndex;
+	actorWriteWord(*actor, kActorSceneHandle, sceneSlot);
+	return actorIndex;
+}
+
+void ComfyEngine::actorFree(uint16 sceneSlot) {
+	if (sceneSlot >= _sceneHandles.size())
+		return;
+
+	uint16 actorIndex = _sceneHandles[sceneSlot];
+	Actor *actor = actorGet(actorIndex);
+	if (!actor)
+		return;
+
+	Actor *root = actorGet(0);
+	actorWriteWord(*actor, kActorNextLink, root ? actorReadWord(*root, kActorNextLink) : 0);
+	actorWriteWord(*actor, kActorSceneHandle, 0);
+	if (root)
+		actorWriteWord(*root, kActorNextLink, actorIndex);
+	_sceneHandles[sceneSlot] = 0;
+}
+
+void ComfyEngine::actorInsertChild(uint16 childIndex, uint16 parentIndex) {
+	Actor *child = actorGet(childIndex);
+	Actor *parent = actorGet(parentIndex);
+	if (!child || !parent)
+		return;
+
+	uint16 tail = actorReadWord(*parent, kActorChildTail);
+	if (tail) {
+		actorWriteWord(*actorGet(tail), kActorNextLink, childIndex);
+		actorWriteWord(*child, kActorPrevLink, tail);
+	} else {
+		actorWriteWord(*parent, kActorChildHead, childIndex);
+		actorWriteWord(*child, kActorPrevLink, 0);
+	}
+
+	actorWriteWord(*child, kActorNextLink, 0);
+	actorWriteWord(*parent, kActorChildTail, childIndex);
+}
+
+void ComfyEngine::actorInsertSibling(uint16 actorIndex, uint16 ownerIndex) {
+	Actor *actor = actorGet(actorIndex);
+	Actor *owner = actorGet(ownerIndex);
+	if (!actor || !owner)
+		return;
+
+	uint16 head = actorReadWord(*owner, kActorSiblingHead);
+	if (head)
+		actorWriteWord(*actorGet(head), kActorPrevLink, actorIndex);
+
+	actorWriteWord(*actor, kActorNextLink, head);
+	actorWriteWord(*actor, kActorPrevLink, 0);
+	actorWriteWord(*owner, kActorSiblingHead, actorIndex);
+}
+
+void ComfyEngine::actorUnlink(uint16 actorIndex) {
+	Actor *actor = actorGet(actorIndex);
+	if (!actor)
+		return;
+
+	Actor *parent = actorGet(actorReadWord(*actor, kActorParent));
+	if (!parent)
+		return;
+
+	uint16 next = actorReadWord(*actor, kActorNextLink);
+	uint16 previous = actorReadWord(*actor, kActorPrevLink);
+	if (next)
+		actorWriteWord(*actorGet(next), kActorPrevLink, previous);
+	else if (actorReadWord(*parent, kActorChildTail) == actorIndex)
+		actorWriteWord(*parent, kActorChildTail, previous);
+
+	if (previous)
+		actorWriteWord(*actorGet(previous), kActorNextLink, next);
+	else if (actorReadWord(*parent, kActorSiblingHead) == actorIndex)
+		actorWriteWord(*parent, kActorSiblingHead, next);
+	else
+		actorWriteWord(*parent, kActorChildHead, next);
+}
+
+uint16 ComfyEngine::actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible, byte active,
+		uint32 pc, int16 x, int16 y, int16 sprite, byte insertAsChild) {
+	uint16 actorIndex = actorAllocate(sceneSlot);
+	Actor *actor = actorGet(actorIndex);
+	if (!actor)
+		return 8;
+
+	actorWriteWord(*actor, kActorSceneHandle, sceneSlot);
+	actorWriteByte(*actor, kActorVisible, visible);
+	actorWriteByte(*actor, kActorActive, active);
+	actorWriteDword(*actor, kActorCurrentPc, pc);
+	actorWriteDword(*actor, kActorResetPc, pc);
+	actorWriteDword(*actor, kActorXFixed, uint32(int32(x) * 0x1000));
+	actorWriteDword(*actor, kActorYFixed, uint32(int32(y) * 0x1000));
+	actorWriteDword(*actor, kActorSpriteSelector, uint32(int32(sprite)));
+	actorWriteByte(*actor, kActorDirty, 1);
+
+	if (parentSlot) {
+		uint16 parentIndex = parentSlot < _sceneHandles.size() ? _sceneHandles[parentSlot] : 0;
+		actorWriteWord(*actor, kActorParent, parentIndex);
+		if (insertAsChild)
+			actorInsertChild(actorIndex, parentIndex);
+		else
+			actorInsertSibling(actorIndex, parentIndex);
+	}
+
+	return 1;
+}
+
+void ComfyEngine::actorSetPc(Actor &actor, uint32 pc) {
+	uint32 previous = actorReadDword(actor, kActorCallPc);
+	uint32 packed = pc;
+	if (previous) {
+		byte entry = _actorPcTable[0] >> 24;
+		if (!entry || entry >= COMFY_ACTOR_PC_TABLE_COUNT) {
+			_scriptFault = true;
+			return;
+		}
+
+		_actorPcTable[0] = _actorPcTable[entry];
+		_actorPcTable[entry] = previous;
+		if (_sceneActorPcOffset + sizeof(_actorPcTable) <= _sceneMemoryBlock.size()) {
+			WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneActorPcOffset], _actorPcTable[0]);
+			WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneActorPcOffset + entry * 4], _actorPcTable[entry]);
+		}
+
+		packed = (uint32(entry) << 24) | (pc & 0x00FFFFFF);
+	}
+
+	actorWriteDword(actor, kActorCallPc, packed);
+}
+
+uint32 ComfyEngine::actorPopPc(Actor &actor) {
+	uint32 packed = actorReadDword(actor, kActorCallPc);
+	byte entry = packed >> 24;
+	if (entry && entry < COMFY_ACTOR_PC_TABLE_COUNT) {
+		actorWriteDword(actor, kActorCallPc, _actorPcTable[entry]);
+		_actorPcTable[entry] = _actorPcTable[0];
+		_actorPcTable[0] = uint32(entry) << 24;
+		if (_sceneActorPcOffset + sizeof(_actorPcTable) <= _sceneMemoryBlock.size()) {
+			WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneActorPcOffset], _actorPcTable[0]);
+			WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneActorPcOffset + entry * 4], _actorPcTable[entry]);
+		}
+	} else {
+		actorWriteDword(actor, kActorCallPc, 0);
+	}
+
+	return packed & 0x00FFFFFF;
+}
+
+void ComfyEngine::actorFreePcChain(Actor &actor) {
+	byte first = actorReadDword(actor, kActorCallPc) >> 24;
+	byte entry = first;
+	while (entry && entry < COMFY_ACTOR_PC_TABLE_COUNT) {
+		byte next = _actorPcTable[entry] >> 24;
+		if (!next) {
+			_actorPcTable[entry] = _actorPcTable[0];
+			_actorPcTable[0] = uint32(first) << 24;
+			if (_sceneActorPcOffset + sizeof(_actorPcTable) <= _sceneMemoryBlock.size())
+				memcpy(&_sceneMemoryBlock[_sceneActorPcOffset], _actorPcTable, sizeof(_actorPcTable));
+
+			break;
+		}
+
+		_actorPcTable[entry] &= 0xFF000000;
+		entry = next;
+	}
+
+	actorWriteDword(actor, kActorCallPc, 0);
+}
+
+void ComfyEngine::actorFreeTree(uint16 actorIndex) {
+	Actor *actor = actorGet(actorIndex);
+	if (!actor)
+		return;
+
+	uint16 child = actorReadWord(*actor, kActorSiblingHead);
+	while (child) {
+		Actor *childActor = actorGet(child);
+		uint16 next = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+		actorFreeTree(child);
+		child = next;
+	}
+
+	child = actorReadWord(*actor, kActorChildHead);
+	while (child) {
+		Actor *childActor = actorGet(child);
+		uint16 next = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+		actorFreeTree(child);
+		child = next;
+	}
+
+	uint16 sceneSlot = actorReadWord(*actor, kActorSceneHandle);
+	actorFreePcChain(*actor);
+	actorFree(sceneSlot);
+}
+
+void ComfyEngine::actorClearDirtyTree(uint16 actorIndex) {
+	Actor *actor = actorGet(actorIndex);
+	if (!actor)
+		return;
+
+	actorWriteByte(*actor, kActorDirty, 0);
+	uint16 child = actorReadWord(*actor, kActorSiblingHead);
+	while (child) {
+		Actor *childActor = actorGet(child);
+		uint16 next = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+		actorClearDirtyTree(child);
+		child = next;
+	}
+
+	child = actorReadWord(*actor, kActorChildHead);
+	while (child) {
+		Actor *childActor = actorGet(child);
+		uint16 next = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+		actorClearDirtyTree(child);
+		child = next;
+	}
+}
+
+bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
+	Actor *actor = actorGet(actorIndex);
+	descendChildren = false;
+	if (!actor)
+		return false;
+
+	_currentActor = actorIndex;
+	_actorDestroyedCurrent = false;
+	if (_stringTable.size() > 3) {
+		_stringTable[2] = actorReadWord(*actor, kActorStringRef);
+		_stringTable[3] = actorReadWord(*actor, kActorStringRef + 2);
+	}
+
+	uint16 triggerKey = actorReadWord(*actor, kActorTriggerKey);
+	if (triggerKey && keyBitTest(triggerKey)) {
+		byte triggerFlags = actorReadByte(*actor, kActorTriggerFlags);
+		if (triggerFlags & 1)
+			actorSetPc(*actor, actorReadDword(*actor, kActorCurrentPc));
+
+		if (triggerFlags & 4)
+			keyBitClear(triggerKey);
+
+		if (triggerFlags & 2)
+			actorWriteWord(*actor, kActorTriggerKey, 0);
+
+		actorWriteWord(*actor, kActorWaitTarget, 0);
+		actorWriteWord(*actor, kActorWaitAccum, 0);
+		actorWriteDword(*actor, kActorCurrentPc, actorReadDword(*actor, kActorTriggerPc));
+	}
+
+	int16 moveTicks = actorReadWord(*actor, kActorMoveTicks);
+	if (moveTicks) {
+		int16 stepTicks = int16(uint16(_timerCurrent + _timer0 + _timer1 + _timer2 + 2)) / 4;
+		if (stepTicks > 20)
+			stepTicks = 20;
+
+		if (moveTicks < stepTicks) {
+			moveTicks = stepTicks;
+			actorWriteWord(*actor, kActorMoveTicks, moveTicks);
+		}
+
+		int32 moveDx = actorReadDword(*actor, kActorMoveDx);
+		int32 moveDy = actorReadDword(*actor, kActorMoveDy);
+		int32 stepDx = (int32(stepTicks) * moveDx) / moveTicks;
+		int32 stepDy = (int32(stepTicks) * moveDy) / moveTicks;
+		actorWriteDword(*actor, kActorXFixed, actorReadDword(*actor, kActorXFixed) + stepDx);
+		actorWriteDword(*actor, kActorYFixed, actorReadDword(*actor, kActorYFixed) + stepDy);
+		actorWriteDword(*actor, kActorMoveDx, moveDx - stepDx);
+		actorWriteDword(*actor, kActorMoveDy, moveDy - stepDy);
+		moveTicks -= stepTicks;
+		if (moveTicks < 0)
+			moveTicks = 0;
+
+		actorWriteWord(*actor, kActorMoveTicks, moveTicks);
+		if (moveTicks && actorReadByte(*actor, kActorBlockingMove)) {
+			if (_stringTable.size() > 3) {
+				actorWriteWord(*actor, kActorStringRef, _stringTable[2]);
+				actorWriteWord(*actor, kActorStringRef + 2, _stringTable[3]);
+			}
+
+			descendChildren = true;
+			return false;
+		}
+
+		if (!moveTicks && actorReadWord(*actor, kActorCompletionKey))
+			keyBitSet(actorReadWord(*actor, kActorCompletionKey));
+	}
+
+	int16 waitTarget = actorReadWord(*actor, kActorWaitTarget);
+	if (waitTarget) {
+		if (waitTarget > _timerCurrent) {
+			actorWriteWord(*actor, kActorWaitTarget, waitTarget - _timerCurrent);
+			if (_stringTable.size() > 3) {
+				actorWriteWord(*actor, kActorStringRef, _stringTable[2]);
+				actorWriteWord(*actor, kActorStringRef + 2, _stringTable[3]);
+			}
+
+			descendChildren = true;
+			return false;
+		}
+
+		int16 elapsed = _timerCurrent - waitTarget;
+		actorWriteWord(*actor, kActorWaitAccum, actorReadWord(*actor, kActorWaitAccum) + elapsed);
+		actorWriteWord(*actor, kActorWaitTarget, 0);
+	}
+
+	uint32 pc = actorReadDword(*actor, kActorCurrentPc);
+	for (;;) {
+		ScriptDispatchStatus status = scriptStep(*actor, pc);
+		if (status == kScriptContinue) {
+			actorWriteDword(*actor, kActorCurrentPc, pc);
+			continue;
+		}
+
+		if (status == kScriptYield && _stringTable.size() > 3) {
+			actorWriteWord(*actor, kActorStringRef, _stringTable[2]);
+			actorWriteWord(*actor, kActorStringRef + 2, _stringTable[3]);
+		}
+
+		descendChildren = status == kScriptYield && !_actorDestroyedCurrent;
+		return status == kScriptDeactivatedRoot || _actorDestroyedCurrent;
+	}
+}
+
+bool ComfyEngine::actorTickTreeInternal(uint16 actorIndex) {
+	if (_pendingScene)
+		return false;
+
+	Actor *actor = actorGet(actorIndex);
+	if (!actor)
+		return false;
+
+	if (!actorReadByte(*actor, kActorActive)) {
+		actorClearDirtyTree(actorIndex);
+		return false;
+	}
+
+	bool descendChildren = true;
+	bool stopBranch = actorRunScript(actorIndex, descendChildren);
+	actor = actorGet(actorIndex);
+	if (stopBranch || !descendChildren || !actor)
+		return stopBranch;
+
+	uint16 child = actorReadWord(*actor, kActorSiblingHead);
+	while (child) {
+		Actor *childActor = actorGet(child);
+		uint16 savedNext = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+		if (actorTickTreeInternal(child))
+			child = savedNext;
+		else {
+			childActor = actorGet(child);
+			child = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+		}
+	}
+
+	child = actorReadWord(*actor, kActorChildHead);
+	while (child) {
+		Actor *childActor = actorGet(child);
+		uint16 savedNext = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+		if (actorTickTreeInternal(child))
+			child = savedNext;
+		else {
+			childActor = actorGet(child);
+			child = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+		}
+	}
+
+	return false;
+}
+
 
 } // End of namespace Comfy
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index ad79f592a57..9312719989c 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -68,6 +68,13 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Eng
 	_keyboardUiInitialized(false), _keyboardUiVisible(true),
 	_stringCount(0), _sceneCount(0), _keyBitCount(0), _resourceHandleCount(0), _midiEntryCount(0),
 	_picDataSize(0), _usesAnimFile(false), _sceneOpen(false),
+	_sceneMidiInstanceOffset(0), _sceneEntryListOffset(0), _sceneActorPcOffset(0), _sceneStringTableOffset(0),
+	_sceneHandlesOffset(0), _sceneActorsOffset(0), _sceneKeyBitsOffset(0), _scenePoolCursor(0),
+	_scenePoolEvictCursor(0), _activeSceneCount(0), _sceneEntryCount(0), _sceneEntryFrameSize(0),
+	_numObjects(0), _numFrames(0), _numSprites(0), _envNumSprites(0), _midiFileMode(0), _mirrorMode(false),
+	_currentActor(0), _pendingScene(0), _musicEventMask(0), _musicEventFlag(0), _musicEnabled(true),
+	_usesWcomfy99ScriptOps(false), _actorDestroyedCurrent(false),
+	_exprStackTop(0), _scriptFault(false),
 	_gameInitialized(false), _videoInitialized(false),
 	_timerInitialized(false), _lptKeyboardInitialized(false), _mainLoopRunning(false) {
 	memset(_paletteFadeSource, 0, sizeof(_paletteFadeSource));
@@ -240,9 +247,26 @@ void ComfyEngine::midiPollChannels(uint16 ticks) {
 }
 
 void ComfyEngine::actorTickTree() {
+	if (_sceneHandles.size() > 1 && _sceneHandles[1])
+		actorTickTreeInternal(_sceneHandles[1]);
+
+	scenePackRuntimeState();
 }
 
 void ComfyEngine::renderFrame() {
+	Actor *root = actorGet(0);
+	uint16 frame = root ? actorReadDword(*root, kActorSpriteSelector) : 0;
+	if (frame) {
+		SpriteResource *background = spriteGet(int16(frame));
+		if (background && background->header.width == _logicalScreenWidth &&
+				background->header.height == _logicalScreenHeight && !background->pixels.empty()) {
+			spriteBlitRle(&background->pixels[0], background->pixels.size());
+		} else {
+			uint16 clear = background && background->pixels.size() > 3 ? background->pixels[3] : 0;
+			framebufClear(clear);
+		}
+	}
+
 	videoPresentFrame();
 }
 
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index b6a5cdcc944..14bebc0ecf4 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -49,6 +49,16 @@
 #define COMFY_PALETTE_BYTES 0x300
 #define COMFY_INPUT_QUEUE_CAPACITY 20
 #define COMFY_KEYBOARD_CONTACT_COUNT 24
+#define COMFY_ACTOR_SIZE 0x54
+#define COMFY_ACTOR_COUNT 0x79
+#define COMFY_EXPR_STACK_CAPACITY 64
+#define COMFY_ACTOR_PC_TABLE_COUNT 200
+#define COMFY_TILE_SIZE 0x800
+#define COMFY_RESOURCE_LIST_CAPACITY 32
+#define COMFY_SCENE_ENTRY_OFFSET_CAPACITY 16
+#define COMFY_SCENE_MIDI_INSTANCE_BYTES 0x18C
+#define COMFY_SCENE_ACTOR_PC_BYTES 0x320
+#define COMFY_SCENE_FRAME_BYTES 0x4E20
 
 namespace Comfy {
 
@@ -95,11 +105,66 @@ private:
 	};
 
 	struct SpriteResource {
+		int16 id;
 		SpriteObjectHeader header;
 		Common::Array<byte> pixels;
 		bool loaded;
 	};
 
+	struct SpriteCacheEntry {
+		uint32 poolOffset;
+		uint16 slotSize;
+	};
+
+	struct ResourceLoadList {
+		uint16 ids[COMFY_RESOURCE_LIST_CAPACITY];
+		uint16 count;
+	};
+
+	struct Actor {
+		byte raw[COMFY_ACTOR_SIZE];
+	};
+
+	enum ActorOffset {
+		kActorCurrentPc = 0x00,
+		kActorCallPc = 0x04,
+		kActorResetPc = 0x08,
+		kActorXFixed = 0x0C,
+		kActorYFixed = 0x10,
+		kActorSpriteSelector = 0x14,
+		kActorMoveDx = 0x18,
+		kActorMoveDy = 0x1C,
+		kActorTriggerPc = 0x20,
+		kActorStringRef = 0x24,
+		kActorSceneHandle = 0x28,
+		kActorVisible = 0x2A,
+		kActorActive = 0x2B,
+		kActorParent = 0x2C,
+		kActorChildTail = 0x2E,
+		kActorChildHead = 0x30,
+		kActorSiblingHead = 0x32,
+		kActorNextLink = 0x34,
+		kActorPrevLink = 0x36,
+		kActorMoveTicks = 0x38,
+		kActorBlockingMove = 0x3A,
+		kActorCompletionKey = 0x3B,
+		kActorTriggerKey = 0x3D,
+		kActorTriggerFlags = 0x3F,
+		kActorWaitTarget = 0x40,
+		kActorWaitAccum = 0x42,
+		kActorDirty = 0x44,
+		kActorCachedRect = 0x45,
+		kActorCachedVisible = 0x4F,
+		kActorCachedSprite = 0x50
+	};
+
+	enum ScriptDispatchStatus {
+		kScriptUnhandled,
+		kScriptContinue,
+		kScriptYield,
+		kScriptDeactivatedRoot
+	};
+
 	const ADGameDescription *_gameDescription;
 	ComfyEngineVersion _engineVersion;
 	Common::Path _gameDirectory;
@@ -161,6 +226,7 @@ private:
 	Common::Array<byte> _midiFileData;
 	Common::Array<SpriteObjectHeader> _spriteHeaders;
 	Common::Array<SpriteResource> _spriteResources;
+	SpriteResource _frameSpriteResource;
 	uint16 _stringCount;
 	uint16 _sceneCount;
 	uint16 _keyBitCount;
@@ -169,6 +235,47 @@ private:
 	uint32 _picDataSize;
 	bool _usesAnimFile;
 	bool _sceneOpen;
+	Common::Array<uint16> _stringTable;
+	Common::Array<uint16> _sceneHandles;
+	Common::Array<uint16> _midiHandles;
+	Common::Array<Actor> _actors;
+	Common::Array<byte> _sceneMemoryBlock;
+	Common::Array<byte> _scenePoolData;
+	Common::Array<byte> _environmentData;
+	Common::Array<byte> _sceneFrameData;
+	Common::Array<SpriteCacheEntry> _objectCacheEntries;
+	Common::Array<SpriteCacheEntry> _frameCacheEntries;
+	ResourceLoadList _spriteConversionLoads;
+	uint32 _sceneEntryOffsets[COMFY_SCENE_ENTRY_OFFSET_CAPACITY];
+	uint32 _sceneMidiInstanceOffset;
+	uint32 _sceneEntryListOffset;
+	uint32 _sceneActorPcOffset;
+	uint32 _sceneStringTableOffset;
+	uint32 _sceneHandlesOffset;
+	uint32 _sceneActorsOffset;
+	uint32 _sceneKeyBitsOffset;
+	uint32 _scenePoolCursor;
+	uint32 _scenePoolEvictCursor;
+	uint16 _activeSceneCount;
+	uint16 _sceneEntryCount;
+	uint16 _sceneEntryFrameSize;
+	uint16 _numObjects;
+	uint16 _numFrames;
+	uint32 _numSprites;
+	uint32 _envNumSprites;
+	byte _midiFileMode;
+	bool _mirrorMode;
+	uint32 _actorPcTable[COMFY_ACTOR_PC_TABLE_COUNT];
+	uint16 _currentActor;
+	uint16 _pendingScene;
+	uint16 _musicEventMask;
+	byte _musicEventFlag;
+	bool _musicEnabled;
+	bool _usesWcomfy99ScriptOps;
+	bool _actorDestroyedCurrent;
+	uint16 _exprStack[COMFY_EXPR_STACK_CAPACITY];
+	uint16 _exprStackTop;
+	bool _scriptFault;
 	bool _gameInitialized;
 	bool _videoInitialized;
 	bool _timerInitialized;
@@ -237,12 +344,50 @@ private:
 	bool comfyObjOpen();
 	bool picFileOpen();
 	bool midiFileOpen();
-	bool spriteLoad(uint16 spriteId);
+	bool spriteLoad(int16 spriteId);
+	SpriteResource *spriteGet(int16 spriteId);
 	bool spriteDecompressTile(SpriteResource &sprite, const byte *source, uint32 sourceSize);
-	void spriteBlitClipped(uint16 spriteId, int16 x, int16 y);
+	void spriteBlitClipped(int16 spriteId, int16 x, int16 y);
 	void spriteBlitRle(const byte *source, uint32 sourceSize);
 	bool sceneOpen();
 	void sceneClose();
+	void scenePackRuntimeState();
+	bool environmentLoad(uint16 index);
+	bool environmentStore(uint16 index);
+	void sceneGoto(uint16 count);
+	void sceneStop();
+	bool sceneEntryLoad(uint16 descriptor, uint16 index);
+	bool scriptHasRange(uint32 pc, uint32 width);
+	byte scriptReadByte(uint32 pc);
+	uint16 scriptReadWord(uint32 pc);
+	uint32 scriptReadDword(uint32 pc);
+	uint16 scriptReadStringIndex(uint32 pc);
+	uint32 scriptReadArgs(uint32 pc, uint16 fallbackActor, const char *format, ...);
+	uint16 scriptEvalExpr(uint32 &pc, uint16 fallbackActor);
+	ScriptDispatchStatus scriptDispatch(Actor &actor, byte opcode, uint32 &pc);
+	ScriptDispatchStatus scriptStep(Actor &actor, uint32 &pc);
+	uint32 actorReadDword(Actor &actor, uint offset);
+	uint16 actorReadWord(Actor &actor, uint offset);
+	byte actorReadByte(Actor &actor, uint offset);
+	void actorWriteDword(Actor &actor, uint offset, uint32 value);
+	void actorWriteWord(Actor &actor, uint offset, uint16 value);
+	void actorWriteByte(Actor &actor, uint offset, byte value);
+	Actor *actorGet(uint16 actorIndex);
+	Actor *actorResolve(uint16 sceneOrActor, uint16 fallbackActor);
+	uint16 actorAllocate(uint16 sceneSlot);
+	void actorFree(uint16 sceneSlot);
+	void actorInsertChild(uint16 childIndex, uint16 parentIndex);
+	void actorInsertSibling(uint16 actorIndex, uint16 ownerIndex);
+	void actorUnlink(uint16 actorIndex);
+	void actorSetPc(Actor &actor, uint32 pc);
+	uint32 actorPopPc(Actor &actor);
+	void actorFreePcChain(Actor &actor);
+	void actorFreeTree(uint16 actorIndex);
+	void actorClearDirtyTree(uint16 actorIndex);
+	uint16 actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible, byte active,
+		uint32 pc, int16 x, int16 y, int16 sprite, byte insertAsChild);
+	bool actorRunScript(uint16 actorIndex, bool &descendChildren);
+	bool actorTickTreeInternal(uint16 actorIndex);
 	void timerInit();
 	void timerShutdown();
 	void lptKeyboardInit();
diff --git a/engines/comfy/expr.cpp b/engines/comfy/expr.cpp
index 409cdeb90bd..30c9d3415fa 100644
--- a/engines/comfy/expr.cpp
+++ b/engines/comfy/expr.cpp
@@ -19,7 +19,118 @@
  *
  */
 
+#include "comfy/comfy.h"
+
 namespace Comfy {
 
+uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
+	_exprStackTop = 0;
+	for (;;) {
+		byte opcode = scriptReadByte(pc++);
+		if (_scriptFault)
+			return 0;
+
+		if (opcode == 0x0D)
+			return _exprStackTop ? _exprStack[0] : 0;
+
+		if (opcode == 0x01 || opcode == 0x03 || opcode == 0x15) {
+			if (_exprStackTop < COMFY_EXPR_STACK_CAPACITY)
+				_exprStack[_exprStackTop++] = scriptReadWord(pc);
+
+			pc += 2;
+			continue;
+		}
+
+		if (opcode == 0x02) {
+			uint16 index = scriptReadWord(pc);
+			pc += 2;
+			uint16 value = index < _stringTable.size() ? _stringTable[index] : 0;
+			if (_exprStackTop < COMFY_EXPR_STACK_CAPACITY)
+				_exprStack[_exprStackTop++] = value;
+
+			continue;
+		}
+
+		if (opcode >= 0x10 && opcode <= 0x14) {
+			Actor *actor = actorResolve(scriptReadWord(pc), fallbackActor);
+			pc += 2;
+			if (!actor) {
+				_scriptFault = true;
+				return 0;
+			}
+
+			uint16 value = 0;
+			if (opcode == 0x10)
+				value = actorReadDword(*actor, kActorXFixed) >> 12;
+			else if (opcode == 0x11)
+				value = actorReadDword(*actor, kActorYFixed) >> 12;
+			else if (opcode == 0x12 || opcode == 0x13) {
+				uint offset = opcode == 0x12 ? kActorXFixed : kActorYFixed;
+				int32 position = actorReadDword(*actor, offset);
+				while (actorReadWord(*actor, kActorParent)) {
+					actor = actorGet(actorReadWord(*actor, kActorParent));
+					if (!actor)
+						break;
+
+					position += actorReadDword(*actor, offset);
+				}
+
+				value = uint16(position >> 12);
+			} else if (opcode == 0x14)
+				value = actorReadWord(*actor, kActorSpriteSelector);
+
+			if (_exprStackTop < COMFY_EXPR_STACK_CAPACITY)
+				_exprStack[_exprStackTop++] = value;
+
+			continue;
+		}
+
+		if (opcode == 0x16) {
+			if (_exprStackTop) {
+				int16 maximum = _exprStack[_exprStackTop - 1];
+				_exprStack[_exprStackTop - 1] = uint16((int32(getRandomNumber(0x7FFF)) * maximum) / 0x8000);
+			}
+
+			continue;
+		}
+
+		if (opcode == 0x0C) {
+			if (_exprStackTop < 2) {
+				_exprStackTop = 0;
+				continue;
+			}
+
+			uint16 index = _exprStack[_exprStackTop - 2] + _exprStack[_exprStackTop - 1];
+			_exprStackTop--;
+			_exprStack[_exprStackTop - 1] = index < _stringTable.size() ? _stringTable[index] : 0;
+			continue;
+		}
+
+		if (opcode != 0x08 && opcode != 0x09 && opcode != 0x0A && opcode != 0x0B && opcode != 0x0E)
+			continue;
+
+		if (_exprStackTop < 2) {
+			_exprStackTop = 0;
+			continue;
+		}
+
+		int16 rhs = _exprStack[--_exprStackTop];
+		int16 lhs = _exprStack[_exprStackTop - 1];
+		if (opcode == 0x08)
+			_exprStack[_exprStackTop - 1] = uint16(lhs + rhs);
+		else if (opcode == 0x09)
+			_exprStack[_exprStackTop - 1] = uint16(lhs - rhs);
+		else if (opcode == 0x0A)
+			_exprStack[_exprStackTop - 1] = uint16(lhs * rhs);
+		else if ((opcode == 0x0B || opcode == 0x0E) && !rhs) {
+			_scriptFault = true;
+			return 0;
+		} else if (opcode == 0x0B)
+			_exprStack[_exprStackTop - 1] = uint16(lhs / rhs);
+		else if (opcode == 0x0E)
+			_exprStack[_exprStackTop - 1] = uint16(lhs % rhs);
+	}
+}
+
 
 } // End of namespace Comfy
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index 2919d59b450..7275a227589 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -261,6 +261,7 @@ bool ComfyEngine::picFileOpen() {
 		header.reserved = entry[0x0E];
 		header.tiledSize = READ_LE_UINT16(entry + 0x0F);
 		_spriteResources[i].header = header;
+		_spriteResources[i].id = i;
 		_spriteResources[i].pixels.clear();
 		_spriteResources[i].loaded = false;
 
@@ -280,6 +281,7 @@ bool ComfyEngine::midiFileOpen() {
 		return false;
 
 	_midiEntryCount = READ_LE_UINT16(&_midiFileData[2]);
+	_midiFileMode = _midiFileData[1] == 'm' ? 1 : 0;
 	return true;
 }
 
@@ -290,6 +292,74 @@ bool ComfyEngine::assetsLoad() {
 		return false;
 	}
 
+	_stringTable.resize(_stringCount + 1);
+	memset(&_stringTable[0], 0, _stringTable.size() * sizeof(uint16));
+	_sceneHandles.resize(_sceneCount + 1);
+	memset(&_sceneHandles[0], 0, _sceneHandles.size() * sizeof(uint16));
+	_midiHandles.resize(_resourceHandleCount + 1);
+	memset(&_midiHandles[0], 0, _midiHandles.size() * sizeof(uint16));
+	_actors.resize(COMFY_ACTOR_COUNT);
+	memset(&_actors[0], 0, _actors.size() * sizeof(Actor));
+	memset(_actorPcTable, 0, sizeof(_actorPcTable));
+	for (uint i = 1; i + 1 < _actors.size(); i++)
+		actorWriteWord(_actors[i], kActorNextLink, i + 1);
+
+	actorWriteWord(_actors[0], kActorNextLink, _actors.size() > 1 ? 1 : 0);
+	for (uint i = 1; i < COMFY_ACTOR_PC_TABLE_COUNT; i++)
+		_actorPcTable[i] = uint32(i + 1) << 24;
+
+	_actorPcTable[COMFY_ACTOR_PC_TABLE_COUNT - 1] = 0;
+	_actorPcTable[0] = 1 << 24;
+	uint32 stringBytes = _stringTable.size() * sizeof(uint16);
+	uint32 handleBytes = _sceneHandles.size() * sizeof(uint16);
+	uint32 actorBytes = _actors.size() * sizeof(Actor);
+	uint32 keyBytes = (_keyBitCount + 1) / 8 + 1;
+	_sceneMidiInstanceOffset = 0;
+	_sceneEntryListOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES;
+	_sceneActorPcOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES + 0x167;
+	_sceneStringTableOffset = _sceneActorPcOffset + COMFY_SCENE_ACTOR_PC_BYTES;
+	_sceneHandlesOffset = _sceneStringTableOffset + stringBytes;
+	_sceneActorsOffset = _sceneHandlesOffset + handleBytes;
+	_sceneKeyBitsOffset = _sceneActorsOffset + actorBytes;
+	uint32 sceneBytes = (_sceneKeyBitsOffset + keyBytes + 1) & ~1U;
+	_sceneMemoryBlock.resize(sceneBytes);
+	memset(&_sceneMemoryBlock[0], 0, _sceneMemoryBlock.size());
+	memcpy(&_sceneMemoryBlock[_sceneActorPcOffset], _actorPcTable, sizeof(_actorPcTable));
+	_sceneFrameData.resize(COMFY_SCENE_FRAME_BYTES);
+	memset(&_sceneFrameData[0], 0, _sceneFrameData.size());
+	memset(_sceneEntryOffsets, 0, sizeof(_sceneEntryOffsets));
+	_numFrames = _picDataSize / COMFY_TILE_SIZE + (_picDataSize % COMFY_TILE_SIZE ? 2 : 1);
+	_numObjects = _spriteHeaders.size();
+	_numSprites = sceneBytes;
+	_envNumSprites = _numSprites;
+	_objectCacheEntries.resize(_spriteHeaders.size());
+	_frameCacheEntries.resize(_numFrames + 1);
+	if (!_objectCacheEntries.empty())
+		memset(&_objectCacheEntries[0], 0xFF, _objectCacheEntries.size() * sizeof(SpriteCacheEntry));
+
+	if (!_frameCacheEntries.empty())
+		memset(&_frameCacheEntries[0], 0xFF, _frameCacheEntries.size() * sizeof(SpriteCacheEntry));
+	memset(&_spriteConversionLoads, 0, sizeof(_spriteConversionLoads));
+	_scenePoolData.resize(0x1FC000);
+	memset(&_scenePoolData[0], 0, _scenePoolData.size());
+	_scenePoolCursor = 0;
+	_scenePoolEvictCursor = 0;
+	uint32 environmentBytes = ((_envNumSprites * 5 + 0x3FF) / 0x400) * 0x400;
+	_environmentData.resize(environmentBytes);
+	if (environmentBytes)
+		memset(&_environmentData[0], 0, environmentBytes);
+
+	_activeSceneCount = _resourceHandleCount;
+	_sceneEntryCount = 0;
+	_sceneEntryFrameSize = 0;
+	Common::ScopedPtr<Common::SeekableReadStream> message(pathFOpen(Common::Path("MESSAGE"), true));
+	_usesWcomfy99ScriptOps = bool(message);
+	_pendingScene = 0;
+	_musicEventMask = 0;
+	_musicEventFlag = 0;
+	_musicEnabled = true;
+	_scriptFault = false;
+
 	return true;
 }
 
@@ -300,12 +370,37 @@ void ComfyEngine::assetsUnload() {
 	_midiFileData.clear();
 	_spriteHeaders.clear();
 	_spriteResources.clear();
+	_stringTable.clear();
+	_sceneHandles.clear();
+	_midiHandles.clear();
+	_actors.clear();
+	_sceneMemoryBlock.clear();
+	_scenePoolData.clear();
+	_environmentData.clear();
+	_sceneFrameData.clear();
+	_objectCacheEntries.clear();
+	_frameCacheEntries.clear();
+	memset(&_spriteConversionLoads, 0, sizeof(_spriteConversionLoads));
+	memset(_sceneEntryOffsets, 0, sizeof(_sceneEntryOffsets));
+	memset(_actorPcTable, 0, sizeof(_actorPcTable));
+	_usesWcomfy99ScriptOps = false;
+	_pendingScene = 0;
+	_currentActor = 0;
+	_scriptFault = false;
 	_stringCount = 0;
 	_sceneCount = 0;
 	_keyBitCount = 0;
 	_resourceHandleCount = 0;
 	_midiEntryCount = 0;
 	_picDataSize = 0;
+	_numFrames = 0;
+	_numObjects = 0;
+	_numSprites = 0;
+	_envNumSprites = 0;
+	_activeSceneCount = 0;
+	_sceneEntryCount = 0;
+	_sceneEntryFrameSize = 0;
+	_midiFileMode = 0;
 	_usesAnimFile = false;
 }
 
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index 7bfe7d34061..273840f0dfc 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -23,6 +23,86 @@
 
 namespace Comfy {
 
+void ComfyEngine::scenePackRuntimeState() {
+	if (_sceneMemoryBlock.empty())
+		return;
+
+	if (!_stringTable.empty())
+		memcpy(&_sceneMemoryBlock[_sceneStringTableOffset], &_stringTable[0], _stringTable.size() * sizeof(uint16));
+
+	if (!_sceneHandles.empty())
+		memcpy(&_sceneMemoryBlock[_sceneHandlesOffset], &_sceneHandles[0], _sceneHandles.size() * sizeof(uint16));
+
+	if (!_actors.empty())
+		memcpy(&_sceneMemoryBlock[_sceneActorsOffset], &_actors[0], _actors.size() * sizeof(Actor));
+
+	if (_keyBits && _keyBitsSize)
+		memcpy(&_sceneMemoryBlock[_sceneKeyBitsOffset], _keyBits, _keyBitsSize);
+}
+
+bool ComfyEngine::environmentStore(uint16 index) {
+	if (!index || _sceneMemoryBlock.empty())
+		return false;
+
+	scenePackRuntimeState();
+	uint32 offset = uint32(index - 1) * _sceneMemoryBlock.size();
+	if (offset > _environmentData.size() || _sceneMemoryBlock.size() > _environmentData.size() - offset)
+		return false;
+
+	memcpy(&_environmentData[offset], &_sceneMemoryBlock[0], _sceneMemoryBlock.size());
+	return true;
+}
+
+bool ComfyEngine::environmentLoad(uint16 index) {
+	if (!index || _sceneMemoryBlock.empty())
+		return false;
+
+	uint32 offset = uint32(index - 1) * _sceneMemoryBlock.size();
+	if (offset > _environmentData.size() || _sceneMemoryBlock.size() > _environmentData.size() - offset)
+		return false;
+
+	memcpy(&_sceneMemoryBlock[0], &_environmentData[offset], _sceneMemoryBlock.size());
+	memcpy(_actorPcTable, &_sceneMemoryBlock[_sceneActorPcOffset], sizeof(_actorPcTable));
+	memcpy(&_stringTable[0], &_sceneMemoryBlock[_sceneStringTableOffset], _stringTable.size() * sizeof(uint16));
+	memcpy(&_sceneHandles[0], &_sceneMemoryBlock[_sceneHandlesOffset], _sceneHandles.size() * sizeof(uint16));
+	memcpy(&_actors[0], &_sceneMemoryBlock[_sceneActorsOffset], _actors.size() * sizeof(Actor));
+	if (_keyBits && _keyBitsSize)
+		memcpy(_keyBits, &_sceneMemoryBlock[_sceneKeyBitsOffset], _keyBitsSize);
+
+	return true;
+}
+
+void ComfyEngine::sceneGoto(uint16 count) {
+	_sceneEntryCount = count;
+	_sceneEntryFrameSize = count ? COMFY_SCENE_FRAME_BYTES / int16(count) : 0;
+	for (uint i = 0; i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
+		_sceneEntryOffsets[i] = 0xFFFF;
+}
+
+void ComfyEngine::sceneStop() {
+	_sceneEntryCount = 0;
+	_sceneEntryFrameSize = 0;
+}
+
+bool ComfyEngine::sceneEntryLoad(uint16 descriptor, uint16 index) {
+	uint32 descriptorOffset = 4 + uint32(descriptor) * 6;
+	if (descriptorOffset > _midiFileData.size() || 6 > _midiFileData.size() - descriptorOffset)
+		return false;
+
+	uint16 size = READ_LE_UINT16(&_midiFileData[descriptorOffset]);
+	uint32 fileOffset = READ_LE_UINT32(&_midiFileData[descriptorOffset + 2]);
+	uint32 destinationOffset = uint32(_sceneEntryFrameSize) * index;
+	if (fileOffset > _midiFileData.size() || size > _midiFileData.size() - fileOffset ||
+			destinationOffset > _sceneFrameData.size() || size > _sceneFrameData.size() - destinationOffset)
+		return false;
+
+	memcpy(&_sceneFrameData[destinationOffset], &_midiFileData[fileOffset], size);
+	if (index < COMFY_SCENE_ENTRY_OFFSET_CAPACITY)
+		_sceneEntryOffsets[index] = descriptor;
+
+	return true;
+}
+
 bool ComfyEngine::sceneOpen() {
 	if (_sceneOpen)
 		sceneClose();
@@ -32,17 +112,13 @@ bool ComfyEngine::sceneOpen() {
 
 	paletteLoadWithFade(0, 0);
 	framebufClear(0);
-	int16 y = 0;
-	for (uint spriteId = 1; spriteId < _spriteHeaders.size() && y < int16(_logicalScreenHeight); spriteId++) {
-		SpriteObjectHeader &header = _spriteHeaders[spriteId];
-		if (header.width != _logicalScreenWidth || !header.height || y + header.height > _logicalScreenHeight)
-			continue;
-
-		spriteBlitClipped(spriteId, 0, y);
-		y += header.height;
+	if (actorInit(1, 0, 1, 1, 0x14, 0, 0, 0, 1) != 1) {
+		midiPlyrStop();
+		return false;
 	}
 
 	_sceneOpen = true;
+	scenePackRuntimeState();
 	renderSetDirty();
 	return true;
 }
@@ -51,6 +127,10 @@ void ComfyEngine::sceneClose() {
 	if (!_sceneOpen)
 		return;
 
+	if (_sceneHandles.size() > 1 && _sceneHandles[1])
+		actorFreeTree(_sceneHandles[1]);
+
+	scenePackRuntimeState();
 	midiPlyrStop();
 	for (uint i = 0; i < _spriteResources.size(); i++) {
 		_spriteResources[i].pixels.clear();
diff --git a/engines/comfy/script.cpp b/engines/comfy/script.cpp
index 409cdeb90bd..6f477d80b29 100644
--- a/engines/comfy/script.cpp
+++ b/engines/comfy/script.cpp
@@ -19,7 +19,84 @@
  *
  */
 
+#include "comfy/comfy.h"
+
+#include "common/endian.h"
+
+#include <cstdarg>
+
 namespace Comfy {
 
+bool ComfyEngine::scriptHasRange(uint32 pc, uint32 width) {
+	uint32 tileOffset = pc % COMFY_TILE_SIZE;
+	uint32 tileBase = pc - tileOffset;
+	uint32 tileSize = tileBase < _picDataSize ? MIN<uint32>(COMFY_TILE_SIZE, _picDataSize - tileBase) : 0;
+	if (tileBase > _comfyObjData.size() || tileSize > _comfyObjData.size() - tileBase ||
+			tileOffset > tileSize || width > tileSize - tileOffset) {
+		_scriptFault = true;
+		return false;
+	}
+
+	return true;
+}
+
+byte ComfyEngine::scriptReadByte(uint32 pc) {
+	return scriptHasRange(pc, 1) ? _comfyObjData[pc] : 0;
+}
+
+uint16 ComfyEngine::scriptReadWord(uint32 pc) {
+	return scriptHasRange(pc, 2) ? READ_LE_UINT16(&_comfyObjData[pc]) : 0;
+}
+
+uint32 ComfyEngine::scriptReadDword(uint32 pc) {
+	return scriptHasRange(pc, 4) ? READ_LE_UINT32(&_comfyObjData[pc]) : 0;
+}
+
+uint16 ComfyEngine::scriptReadStringIndex(uint32 pc) {
+	uint16 value = scriptReadWord(pc);
+	if (value >= 0x7530) {
+		uint32 index = value - 0x7530;
+		if (index < _stringTable.size())
+			value = _stringTable[index];
+	}
+
+	return value;
+}
+
+uint32 ComfyEngine::scriptReadArgs(uint32 pc, uint16 fallbackActor, const char *format, ...) {
+	va_list args;
+	va_start(args, format);
+	for (char type = *format; type; type = *++format) {
+		if (type == 'C') {
+			byte *value = va_arg(args, byte *);
+			if (value)
+				*value = scriptReadByte(pc);
+
+			pc++;
+		} else if (type == 'I' || type == 'N') {
+			uint16 *value = va_arg(args, uint16 *);
+			if (value)
+				*value = type == 'N' ? scriptReadStringIndex(pc) : scriptReadWord(pc);
+
+			pc += 2;
+		} else if (type == 'L') {
+			uint32 *value = va_arg(args, uint32 *);
+			if (value)
+				*value = scriptReadDword(pc);
+
+			pc += 4;
+		} else if (type == 'O') {
+			Actor **value = va_arg(args, Actor **);
+			if (value)
+				*value = actorResolve(scriptReadWord(pc), fallbackActor);
+
+			pc += 2;
+		}
+	}
+
+	va_end(args);
+	return pc;
+}
+
 
 } // End of namespace Comfy
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 409cdeb90bd..4b2dbdaaee2 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -19,7 +19,778 @@
  *
  */
 
+#include "comfy/comfy.h"
+
+#include "common/config-manager.h"
+#include "common/ptr.h"
+
 namespace Comfy {
 
+ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte opcode, uint32 &pc) {
+	if (opcode == 0x01 || opcode == 0x02) {
+		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
+		pc += 2;
+		int16 x = scriptReadStringIndex(pc);
+		pc += 2;
+		int16 y = scriptReadStringIndex(pc);
+		pc += 2;
+		byte randomize = scriptReadByte(pc++);
+		if (!target)
+			return kScriptUnhandled;
+
+		if ((opcode == 0x01 && x == int16(0xF830)) || (opcode == 0x02 && x == int16(0x8AD0))) {
+			Actor *other = actorResolve(uint16(y), _currentActor);
+			if (!other)
+				return kScriptUnhandled;
+
+			x = int16(int32(actorReadDword(*other, kActorXFixed)) >> 12);
+			y = int16(int32(actorReadDword(*other, kActorYFixed)) >> 12);
+		} else if (opcode == 0x01 && x == int16(0xF448)) {
+			x = int16(-int32(actorReadDword(*target, kActorXFixed)) >> 12);
+		}
+
+		if (opcode == 0x01 && y == int16(0xF448))
+			y = int16(-int32(actorReadDword(*target, kActorYFixed)) >> 12);
+
+		if (randomize) {
+			if (x != int16(0xFC18))
+				x = int16((int32(getRandomNumber(0x7FFF)) * x) / 0x8000);
+
+			if (y != int16(0xFC18))
+				y = int16((int32(getRandomNumber(0x7FFF)) * y) / 0x8000);
+		}
+
+		if (opcode == 0x01) {
+			if (x != int16(0xFC18))
+				actorWriteDword(*target, kActorXFixed, uint32(int32(x) * 0x1000));
+
+			if (y != int16(0xFC18))
+				actorWriteDword(*target, kActorYFixed, uint32(int32(y) * 0x1000));
+		} else {
+			actorWriteDword(*target, kActorXFixed, actorReadDword(*target, kActorXFixed) + uint32(int32(x) * 0x1000));
+			actorWriteDword(*target, kActorYFixed, actorReadDword(*target, kActorYFixed) + uint32(int32(y) * 0x1000));
+		}
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x03) {
+		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
+		pc += 2;
+		uint16 frame = scriptReadStringIndex(pc);
+		pc += 2;
+		if (target)
+			actorWriteDword(*target, kActorSpriteSelector, uint32(int32(int16(frame))));
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x04) {
+		uint16 key = scriptReadWord(pc);
+		if (key && !keyBitTest(key)) {
+			pc--;
+			return kScriptYield;
+		}
+
+		pc += 2;
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x05 || opcode == 0x19) {
+		uint16 key = scriptReadWord(pc);
+		byte state = scriptReadByte(pc + 2);
+		uint32 targetPc = scriptReadDword(pc + 3);
+		pc += 7;
+		if (!key || byte(keyBitTest(key)) == state) {
+			if (opcode == 0x19)
+				actorSetPc(actor, pc);
+
+			pc = targetPc;
+		}
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x06) {
+		uint16 key = scriptReadWord(pc);
+		byte state = scriptReadByte(pc + 2);
+		pc += 3;
+		if (state == 1)
+			keyBitSet(key);
+		else
+			keyBitClear(key);
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x07) {
+		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
+		pc += 2;
+		if (!target)
+			return kScriptUnhandled;
+
+		bool current = target == &actor;
+		uint16 actorIndex = uint16(target - &_actors[0]);
+		actorUnlink(actorIndex);
+		actorFreeTree(actorIndex);
+		_actorDestroyedCurrent = current;
+		return current ? kScriptYield : kScriptContinue;
+	}
+
+	if (opcode == 0x08) {
+		uint16 sceneSlot = scriptReadWord(pc);
+		uint16 parentSlot = scriptReadWord(pc + 2);
+		byte flags = scriptReadByte(pc + 4);
+		uint32 newPc = scriptReadDword(pc + 5);
+		pc += 9;
+		int16 x = scriptReadStringIndex(pc);
+		pc += 2;
+		int16 y = scriptReadStringIndex(pc);
+		pc += 2;
+		int16 sprite = scriptReadWord(pc);
+		pc += 2;
+		if (!parentSlot)
+			parentSlot = actorReadWord(actor, kActorSceneHandle);
+
+		actorInit(sceneSlot, parentSlot, flags & 1, flags & 2, newPc, x, y, sprite, flags & 4);
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x09) {
+		Actor *root = actorGet(0);
+		if (root)
+			actorWriteDword(*root, kActorSpriteSelector, uint32(int32(int16(scriptReadWord(pc)))));
+
+		pc += 2;
+		return kScriptContinue;
+	}
+
+	if (opcode >= 0x0A && opcode <= 0x0D) {
+		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
+		pc += 2;
+		if (!target)
+			return kScriptUnhandled;
+
+		if (opcode == 0x0A)
+			actorWriteByte(*target, kActorVisible, 1);
+		else if (opcode == 0x0B)
+			actorWriteByte(*target, kActorVisible, 0);
+		else if (opcode == 0x0C)
+			actorWriteByte(*target, kActorActive, 1);
+		else {
+			actorWriteWord(*target, kActorMoveTicks, 0);
+			actorWriteByte(*target, kActorActive, 0);
+			if (target == &actor)
+				return kScriptYield;
+		}
+
+		return kScriptContinue;
+	}
+
+	if (opcode >= 0x0E && opcode <= 0x11) {
+		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
+		int16 expected = scriptReadWord(pc + 2);
+		uint16 key = scriptReadWord(pc + 4);
+		byte mode = scriptReadByte(pc + 6);
+		pc += 7;
+		if (!target)
+			return kScriptUnhandled;
+
+		int16 actual = int32(actorReadDword(*target, opcode == 0x0E || opcode == 0x10 ? kActorXFixed : kActorYFixed)) >> 12;
+		bool matched = ((mode & 2) && expected == actual) || ((mode & 4) && expected < actual) || ((mode & 1) && expected > actual);
+		if (matched) {
+			if (opcode == 0x0E || opcode == 0x0F)
+				keyBitSet(key);
+			else
+				keyBitClear(key);
+		}
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x12) {
+		pc += 4;
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x13) {
+		byte totalWeight = scriptReadByte(pc++);
+		byte installReturnPc = scriptReadByte(pc++);
+		uint32 returnPc = pc + installReturnPc - 3;
+		byte choice = byte((getRandomNumber(0x7FFF) * totalWeight) / 0x8000);
+		byte accumulated = 0;
+		uint32 targetPc = 0;
+		do {
+			accumulated += scriptReadByte(pc++);
+			targetPc = scriptReadDword(pc);
+			pc += 4;
+		} while (choice >= accumulated && !_scriptFault);
+
+		if (installReturnPc)
+			actorSetPc(actor, returnPc);
+
+		pc = targetPc;
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x14) {
+		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
+		byte mode = scriptReadByte(pc + 2);
+		pc += 3;
+		if (!target)
+			return kScriptUnhandled;
+
+		uint16 targetIndex = uint16(target - &_actors[0]);
+		uint16 oldParent = actorReadWord(*target, kActorParent);
+		actorUnlink(targetIndex);
+		if (mode == 'O')
+			actorInsertChild(targetIndex, oldParent);
+		else
+			actorInsertSibling(targetIndex, oldParent);
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x15 || opcode == 0x16) {
+		byte count = scriptReadByte(pc++);
+		for (uint i = 0; i < count; i++) {
+			uint16 id = scriptReadWord(pc);
+			pc += 2;
+			if (opcode == 0x15) {
+				spriteGet(int16(id));
+				if (_spriteConversionLoads.count < COMFY_RESOURCE_LIST_CAPACITY)
+					_spriteConversionLoads.ids[_spriteConversionLoads.count++] = id;
+			}
+		}
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x17) {
+		if (_musicEventMask) {
+			pc--;
+			return kScriptYield;
+		}
+
+		pc += 2;
+		byte count = scriptReadByte(pc++);
+		pc += uint32(count) * 2;
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x18) {
+		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
+		pc += 2;
+		if (!target)
+			return kScriptUnhandled;
+
+		uint32 resetPc = actorReadDword(*target, kActorResetPc);
+		actorWriteDword(*target, kActorCurrentPc, resetPc);
+		actorWriteByte(*target, kActorActive, 1);
+		actorWriteWord(*target, kActorWaitTarget, 0);
+		actorWriteWord(*target, kActorWaitAccum, 0);
+		if (actorReadWord(*target, kActorMoveTicks)) {
+			actorWriteWord(*target, kActorMoveTicks, 0);
+			uint16 completionKey = actorReadWord(*target, kActorCompletionKey);
+			if (completionKey)
+				keyBitSet(completionKey);
+		}
+
+		actorFreePcChain(*target);
+
+		if (target == &actor)
+			pc = resetPc;
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x1B)
+		return kScriptContinue;
+
+	if (opcode == 0x1C) {
+		pc += 2;
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x1D) {
+		byte subop = scriptReadByte(pc++) & 0x0F;
+		if (subop == 1) {
+			pc += 4;
+			uint16 count = scriptReadWord(pc);
+			pc += 2 + uint32(count) * 2;
+		} else if (subop >= 2 && subop <= 4) {
+			pc += 4;
+		}
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x1E) {
+		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
+		uint16 key = scriptReadWord(pc + 2);
+		byte flags = scriptReadByte(pc + 4);
+		uint32 triggerPc = scriptReadDword(pc + 5);
+		pc += 9;
+		if (!target)
+			return kScriptUnhandled;
+
+		if (key != 0xFC18)
+			actorWriteWord(*target, kActorTriggerKey, key);
+
+		if (triggerPc != 0xFFFFFC18) {
+			actorWriteDword(*target, kActorTriggerPc, triggerPc);
+			actorWriteByte(*target, kActorTriggerFlags, flags);
+		} else {
+			actorWriteByte(*target, kActorTriggerFlags, (actorReadByte(*target, kActorTriggerFlags) & 1) | flags);
+		}
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x1F) {
+		uint16 bit = scriptReadWord(pc);
+		pc += 2;
+		if (int16(bit) >= 0x32) {
+			bit -= 0x32;
+			_musicEventFlag = 1;
+		}
+
+		if (bit < 16)
+			_musicEventMask |= 1 << bit;
+
+		return kScriptYield;
+	}
+
+	if (opcode == 0x20) {
+		uint16 scene = scriptReadWord(pc);
+		pc += 2;
+		if (!_pendingScene || int16(scene) < int16(_pendingScene))
+			_pendingScene = scene;
+
+		renderSetDirty();
+
+		return kScriptYield;
+	}
+
+	if (opcode == 0x21) {
+		uint16 paletteId = scriptReadStringIndex(pc);
+		uint16 fadeTicks = scriptReadStringIndex(pc + 2);
+		byte brightness = scriptReadByte(pc + 4);
+		pc += 5;
+		if (!brightness)
+			paletteLoadWithFade(paletteId, fadeTicks);
+		else
+			paletteApplyBrightness(brightness);
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x22) {
+		_musicEnabled = scriptReadByte(pc) != 0;
+		pc++;
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x23) {
+		uint16 handle = scriptReadWord(pc);
+		int16 delta = scriptReadStringIndex(pc + 2);
+		pc += 4;
+		if (handle < _midiHandles.size())
+			_midiHandles[handle] += delta;
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x24) {
+		midiSetTimeScale(int16(scriptReadStringIndex(pc)));
+		pc += 2;
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x1A) {
+		pc = actorPopPc(actor);
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x25) {
+		uint16 first = scriptReadWord(pc);
+		uint16 last = scriptReadWord(pc + 2);
+		pc += 4;
+		for (uint16 key = first; key <= last; key++) {
+			keyBitClear(key);
+			if (key == 0xFFFF)
+				break;
+		}
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x26 || opcode == 0x2E) {
+		uint16 first = scriptReadWord(pc);
+		uint16 second = scriptReadWord(pc + 2);
+		uint16 key = scriptReadWord(pc + 4);
+		pc += 6;
+		int16 lhs = first < _midiHandles.size() ? _midiHandles[first] : 0;
+		int16 rhs = opcode == 0x26 ? int16(second) : (second < _midiHandles.size() ? int16(_midiHandles[second]) : 0);
+		if (lhs >= rhs)
+			keyBitSet(key);
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x28 || opcode == 0x29) {
+		pc += 2;
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x2A) {
+		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
+		uint32 selector = scriptReadDword(pc + 2);
+		pc += 6;
+		if (target)
+			actorWriteDword(*target, kActorSpriteSelector, (selector + 1) | 0xFF000000);
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x2B) {
+		pc = uint32(int32(pc) + int16(scriptReadWord(pc) * 2));
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x2C) {
+		uint16 destination = scriptReadWord(pc);
+		uint16 source = scriptReadWord(pc + 2);
+		pc += 4;
+		if (keyBitTest(source))
+			keyBitSet(destination);
+		else
+			keyBitClear(destination);
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x2D) {
+		byte subop = scriptReadByte(pc++);
+		if (subop == 1) {
+			sceneGoto(scriptReadWord(pc));
+			pc += 2;
+		} else if (subop == 2) {
+			sceneStop();
+		} else if (subop == 3) {
+			uint16 descriptor = scriptReadWord(pc);
+			uint16 index = scriptReadWord(pc + 2);
+			pc += 4;
+			sceneEntryLoad(descriptor, index);
+		} else if (subop == 4) {
+			pc += 4;
+		} else if (subop == 5) {
+			pc += 2;
+		}
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x2F) {
+		byte command = scriptReadByte(pc);
+		uint16 destination = scriptReadWord(pc + 1);
+		uint16 first = scriptReadWord(pc + 3);
+		uint16 second = scriptReadWord(pc + 5);
+		pc += 7;
+		if (destination < _midiHandles.size() && first < _midiHandles.size()) {
+			if (command == '=')
+				_midiHandles[destination] = _midiHandles[first];
+			else if (command == 'm' && second < _midiHandles.size())
+				_midiHandles[destination] = int16(_midiHandles[second]) <= int16(_midiHandles[first]) ? _midiHandles[first] : _midiHandles[second];
+		}
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x30 && _usesAnimFile) {
+		byte subop = scriptReadByte(pc++);
+		if (subop == 1)
+			pc += 4;
+
+		return kScriptContinue;
+	}
+
+	if (opcode >= 0x31 && opcode <= 0x36 && _usesWcomfy99ScriptOps) {
+		if (opcode == 0x31) {
+			uint16 count = scriptReadStringIndex(pc);
+			pc += 2 + uint32(count) * 2;
+		} else if (opcode == 0x32) {
+			pc += 4;
+		} else if (opcode == 0x33) {
+			pc += 4;
+			byte inlineBytes = scriptReadByte(pc++);
+			byte tripleCount = scriptReadByte(pc++);
+			pc += inlineBytes + uint32(tripleCount) * 3;
+		} else if (opcode == 0x34) {
+			byte subop = scriptReadByte(pc++);
+			uint16 value = scriptReadWord(pc);
+			pc += 2;
+			Common::String key;
+			for (byte character = scriptReadByte(pc++); character; character = scriptReadByte(pc++))
+				key += char(character);
+
+			key.trim();
+
+			if (subop == 0 && value < _stringTable.size()) {
+				_stringTable[value] = ConfMan.hasKey(key) ? ConfMan.getInt(key) : 0;
+			} else if (subop == 1) {
+				ConfMan.setInt(key, value);
+			} else if (subop == 4) {
+				if (ConfMan.hasKey(key) && !ConfMan.get(key).equalsIgnoreCase("?????"))
+					keyBitSet(value);
+				else
+					keyBitClear(value);
+			} else if (subop == 5) {
+				Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(Common::Path(key), true));
+				if (stream)
+					keyBitSet(value);
+				else
+					keyBitClear(value);
+			} else if (subop == 6 && value < _stringTable.size()) {
+				byte last = key.empty() ? 0 : key.lastChar();
+				_stringTable[value] = Common::isSpace(last) ? 0x81 : Common::isDigit(last) ? 0x12 :
+					(Common::isAlpha(last) ? (Common::isUpper(last) ? 0x04 : 0x08) : 0x40);
+			}
+		} else if (opcode == 0x35) {
+			pc++;
+		} else {
+			byte subop = scriptReadByte(pc++);
+			if (subop >= 3 && subop <= 5)
+				pc += uint32(subop - 1) * 2;
+		}
+
+		return kScriptContinue;
+	}
+
+	if ((opcode == 0x46 || opcode == 0x47) && _usesWcomfy99ScriptOps) {
+		if (opcode == 0x46) {
+			byte subop = scriptReadByte(pc++);
+			if (subop >= 1 && subop <= 8)
+				pc += 2;
+		} else {
+			pc += 4;
+		}
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x50) {
+		uint16 lhsIndex = scriptReadWord(pc);
+		uint16 rhsIndex = scriptReadWord(pc + 2);
+		uint16 key = scriptReadWord(pc + 4);
+		byte mode = scriptReadByte(pc + 6);
+		pc += 7;
+		int16 lhs = lhsIndex < _stringTable.size() ? _stringTable[lhsIndex] : 0;
+		int16 rhs = rhsIndex < _stringTable.size() ? _stringTable[rhsIndex] : 0;
+		bool matched = ((mode & 4) && lhs > rhs) || ((mode & 2) && lhs == rhs) || ((mode & 1) && lhs < rhs);
+		if (matched)
+			keyBitSet(key);
+		else
+			keyBitClear(key);
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x51 || opcode == 0x52 || opcode == 0x70 || opcode == 0x71) {
+		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
+		pc += 2;
+		int16 x = scriptReadStringIndex(pc);
+		pc += 2;
+		int16 y = scriptReadStringIndex(pc);
+		pc += 2;
+		byte randomize = scriptReadByte(pc++);
+		int16 duration = scriptReadStringIndex(pc);
+		pc += 2;
+		byte blocking = scriptReadByte(pc++);
+		uint16 completionKey = scriptReadWord(pc);
+		pc += 2;
+		if (!target || !duration)
+			return kScriptUnhandled;
+
+		bool moveTo = opcode == 0x52 || opcode == 0x71;
+		if ((moveTo && x == int16(0xF830)) || (!moveTo && x == int16(0x8AD0))) {
+			Actor *other = actorResolve(uint16(y), _currentActor);
+			if (!other)
+				return kScriptUnhandled;
+
+			if (moveTo) {
+				x = int16(int32(actorReadDword(*other, kActorXFixed)) >> 12);
+				y = int16(int32(actorReadDword(*other, kActorYFixed)) >> 12);
+			} else {
+				x = int16(actorReadWord(*other, kActorXFixed)) >> 12;
+				y = int16(actorReadWord(*other, kActorYFixed)) >> 12;
+			}
+		}
+
+		if (randomize) {
+			if (!moveTo || x != int16(0xFC18))
+				x = int16((int32(getRandomNumber(0x7FFF)) * x) / 0x8000);
+
+			if (!moveTo || y != int16(0xFC18))
+				y = int16((int32(getRandomNumber(0x7FFF)) * y) / 0x8000);
+		}
+
+		int32 dx = int32(x) * 0x1000;
+		int32 dy = int32(y) * 0x1000;
+		if (moveTo) {
+			dx = x == int16(0xFC18) ? 0 : dx - int32(actorReadDword(*target, kActorXFixed));
+			dy = y == int16(0xFC18) ? 0 : dy - int32(actorReadDword(*target, kActorYFixed));
+		}
+
+		if (opcode == 0x51 || opcode == 0x52 || (moveTo && duration < 0)) {
+			if (duration < 0)
+				duration = -duration;
+
+			int16 distanceX = ABS(int16(dx >> 12));
+			int16 distanceY = ABS(int16(dy >> 12));
+			int16 distance = MAX(distanceX, distanceY);
+			duration = int16((int32(distance) * 100) / duration);
+			if (!duration)
+				duration = 1;
+		}
+
+		actorWriteDword(*target, kActorMoveDx, dx);
+		actorWriteDword(*target, kActorMoveDy, dy);
+		actorWriteWord(*target, kActorMoveTicks, duration);
+		actorWriteByte(*target, kActorBlockingMove, blocking);
+		actorWriteWord(*target, kActorCompletionKey, completionKey);
+		return blocking && target == &actor ? kScriptYield : kScriptContinue;
+	}
+
+	if ((opcode == 0x48 || opcode == 0x49) && _usesWcomfy99ScriptOps) {
+		uint16 key = scriptReadWord(pc);
+		uint32 targetPc = scriptReadDword(pc + 2);
+		bool jumpWhenSet = opcode == 0x49;
+		pc = keyBitTest(key) == jumpWhenSet ? targetPc : pc + 6;
+		return kScriptContinue;
+	}
+
+	if ((opcode == 0x54 || opcode == 0x55) && _usesWcomfy99ScriptOps) {
+		pc += 4;
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x6E)
+		return kScriptYield;
+
+	if (opcode == 0x6F) {
+		pc += 4;
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x72) {
+		uint16 requested = scriptReadStringIndex(pc);
+		pc += 2;
+		uint16 balance = actorReadWord(actor, kActorWaitAccum);
+		if (!requested)
+			balance = 0;
+
+		if (balance) {
+			uint16 step = balance < 5 ? balance : 5;
+			balance = step < uint16(requested - 1) ? step : uint16(requested - 1);
+			actorWriteWord(actor, kActorWaitAccum, actorReadWord(actor, kActorWaitAccum) - balance);
+		}
+
+		actorWriteWord(actor, kActorWaitTarget, requested - balance);
+		return kScriptYield;
+	}
+
+	if (opcode == 0x73)
+		return kScriptContinue;
+
+	if (opcode == 0x74) {
+		uint16 key = scriptReadWord(pc);
+		if (keyBitTest(key)) {
+			pc--;
+			return kScriptYield;
+		}
+
+		pc += 2;
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x75) {
+		byte kind = scriptReadByte(pc++);
+		uint16 key = scriptReadWord(pc);
+		pc += 2;
+		bool condition = false;
+		if (_usesWcomfy99ScriptOps) {
+			uint16 argument = scriptReadWord(pc);
+			pc += 2;
+			if (kind == 1)
+				condition = argument < _sceneHandles.size() && _sceneHandles[argument];
+			else if (kind == 2)
+				condition = _inputDeviceMode == 1;
+			else if (kind == 14 && argument <= 4)
+				condition = _inputDeviceMode == argument;
+		} else if (kind == 1) {
+			uint16 scene = scriptReadWord(pc);
+			condition = scene < _sceneHandles.size() && _sceneHandles[scene];
+			pc += 2;
+		}
+
+		if (condition)
+			keyBitSet(key);
+		else
+			keyBitClear(key);
+
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x76 || opcode == 0x77) {
+		uint16 index = scriptReadWord(pc);
+		pc += 2;
+		if (opcode == 0x77) {
+			if (_stringTable.size() <= 1) {
+				_scriptFault = true;
+				return kScriptUnhandled;
+			}
+
+			index += _stringTable[1];
+		}
+
+		uint16 value = scriptEvalExpr(pc, _currentActor);
+		if (index >= _stringTable.size()) {
+			_scriptFault = true;
+			return kScriptUnhandled;
+		}
+
+		_stringTable[index] = value;
+		return kScriptContinue;
+	}
+
+	if (opcode == 0x7F)
+		return kScriptContinue;
+
+	if (!opcode || opcode > 0x7F || opcode == 0x27 || (opcode >= 0x30 && opcode <= 0x4F) ||
+	    (opcode >= 0x53 && opcode <= 0x6D) || (opcode >= 0x78 && opcode <= 0x7E)) {
+		Actor *root = actorGet(0);
+		if (root)
+			actorWriteByte(*root, kActorActive, 0);
+
+		return kScriptDeactivatedRoot;
+	}
+
+	_scriptFault = true;
+	return kScriptUnhandled;
+}
+
+ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptStep(Actor &actor, uint32 &pc) {
+	uint32 originalPc = pc;
+	byte opcode = scriptReadByte(pc++);
+	ScriptDispatchStatus status = scriptDispatch(actor, opcode, pc);
+	if (status == kScriptUnhandled)
+		pc = originalPc;
+	else if (status == kScriptYield)
+		actorWriteDword(actor, kActorCurrentPc, pc);
+
+	return status;
+}
+
 
 } // End of namespace Comfy


Commit: b2ee0458b0fc1e26bbe55cefe62eb06db1a6b4f7
    https://github.com/scummvm/scummvm/commit/b2ee0458b0fc1e26bbe55cefe62eb06db1a6b4f7
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Render first scene

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/game.cpp
    engines/comfy/script_vm.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index 329bed0ddaf..f5d529dd8fa 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -589,6 +589,11 @@ void ComfyEngine::actorClearDirtyTree(uint16 actorIndex) {
 	}
 }
 
+void ComfyEngine::actorSetAllDirty() {
+	for (uint i = 0; i + 1 < _actors.size(); i++)
+		actorWriteByte(_actors[i], kActorDirty, 1);
+}
+
 bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
 	Actor *actor = actorGet(actorIndex);
 	descendChildren = false;
@@ -739,5 +744,144 @@ bool ComfyEngine::actorTickTreeInternal(uint16 actorIndex) {
 	return false;
 }
 
+void ComfyEngine::actorDrawList(uint16 actorIndex, int16 x, int16 y) {
+	while (actorIndex) {
+		actorDraw(actorIndex, x, y);
+		Actor *actor = actorGet(actorIndex);
+		actorIndex = actor ? actorReadWord(*actor, kActorNextLink) : 0;
+	}
+}
+
+void ComfyEngine::actorDrawScripted(uint16 actorIndex, uint32 selector, int16 x, int16 y) {
+	uint32 pc = selector & 0x00FFFFFF;
+	int16 wordsLeft = int16(scriptReadWord(pc) - 1);
+	pc += 2;
+	while (wordsLeft > 0 && !_scriptFault) {
+		uint16 spriteId = scriptReadWord(pc);
+		int16 dx = scriptReadWord(pc + 2);
+		int16 dy = scriptReadWord(pc + 4);
+		pc += 6;
+		wordsLeft -= 3;
+		if (spriteId & 0x8000) {
+			wordsLeft -= 2;
+			uint16 key = scriptReadWord(pc);
+			pc += 2;
+			if (keyBitTest(key))
+				spriteId &= 0x7FFF;
+			else
+				spriteId = scriptReadWord(pc);
+
+			pc += 2;
+		}
+
+		if (spriteId) {
+			SpriteResource *sprite = spriteGet(int16(spriteId));
+			if (sprite)
+				spriteBlitClipped(int16(spriteId), x + dx - sprite->header.hotspotX, y + dy - sprite->header.hotspotY);
+		}
+	}
+
+	(void)actorIndex;
+}
+
+ComfyEngine::VideoRectRecord ComfyEngine::actorReadCachedRect(Actor &actor) {
+	VideoRectRecord rect;
+	rect.left = actorReadWord(actor, kActorCachedRect);
+	rect.top = actorReadWord(actor, kActorCachedRect + 2);
+	rect.right = actorReadWord(actor, kActorCachedRect + 4);
+	rect.bottom = actorReadWord(actor, kActorCachedRect + 6);
+	rect.area = actorReadWord(actor, kActorCachedRect + 8);
+	return rect;
+}
+
+void ComfyEngine::actorWriteCachedRect(Actor &actor, VideoRectRecord rect) {
+	actorWriteWord(actor, kActorCachedRect, rect.left);
+	actorWriteWord(actor, kActorCachedRect + 2, rect.top);
+	actorWriteWord(actor, kActorCachedRect + 4, rect.right);
+	actorWriteWord(actor, kActorCachedRect + 6, rect.bottom);
+	actorWriteWord(actor, kActorCachedRect + 8, rect.area);
+}
+
+void ComfyEngine::actorInvalidateDrawTree(uint16 actorIndex) {
+	Actor *actor = actorGet(actorIndex);
+	if (!actor)
+		return;
+
+	VideoRectRecord rect = actorReadCachedRect(*actor);
+	if (rect.area)
+		videoFindBestMode(rect);
+
+	actorWriteByte(*actor, kActorCachedVisible, 0);
+	actorWriteDword(*actor, kActorCachedSprite, 0);
+	VideoRectRecord empty = {0, 0, 0, 0, 0};
+	actorWriteCachedRect(*actor, empty);
+	uint16 child = actorReadWord(*actor, kActorSiblingHead);
+	while (child) {
+		Actor *childActor = actorGet(child);
+		uint16 next = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+		actorInvalidateDrawTree(child);
+		child = next;
+	}
+
+	child = actorReadWord(*actor, kActorChildHead);
+	while (child) {
+		Actor *childActor = actorGet(child);
+		uint16 next = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+		actorInvalidateDrawTree(child);
+		child = next;
+	}
+}
+
+bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
+	Actor *actor = actorGet(actorIndex);
+	if (!actor)
+		return true;
+
+	int16 drawX = int16(int32(actorReadDword(*actor, kActorXFixed)) >> 12) + x;
+	int16 drawY = int16(int32(actorReadDword(*actor, kActorYFixed)) >> 12) + y;
+	byte oldVisible = actorReadByte(*actor, kActorCachedVisible);
+	uint32 oldSelector = actorReadDword(*actor, kActorCachedSprite);
+	VideoRectRecord oldRect = actorReadCachedRect(*actor);
+	if (!actorReadByte(*actor, kActorVisible)) {
+		if (oldVisible)
+			actorInvalidateDrawTree(actorIndex);
+
+		return true;
+	}
+
+	actorDrawList(actorReadWord(*actor, kActorSiblingHead), drawX, drawY);
+	uint32 selector = actorReadDword(*actor, kActorSpriteSelector);
+	VideoRectRecord newRect = {0, 0, 0, 0, 0};
+	if (selector & 0xFF000000) {
+		actorDrawScripted(actorIndex, selector, drawX, drawY);
+	} else if (selector) {
+		SpriteResource *sprite = spriteGet(int16(selector));
+		if (sprite) {
+			newRect.left = drawX - sprite->header.hotspotX;
+			newRect.top = drawY - sprite->header.hotspotY;
+			newRect.right = newRect.left + sprite->header.width;
+			newRect.bottom = newRect.top + sprite->header.height;
+			newRect.area = sprite->header.width * sprite->header.height;
+			spriteBlitClipped(int16(selector), drawX - sprite->header.hotspotX, drawY - sprite->header.hotspotY);
+		}
+	}
+
+	bool rectChanged = oldRect.left != newRect.left || oldRect.top != newRect.top ||
+		oldRect.right != newRect.right || oldRect.bottom != newRect.bottom || oldRect.area != newRect.area;
+	if (oldSelector != selector || oldVisible != actorReadByte(*actor, kActorVisible) || rectChanged) {
+		if (oldRect.area)
+			videoFindBestMode(oldRect);
+
+		if (newRect.area)
+			videoFindBestMode(newRect);
+	}
+
+	actorWriteByte(*actor, kActorCachedVisible, actorReadByte(*actor, kActorVisible));
+	actorWriteDword(*actor, kActorCachedSprite, selector);
+	actorWriteCachedRect(*actor, newRect);
+	actorDrawList(actorReadWord(*actor, kActorChildHead), drawX, drawY);
+	return true;
+}
+
 
 } // End of namespace Comfy
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 9312719989c..461a21923b8 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -73,7 +73,9 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Eng
 	_scenePoolEvictCursor(0), _activeSceneCount(0), _sceneEntryCount(0), _sceneEntryFrameSize(0),
 	_numObjects(0), _numFrames(0), _numSprites(0), _envNumSprites(0), _midiFileMode(0), _mirrorMode(false),
 	_currentActor(0), _pendingScene(0), _musicEventMask(0), _musicEventFlag(0), _musicEnabled(true),
-	_usesWcomfy99ScriptOps(false), _actorDestroyedCurrent(false),
+	_usesWcomfy99ScriptOps(false), _actorDestroyedCurrent(false), _lastKey(0xFFFF),
+	_soundEventIndex(0), _soundEventMaximum(0), _soundEventSubIndex(0xFFFF),
+	_soundEventPreviousSubIndex(0xFFFF),
 	_exprStackTop(0), _scriptFault(false),
 	_gameInitialized(false), _videoInitialized(false),
 	_timerInitialized(false), _lptKeyboardInitialized(false), _mainLoopRunning(false) {
@@ -83,6 +85,7 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Eng
 	memset(_logicalPalette, 0, sizeof(_logicalPalette));
 	memset(&_inputQueue, 0, sizeof(_inputQueue));
 	memset(_keyboardKeyToBit, 0xFF, sizeof(_keyboardKeyToBit));
+	memset(_vocQueue, 0, sizeof(_vocQueue));
 	g_engine = this;
 }
 
@@ -105,7 +108,28 @@ Common::Error ComfyEngine::run() {
 	if (saveSlot != -1)
 		(void)loadGameState(saveSlot);
 
-	gameMainLoop();
+	uint16 currentScene = _language;
+	uint16 chooserScene = currentScene;
+	if (iniGetGameDataPath(0))
+		sceneRun(currentScene, false, true);
+
+	while (currentScene && !shouldQuit()) {
+		if (!iniGetGameDataPath(currentScene)) {
+			gameShutdown();
+			return Common::kNoGameDataFoundError;
+		}
+
+		if (currentScene == 0x63)
+			currentScene = sceneRun(chooserScene, _multiLanguage, false);
+		else {
+			chooserScene = currentScene;
+			currentScene = sceneRun(currentScene, _multiLanguage, false);
+		}
+
+		if (currentScene && currentScene != 0x63)
+			iniWriteLanguage(currentScene);
+	}
+
 	gameShutdown();
 	return Common::kNoError;
 }
@@ -118,15 +142,8 @@ Common::Error ComfyEngine::gameInit() {
 	if (!iniReadGameConfig())
 		return Common::kNoGameDataFoundError;
 
-	if (!iniGetGameDataPath(0))
-		return Common::kNoGameDataFoundError;
-
 	videoInit();
-	if (!assetsLoad() || !sceneOpen())
-		return Common::kNoGameDataFoundError;
-
 	timerInit();
-	lptKeyboardInit();
 	_gameInitialized = true;
 	return Common::kNoError;
 }
@@ -175,6 +192,37 @@ void ComfyEngine::gameMainLoop() {
 	_mainLoopRunning = false;
 }
 
+uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
+	if (!assetsLoad() || !sceneOpen()) {
+		assetsUnload();
+		return 0;
+	}
+
+	keyBitSet(2);
+	lptKeyboardInit();
+	paletteVsyncFlip();
+	paletteVsyncFlip();
+	if (_activeSceneCount && _midiHandles.size() > 1)
+		_midiHandles[1] += sceneId;
+
+	gameMainLoop();
+	uint16 nextScene = 0;
+	if (checkNext && _activeSceneCount > 1 && _midiHandles.size() > 1)
+		nextScene = _midiHandles[1];
+
+	if (nextScene == sceneId || int16(nextScene) <= 0 || int16(nextScene) >= 0x65)
+		nextScene = 0;
+
+	lptKeyboardShutdown();
+	sceneClose();
+	assetsUnload();
+	inputQueueReset();
+	if (!exitFlag && nextScene)
+		renderSetDirty();
+
+	return nextScene;
+}
+
 void ComfyEngine::processEvents() {
 	Common::Event event;
 
@@ -210,13 +258,15 @@ void ComfyEngine::processEvents() {
 			hostKeyboardSetKeyState(hostKeyboardVirtualKey(event.kbd.keycode), false);
 			break;
 		default:
-			debug("EVent %d", event.type);
 			break;
 		}
 	}
 }
 
 void ComfyEngine::gameMainLoopTick() {
+	_pendingScene = 0;
+	_musicEventMask = 0;
+	_musicEventFlag = 0;
 	uint16 ticks = timerTick();
 
 	midiTrackTickAndRemove();
@@ -226,7 +276,6 @@ void ComfyEngine::gameMainLoopTick() {
 	paletteFadeStep(ticks);
 	lptKeyboardScanAndProcess();
 	actorTickTree();
-	paletteVsyncFlip();
 	renderFrame();
 	processInput();
 	processMusicEvents();
@@ -240,6 +289,41 @@ void ComfyEngine::animFileTickCommands() {
 }
 
 void ComfyEngine::sceneTickEvent() {
+	if (_soundEventIndex == _soundEventMaximum)
+		return;
+
+	VocQueueEntry &entry = _vocQueue[_soundEventIndex % COMFY_VOC_QUEUE_CAPACITY];
+	if (entry.state == 0xFFFF) {
+		entry.state = 0;
+		keyBitSet(1);
+		keyBitSet(4);
+		keyBitClear(2);
+		keyBitClear(3);
+		_soundEventSubIndex = 0xFFFF;
+	} else if (_soundEventSubIndex != 0xFFFF && _soundEventSubIndex != _soundEventPreviousSubIndex) {
+		if (!_soundEventSubIndex) {
+			if (entry.argumentCount)
+				keyBitSet(entry.arguments[0]);
+
+			_soundEventIndex = (_soundEventIndex + 1) % COMFY_VOC_QUEUE_CAPACITY;
+			if (_soundEventIndex == _soundEventMaximum) {
+				keyBitClear(1);
+				keyBitClear(4);
+				keyBitSet(2);
+				keyBitSet(3);
+			}
+		} else if (_soundEventSubIndex == 1) {
+			keyBitSet(3);
+			keyBitClear(4);
+		} else if (_soundEventSubIndex == 2) {
+			keyBitSet(4);
+			keyBitClear(3);
+		} else if (_soundEventSubIndex < entry.argumentCount) {
+			keyBitSet(entry.arguments[_soundEventSubIndex]);
+		}
+	}
+
+	_soundEventPreviousSubIndex = _soundEventSubIndex;
 }
 
 void ComfyEngine::midiPollChannels(uint16 ticks) {
@@ -267,16 +351,94 @@ void ComfyEngine::renderFrame() {
 		}
 	}
 
-	videoPresentFrame();
+	uint16 rootIndex = _sceneHandles.size() > 1 ? _sceneHandles[1] : 0;
+	if (!rootIndex || actorDraw(rootIndex, 0, 0)) {
+		paletteVsyncFlip();
+		videoPresentFrame();
+	} else {
+		renderSetDirty();
+	}
 }
 
 void ComfyEngine::processInput() {
+	_lastKey = 0xFFFF;
+	if (inputQueueHasItems())
+		_lastKey = lptReadKeyOrNext();
+
+	lptKeyToFlags(_lastKey);
+	if (_lastKey == 0x0101) {
+		_mainLoopRunning = false;
+		return;
+	}
+
+	uint16 rootIndex = _sceneHandles.size() > 1 ? _sceneHandles[1] : 0;
+	Actor *root = actorGet(rootIndex);
+	if (root && !actorReadByte(*root, kActorActive))
+		_mainLoopRunning = false;
 }
 
 void ComfyEngine::processMusicEvents() {
+	if (!_musicEventMask)
+		return;
+
+	if (_musicEventFlag)
+		vocQueuePlayAll();
+
+	if (vocQueueIsIdle() || _musicEnabled) {
+		uint16 track = 1;
+		while ((_musicEventMask = uint16(int16(_musicEventMask) >> 1)) != 0)
+			track++;
+
+		(void)track;
+	}
 }
 
 void ComfyEngine::processSceneTransition() {
+	keyBitClear(0x42);
+	if (!_pendingScene) {
+		actorSetAllDirty();
+		return;
+	}
+
+	byte keySnapshot[15];
+	memset(keySnapshot, 0, sizeof(keySnapshot));
+	if (_keyBits)
+		memcpy(keySnapshot, _keyBits, MIN<uint32>(sizeof(keySnapshot), _keyBitsSize));
+
+	if (environmentLoad(_pendingScene)) {
+		Actor *root = actorGet(0);
+		if (root) {
+			paletteLoadWithFade(actorReadWord(*root, kActorXFixed), 0);
+			if (actorReadDword(*root, kActorYFixed))
+				paletteApplyBrightness(actorReadWord(*root, kActorYFixed));
+		}
+	}
+
+	if (_keyBits)
+		memcpy(_keyBits, keySnapshot, MIN<uint32>(sizeof(keySnapshot), _keyBitsSize));
+
+	keyBitSet(0x42);
+}
+
+void ComfyEngine::vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc) {
+	VocQueueEntry &entry = _vocQueue[_soundEventMaximum % COMFY_VOC_QUEUE_CAPACITY];
+	entry.soundId = soundId;
+	entry.argumentCount = MIN<uint16>(argumentCount, COMFY_VOC_ARG_CAPACITY);
+	entry.state = 0xFFFF;
+	memset(entry.arguments, 0, sizeof(entry.arguments));
+	for (uint i = 0; i < entry.argumentCount; i++)
+		entry.arguments[i] = scriptReadWord(pc + i * 2);
+
+	_soundEventMaximum = (_soundEventMaximum + 1) % COMFY_VOC_QUEUE_CAPACITY;
+}
+
+void ComfyEngine::vocQueuePlayAll() {
+	if (_soundEventIndex != _soundEventMaximum)
+		_soundEventSubIndex = 0xFFFF;
+}
+
+bool ComfyEngine::vocQueueIsIdle() {
+	return _soundEventIndex == _soundEventMaximum;
 }
 
 Common::Error ComfyEngine::syncGame(Common::Serializer &s) {
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 14bebc0ecf4..3dfa71ea0cf 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -59,6 +59,8 @@
 #define COMFY_SCENE_MIDI_INSTANCE_BYTES 0x18C
 #define COMFY_SCENE_ACTOR_PC_BYTES 0x320
 #define COMFY_SCENE_FRAME_BYTES 0x4E20
+#define COMFY_VOC_ARG_CAPACITY 10
+#define COMFY_VOC_QUEUE_CAPACITY 16
 
 namespace Comfy {
 
@@ -121,6 +123,13 @@ private:
 		uint16 count;
 	};
 
+	struct VocQueueEntry {
+		uint16 soundId;
+		uint16 argumentCount;
+		uint16 state;
+		uint16 arguments[COMFY_VOC_ARG_CAPACITY];
+	};
+
 	struct Actor {
 		byte raw[COMFY_ACTOR_SIZE];
 	};
@@ -273,6 +282,12 @@ private:
 	bool _musicEnabled;
 	bool _usesWcomfy99ScriptOps;
 	bool _actorDestroyedCurrent;
+	uint16 _lastKey;
+	VocQueueEntry _vocQueue[COMFY_VOC_QUEUE_CAPACITY];
+	uint16 _soundEventIndex;
+	uint16 _soundEventMaximum;
+	uint16 _soundEventSubIndex;
+	uint16 _soundEventPreviousSubIndex;
 	uint16 _exprStack[COMFY_EXPR_STACK_CAPACITY];
 	uint16 _exprStackTop;
 	bool _scriptFault;
@@ -384,15 +399,23 @@ private:
 	void actorFreePcChain(Actor &actor);
 	void actorFreeTree(uint16 actorIndex);
 	void actorClearDirtyTree(uint16 actorIndex);
+	void actorSetAllDirty();
 	uint16 actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible, byte active,
 		uint32 pc, int16 x, int16 y, int16 sprite, byte insertAsChild);
 	bool actorRunScript(uint16 actorIndex, bool &descendChildren);
 	bool actorTickTreeInternal(uint16 actorIndex);
+	bool actorDraw(uint16 actorIndex, int16 x, int16 y);
+	void actorDrawList(uint16 actorIndex, int16 x, int16 y);
+	void actorDrawScripted(uint16 actorIndex, uint32 selector, int16 x, int16 y);
+	VideoRectRecord actorReadCachedRect(Actor &actor);
+	void actorWriteCachedRect(Actor &actor, VideoRectRecord rect);
+	void actorInvalidateDrawTree(uint16 actorIndex);
 	void timerInit();
 	void timerShutdown();
 	void lptKeyboardInit();
 	void lptKeyboardShutdown();
 	void gameMainLoop();
+	uint16 sceneRun(uint16 sceneId, bool checkNext, bool exitFlag);
 	void gameMainLoopTick();
 	void processEvents();
 
@@ -408,6 +431,9 @@ private:
 	void processInput();
 	void processMusicEvents();
 	void processSceneTransition();
+	void vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc);
+	void vocQueuePlayAll();
+	bool vocQueueIsIdle();
 
 protected:
 	// Engine APIs
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index 7275a227589..422ce3114c4 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -358,6 +358,11 @@ bool ComfyEngine::assetsLoad() {
 	_musicEventMask = 0;
 	_musicEventFlag = 0;
 	_musicEnabled = true;
+	memset(_vocQueue, 0, sizeof(_vocQueue));
+	_soundEventIndex = 0;
+	_soundEventMaximum = 0;
+	_soundEventSubIndex = 0xFFFF;
+	_soundEventPreviousSubIndex = 0xFFFF;
 	_scriptFault = false;
 
 	return true;
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 4b2dbdaaee2..5fbeb28fb2a 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -272,8 +272,10 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			return kScriptYield;
 		}
 
+		uint16 soundId = scriptReadWord(pc);
 		pc += 2;
 		byte count = scriptReadByte(pc++);
+		vocQueuePush(soundId, count, pc);
 		pc += uint32(count) * 2;
 		return kScriptContinue;
 	}
@@ -304,8 +306,10 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x1B)
+	if (opcode == 0x1B) {
+		vocQueuePlayAll();
 		return kScriptContinue;
+	}
 
 	if (opcode == 0x1C) {
 		pc += 2;


Commit: 093acf12309363916c0c7e5ae08d427ca36c6cd5
    https://github.com/scummvm/scummvm/commit/093acf12309363916c0c7e5ae08d427ca36c6cd5
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Implement lang choice

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/game.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 461a21923b8..d7f855db27b 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -110,6 +110,23 @@ Common::Error ComfyEngine::run() {
 
 	uint16 currentScene = _language;
 	uint16 chooserScene = currentScene;
+	if (_multiLanguage && !ConfMan.getBool("comfy_language_chosen")) {
+		if (!iniGetGameDataPath(0x63)) {
+			gameShutdown();
+			return Common::kNoGameDataFoundError;
+		}
+
+		uint16 selectedLanguage = sceneRun(currentScene, true, false);
+		if (selectedLanguage) {
+			currentScene = selectedLanguage;
+			chooserScene = selectedLanguage;
+			iniWriteLanguage(selectedLanguage);
+		}
+
+		ConfMan.setBool("comfy_language_chosen", true);
+		ConfMan.flushToDisk();
+	}
+
 	if (iniGetGameDataPath(0))
 		sceneRun(currentScene, false, true);
 
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index 422ce3114c4..cc47b408b30 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -102,6 +102,7 @@ void ComfyEngine::gameConfigInit() {
 
 	findLanguageDirectories();
 	ConfMan.registerDefault("comfy_language", 2);
+	ConfMan.registerDefault("comfy_language_chosen", false);
 	ConfMan.registerDefault("comfy_screen_update_interleaved", false);
 	ConfMan.registerDefault("comfy_input_device", 0);
 }


Commit: 881ed723952f54bd11fac8bf0d9aa3f022759caa
    https://github.com/scummvm/scummvm/commit/881ed723952f54bd11fac8bf0d9aa3f022759caa
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Implement sound

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/game.cpp
    engines/comfy/midi.cpp
    engines/comfy/scene.cpp
    engines/comfy/script_vm.cpp
    engines/comfy/sound.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index d7f855db27b..77cf746545b 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -72,10 +72,11 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Eng
 	_sceneHandlesOffset(0), _sceneActorsOffset(0), _sceneKeyBitsOffset(0), _scenePoolCursor(0),
 	_scenePoolEvictCursor(0), _activeSceneCount(0), _sceneEntryCount(0), _sceneEntryFrameSize(0),
 	_numObjects(0), _numFrames(0), _numSprites(0), _envNumSprites(0), _midiFileMode(0), _mirrorMode(false),
-	_currentActor(0), _pendingScene(0), _musicEventMask(0), _musicEventFlag(0), _musicEnabled(true),
+	_currentActor(0), _pendingScene(0), _musicEventMask(0), _musicEventFlag(0), _musicEnabled(false),
 	_usesWcomfy99ScriptOps(false), _actorDestroyedCurrent(false), _lastKey(0xFFFF),
 	_soundEventIndex(0), _soundEventMaximum(0), _soundEventSubIndex(0xFFFF),
-	_soundEventPreviousSubIndex(0xFFFF),
+	_soundEventPreviousSubIndex(0xFFFF), _midiInstanceTrackBase(1),
+	_soundTileStride(0), _soundSampleRate(0x2B11), _soundNextCue(0), _soundCompressed(false), _soundPaused(false),
 	_exprStackTop(0), _scriptFault(false),
 	_gameInitialized(false), _videoInitialized(false),
 	_timerInitialized(false), _lptKeyboardInitialized(false), _mainLoopRunning(false) {
@@ -86,6 +87,9 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Eng
 	memset(&_inputQueue, 0, sizeof(_inputQueue));
 	memset(_keyboardKeyToBit, 0xFF, sizeof(_keyboardKeyToBit));
 	memset(_vocQueue, 0, sizeof(_vocQueue));
+	memset(&_midiEvents, 0, sizeof(_midiEvents));
+	memset(&_midiTracks, 0, sizeof(_midiTracks));
+	memset(_midiChannels, 0, sizeof(_midiChannels));
 	g_engine = this;
 }
 
@@ -289,7 +293,8 @@ void ComfyEngine::gameMainLoopTick() {
 	midiTrackTickAndRemove();
 	animFileTickCommands();
 	sceneTickEvent();
-	midiPollChannels(ticks);
+	if (!_musicEnabled)
+		midiPollChannels(ticks);
 	paletteFadeStep(ticks);
 	lptKeyboardScanAndProcess();
 	actorTickTree();
@@ -300,23 +305,33 @@ void ComfyEngine::gameMainLoopTick() {
 }
 
 void ComfyEngine::midiTrackTickAndRemove() {
+	_midiTracks.baseTime++;
+	_midiInstanceTrackBase = _midiTracks.baseTime;
+	while (_midiTracks.nextIndex != 0x03E7 && _midiTracks.baseTime >= _midiTracks.nextTime) {
+		keyBitSet(_midiTracks.entries[_midiTracks.nextIndex].id);
+		_midiTracks.count--;
+		_midiTracks.entries[_midiTracks.nextIndex] = _midiTracks.entries[_midiTracks.count];
+		midiFindNext(_midiTracks);
+	}
 }
 
 void ComfyEngine::animFileTickCommands() {
 }
 
 void ComfyEngine::sceneTickEvent() {
+	soundAdvanceTick();
 	if (_soundEventIndex == _soundEventMaximum)
 		return;
 
 	VocQueueEntry &entry = _vocQueue[_soundEventIndex % COMFY_VOC_QUEUE_CAPACITY];
 	if (entry.state == 0xFFFF) {
 		entry.state = 0;
+		_soundEventSubIndex = 0xFFFF;
+		soundPlayEntry(entry.soundId);
 		keyBitSet(1);
 		keyBitSet(4);
 		keyBitClear(2);
 		keyBitClear(3);
-		_soundEventSubIndex = 0xFFFF;
 	} else if (_soundEventSubIndex != 0xFFFF && _soundEventSubIndex != _soundEventPreviousSubIndex) {
 		if (!_soundEventSubIndex) {
 			if (entry.argumentCount)
@@ -335,8 +350,8 @@ void ComfyEngine::sceneTickEvent() {
 		} else if (_soundEventSubIndex == 2) {
 			keyBitSet(4);
 			keyBitClear(3);
-		} else if (_soundEventSubIndex < entry.argumentCount) {
-			keyBitSet(entry.arguments[_soundEventSubIndex]);
+		} else if (_soundEventSubIndex - 2 < entry.argumentCount) {
+			keyBitSet(entry.arguments[_soundEventSubIndex - 2]);
 		}
 	}
 
@@ -344,7 +359,36 @@ void ComfyEngine::sceneTickEvent() {
 }
 
 void ComfyEngine::midiPollChannels(uint16 ticks) {
-	(void)ticks;
+	if (!_midiPlyrDriver)
+		return;
+
+	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
+		MidiChannelState &state = _midiChannels[channel];
+		if (!state.entryCount)
+			continue;
+
+		if (state.playing && !_midiPlyrDriver->musicIsSongPlaying(channel))
+			state.playing = false;
+
+		if (!state.playing)
+			midiFinishChannel(channel);
+
+		int16 volume = midiApproachTarget(state.volumeCurrent, state.volumeTarget, state.volumeTicksLeft, ticks);
+		if ((state.volumeCurrent & 0x7F00) != (volume & 0x7F00))
+			_midiPlyrDriver->musicSetVolume(uint16(volume >> 8), channel);
+
+		state.volumeCurrent = volume;
+		int16 pitch = midiApproachTarget(state.pitchCurrent, state.pitchTarget, state.pitchTicksLeft, ticks);
+		if (pitch != state.pitchCurrent)
+			_midiPlyrDriver->musicSetPitch(pitch, channel);
+
+		state.pitchCurrent = pitch;
+		int16 rate = midiApproachTarget(state.rateCurrent, state.rateTarget, state.rateTicksLeft, ticks);
+		if (rate != state.rateCurrent)
+			_midiPlyrDriver->musicSetRate(rate, channel);
+
+		state.rateCurrent = rate;
+	}
 }
 
 void ComfyEngine::actorTickTree() {
@@ -403,10 +447,12 @@ void ComfyEngine::processMusicEvents() {
 
 	if (vocQueueIsIdle() || _musicEnabled) {
 		uint16 track = 1;
-		while ((_musicEventMask = uint16(int16(_musicEventMask) >> 1)) != 0)
-			track++;
+		while ((_musicEventMask = uint16(int16(_musicEventMask) >> 1)) != 0) {
+			if (_musicEventMask & 1)
+				environmentStore(track);
 
-		(void)track;
+			track++;
+		}
 	}
 }
 
@@ -422,7 +468,18 @@ void ComfyEngine::processSceneTransition() {
 	if (_keyBits)
 		memcpy(keySnapshot, _keyBits, MIN<uint32>(sizeof(keySnapshot), _keyBitsSize));
 
+	if (!_musicEnabled && _midiPlyrDriver)
+		_midiPlyrDriver->musicStopAll(1);
+
 	if (environmentLoad(_pendingScene)) {
+		if (!_musicEnabled) {
+			for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
+				_midiChannels[channel].playing = false;
+				if (_midiChannels[channel].entryCount)
+					midiStartChannel(channel);
+			}
+		}
+
 		Actor *root = actorGet(0);
 		if (root) {
 			paletteLoadWithFade(actorReadWord(*root, kActorXFixed), 0);
@@ -438,6 +495,10 @@ void ComfyEngine::processSceneTransition() {
 }
 
 void ComfyEngine::vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc) {
+	uint16 next = (_soundEventMaximum + 1) % COMFY_VOC_QUEUE_CAPACITY;
+	if (next == _soundEventIndex)
+		return;
+
 	VocQueueEntry &entry = _vocQueue[_soundEventMaximum % COMFY_VOC_QUEUE_CAPACITY];
 	entry.soundId = soundId;
 	entry.argumentCount = MIN<uint16>(argumentCount, COMFY_VOC_ARG_CAPACITY);
@@ -446,12 +507,30 @@ void ComfyEngine::vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc)
 	for (uint i = 0; i < entry.argumentCount; i++)
 		entry.arguments[i] = scriptReadWord(pc + i * 2);
 
-	_soundEventMaximum = (_soundEventMaximum + 1) % COMFY_VOC_QUEUE_CAPACITY;
+	_soundEventMaximum = next;
+	keyBitSet(1);
+	keyBitSet(4);
+	keyBitClear(2);
+	keyBitClear(3);
 }
 
 void ComfyEngine::vocQueuePlayAll() {
-	if (_soundEventIndex != _soundEventMaximum)
-		_soundEventSubIndex = 0xFFFF;
+	_mixer->stopHandle(_soundHandle);
+	uint16 slot = _soundEventIndex;
+	while (slot != _soundEventMaximum) {
+		VocQueueEntry &entry = _vocQueue[slot];
+		for (uint i = 0; i < entry.argumentCount && i < COMFY_VOC_ARG_CAPACITY; i++)
+			keyBitSet(entry.arguments[i]);
+
+		slot = (slot + 1) % COMFY_VOC_QUEUE_CAPACITY;
+	}
+
+	_soundEventMaximum = _soundEventIndex;
+	_soundPcm.clear();
+	keyBitClear(1);
+	keyBitClear(4);
+	keyBitSet(2);
+	keyBitSet(3);
 }
 
 bool ComfyEngine::vocQueueIsIdle() {
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 3dfa71ea0cf..4b98f503693 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -36,8 +36,10 @@
 #include "engines/engine.h"
 #include "engines/savestate.h"
 #include "graphics/screen.h"
+#include "audio/mixer.h"
 
 #include "comfy/detection.h"
+#include "comfy/midiplyr/midiplyr.h"
 
 #define COMFY_SCREEN_WIDTH 320
 #define COMFY_SCREEN_HEIGHT 200
@@ -61,6 +63,10 @@
 #define COMFY_SCENE_FRAME_BYTES 0x4E20
 #define COMFY_VOC_ARG_CAPACITY 10
 #define COMFY_VOC_QUEUE_CAPACITY 16
+#define COMFY_MIDI_QUEUE_CAPACITY 32
+#define COMFY_MIDI_CHANNEL_COUNT 2
+#define COMFY_MIDI_TRACK_ENTRY_CAPACITY 5
+#define COMFY_ANIM_FRAME_CAPACITY 10
 
 namespace Comfy {
 
@@ -130,6 +136,51 @@ private:
 		uint16 arguments[COMFY_VOC_ARG_CAPACITY];
 	};
 
+	struct MidiQueueEntry {
+		uint16 id;
+		int32 time;
+	};
+
+	struct MidiQueue {
+		MidiQueueEntry entries[COMFY_MIDI_QUEUE_CAPACITY];
+		uint16 count;
+		int32 baseTime;
+		uint16 nextIndex;
+		int32 nextTime;
+	};
+
+	struct MidiTrackEntry {
+		uint16 songId;
+		uint16 completionKey;
+		byte loadFlag;
+		uint16 frameCount;
+		uint16 frames[COMFY_ANIM_FRAME_CAPACITY];
+	};
+
+	struct MidiChannelState {
+		MidiTrackEntry entries[COMFY_MIDI_TRACK_ENTRY_CAPACITY];
+		uint16 entryCount;
+		int16 volumeCurrent;
+		int16 volumeTarget;
+		int16 volumeTicksLeft;
+		int16 volumeDefault;
+		int16 rateCurrent;
+		int16 rateTarget;
+		int16 rateTicksLeft;
+		int16 rateDefault;
+		int16 pitchCurrent;
+		int16 pitchTarget;
+		int16 pitchTicksLeft;
+		int16 pitchDefault;
+		uint16 loadedFrameSize;
+		bool playing;
+	};
+
+	struct SoundCue {
+		uint16 value;
+		uint32 counterThreshold;
+	};
+
 	struct Actor {
 		byte raw[COMFY_ACTOR_SIZE];
 	};
@@ -288,6 +339,19 @@ private:
 	uint16 _soundEventMaximum;
 	uint16 _soundEventSubIndex;
 	uint16 _soundEventPreviousSubIndex;
+	MidiQueue _midiEvents;
+	MidiQueue _midiTracks;
+	MidiChannelState _midiChannels[COMFY_MIDI_CHANNEL_COUNT];
+	uint32 _midiInstanceTrackBase;
+	Common::Array<byte> _vocFileData;
+	Common::Array<byte> _soundPcm;
+	Common::Array<SoundCue> _soundCues;
+	Audio::SoundHandle _soundHandle;
+	uint16 _soundTileStride;
+	uint32 _soundSampleRate;
+	uint _soundNextCue;
+	bool _soundCompressed;
+	bool _soundPaused;
 	uint16 _exprStack[COMFY_EXPR_STACK_CAPACITY];
 	uint16 _exprStackTop;
 	bool _scriptFault;
@@ -424,6 +488,24 @@ private:
 	void animFileTickCommands();
 	void sceneTickEvent();
 	void midiPollChannels(uint16 ticks);
+	void midiInitInstance();
+	void midiInitChannels();
+	void midiFindNext(MidiQueue &queue);
+	void midiQueueAdd(MidiQueue &queue, uint16 id, int16 delta);
+	void midiQueueRemove(MidiQueue &queue, uint16 id);
+	void midiAddEvent(uint16 id, int16 delta);
+	void midiAddTrack(uint16 id, int16 delta);
+	void midiRemoveTrack(uint16 id);
+	void midiAddTrackEntry(uint16 channel, uint16 songId, uint16 completionKey, byte loadFlag,
+		uint16 frameCount, uint16 *frames);
+	void midiClearChannel(uint16 channel);
+	void midiStartChannel(uint16 channel);
+	void midiFinishChannel(uint16 channel);
+	void midiStopAndFireKeys(uint16 channel);
+	void midiStopAndRemove(uint16 channel);
+	void midiSetChannelParam(uint16 channel, byte parameter, uint16 value, uint16 ticks);
+	int16 midiApproachTarget(int16 current, int16 target, int16 &ticksLeft, int16 ticks);
+	void musicSetEnabled(byte value);
 	void paletteFadeStep(uint16 ticks);
 	void lptKeyboardScanAndProcess();
 	void actorTickTree();
@@ -434,6 +516,13 @@ private:
 	void vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc);
 	void vocQueuePlayAll();
 	bool vocQueueIsIdle();
+	bool soundInit();
+	void soundShutdown();
+	bool soundDecodeEntry(uint16 index);
+	bool soundDecodeCompressedEntry(uint32 dataOffset, uint32 dataSize);
+	bool soundLoadEntry(uint16 index);
+	void soundPlayEntry(uint16 index);
+	void soundAdvanceTick();
 
 protected:
 	// Engine APIs
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index cc47b408b30..14bf5cdc920 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -293,6 +293,11 @@ bool ComfyEngine::assetsLoad() {
 		return false;
 	}
 
+	if (!soundInit()) {
+		assetsUnload();
+		return false;
+	}
+
 	_stringTable.resize(_stringCount + 1);
 	memset(&_stringTable[0], 0, _stringTable.size() * sizeof(uint16));
 	_sceneHandles.resize(_sceneCount + 1);
@@ -358,7 +363,7 @@ bool ComfyEngine::assetsLoad() {
 	_pendingScene = 0;
 	_musicEventMask = 0;
 	_musicEventFlag = 0;
-	_musicEnabled = true;
+	_musicEnabled = false;
 	memset(_vocQueue, 0, sizeof(_vocQueue));
 	_soundEventIndex = 0;
 	_soundEventMaximum = 0;
@@ -370,6 +375,7 @@ bool ComfyEngine::assetsLoad() {
 }
 
 void ComfyEngine::assetsUnload() {
+	soundShutdown();
 	keyBitFree();
 	_comfyObjData.clear();
 	_picFileData.clear();
diff --git a/engines/comfy/midi.cpp b/engines/comfy/midi.cpp
index 0b3fa24c39d..b061d960553 100644
--- a/engines/comfy/midi.cpp
+++ b/engines/comfy/midi.cpp
@@ -23,6 +23,7 @@
 #include "comfy/midiplyr/midiplyr.h"
 
 #include "common/ptr.h"
+#include "common/endian.h"
 
 namespace Comfy {
 
@@ -54,6 +55,7 @@ uint16 ComfyEngine::midiTick() {
 
 	_midiInstanceEventTime = _midiTimeCounter;
 	_midiEventBaseTime = int32(_midiInstanceEventTime);
+	_midiEvents.baseTime = _midiEventBaseTime;
 
 	int16 delta = int16(uint16(_midiInstanceEventTime - previousCounter));
 	if (delta < 1)
@@ -70,10 +72,18 @@ uint16 ComfyEngine::midiTick() {
 
 			_midiInstanceEventTime = uint32(int32(_midiInstanceEventTime) + _midiTimeDelta - delta);
 			_midiEventBaseTime = int32(_midiInstanceEventTime);
+			_midiEvents.baseTime = _midiEventBaseTime;
 			delta = _midiTimeDelta;
 		}
 	}
 
+	while (_midiEvents.nextIndex != 0x03E7 && int32(_midiInstanceEventTime) >= _midiEvents.nextTime) {
+		keyBitSet(_midiEvents.entries[_midiEvents.nextIndex].id);
+		_midiEvents.count--;
+		_midiEvents.entries[_midiEvents.nextIndex] = _midiEvents.entries[_midiEvents.count];
+		midiFindNext(_midiEvents);
+	}
+
 	return uint16(delta);
 }
 
@@ -146,4 +156,251 @@ void ComfyEngine::midiSetTimeScale(int16 delta) {
 		_midiTimeScale = 10000;
 }
 
+void ComfyEngine::midiFindNext(MidiQueue &queue) {
+	if (!queue.count) {
+		queue.nextIndex = 0x03E7;
+		queue.nextTime = 0;
+		return;
+	}
+
+	queue.nextIndex = 0;
+	queue.nextTime = queue.entries[0].time;
+	for (uint i = 1; i < queue.count; i++) {
+		if (queue.entries[i].time < queue.nextTime) {
+			queue.nextIndex = i;
+			queue.nextTime = queue.entries[i].time;
+		}
+	}
+}
+
+void ComfyEngine::midiInitInstance() {
+	memset(&_midiEvents, 0, sizeof(_midiEvents));
+	memset(&_midiTracks, 0, sizeof(_midiTracks));
+	_midiEvents.baseTime = 0;
+	_midiTracks.baseTime = 1;
+	_midiInstanceTrackBase = 1;
+	midiFindNext(_midiEvents);
+	midiFindNext(_midiTracks);
+}
+
+void ComfyEngine::midiInitChannels() {
+	memset(_midiChannels, 0, sizeof(_midiChannels));
+	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
+		MidiChannelState &state = _midiChannels[channel];
+		state.volumeCurrent = state.volumeTarget = state.volumeDefault = 0x6400;
+		state.rateCurrent = state.rateTarget = state.rateDefault = 0x07D0;
+		state.pitchCurrent = state.pitchTarget = state.pitchDefault = 0x1388;
+	}
+}
+
+void ComfyEngine::midiQueueAdd(MidiQueue &queue, uint16 id, int16 delta) {
+	if (queue.count == COMFY_MIDI_QUEUE_CAPACITY)
+		return;
+
+	queue.entries[queue.count].id = id;
+	queue.entries[queue.count].time = queue.baseTime + delta;
+	queue.count++;
+	midiFindNext(queue);
+}
+
+void ComfyEngine::midiQueueRemove(MidiQueue &queue, uint16 id) {
+	for (uint i = 0; i < queue.count;) {
+		if (queue.entries[i].id == id) {
+			queue.count--;
+			queue.entries[i] = queue.entries[queue.count];
+		} else {
+			i++;
+		}
+	}
+
+	midiFindNext(queue);
+}
+
+void ComfyEngine::midiAddEvent(uint16 id, int16 delta) {
+	midiQueueAdd(_midiEvents, id, delta);
+}
+
+void ComfyEngine::midiAddTrack(uint16 id, int16 delta) {
+	midiQueueAdd(_midiTracks, id, delta);
+}
+
+void ComfyEngine::midiRemoveTrack(uint16 id) {
+	midiQueueRemove(_midiTracks, id);
+	midiQueueRemove(_midiEvents, id);
+}
+
+void ComfyEngine::midiClearChannel(uint16 channel) {
+	if (channel >= COMFY_MIDI_CHANNEL_COUNT)
+		return;
+
+	_midiChannels[channel].loadedFrameSize = 0;
+	_midiChannels[channel].playing = false;
+}
+
+void ComfyEngine::midiStartChannel(uint16 channel) {
+	if (!_midiPlyrDriver || channel >= COMFY_MIDI_CHANNEL_COUNT || !_midiChannels[channel].entryCount)
+		return;
+
+	MidiChannelState &state = _midiChannels[channel];
+	uint32 descriptorOffset = 4 + uint32(state.entries[0].songId) * 6;
+	if (descriptorOffset > _midiFileData.size() || 6 > _midiFileData.size() - descriptorOffset) {
+		midiClearChannel(channel);
+		return;
+	}
+
+	uint16 size = READ_LE_UINT16(&_midiFileData[descriptorOffset]);
+	uint32 fileOffset = READ_LE_UINT32(&_midiFileData[descriptorOffset + 2]);
+	if (!size || fileOffset > _midiFileData.size() || size > _midiFileData.size() - fileOffset || size > _sceneFrameData.size()) {
+		midiClearChannel(channel);
+		return;
+	}
+
+	uint32 destinationOffset = channel ? _sceneFrameData.size() - size : 0;
+	memcpy(&_sceneFrameData[destinationOffset], &_midiFileData[fileOffset], size);
+	state.loadedFrameSize = size;
+	state.rateCurrent = state.rateDefault = size >= 4 ? READ_LE_UINT16(&_sceneFrameData[destinationOffset + 2]) : 0x07D0;
+	state.rateTarget = state.rateCurrent;
+	_midiPlyrDriver->musicPlaySong(&_sceneFrameData[destinationOffset], size, channel);
+	_midiPlyrDriver->musicSetVolume(uint16(state.volumeCurrent >> 8), channel);
+	state.playing = true;
+}
+
+void ComfyEngine::midiFinishChannel(uint16 channel) {
+	if (channel >= COMFY_MIDI_CHANNEL_COUNT)
+		return;
+
+	MidiChannelState &state = _midiChannels[channel];
+	if (!state.entryCount)
+		return;
+
+	if (_midiPlyrDriver)
+		_midiPlyrDriver->musicStopSong(1, channel);
+
+	if (state.entries[0].completionKey)
+		keyBitSet(state.entries[0].completionKey);
+
+	for (uint i = 1; i < state.entryCount; i++)
+		state.entries[i - 1] = state.entries[i];
+
+	state.entryCount--;
+	midiClearChannel(channel);
+	if (state.entryCount)
+		midiStartChannel(channel);
+}
+
+void ComfyEngine::midiStopAndFireKeys(uint16 channel) {
+	if (channel >= COMFY_MIDI_CHANNEL_COUNT)
+		return;
+
+	MidiChannelState &state = _midiChannels[channel];
+	uint16 firstKey = state.entryCount ? state.entries[0].completionKey : 0;
+	if (_midiPlyrDriver)
+		_midiPlyrDriver->musicStopSong(1, channel);
+
+	midiClearChannel(channel);
+	for (uint i = 0; i < state.entryCount; i++) {
+		// The original tests every entry but always fires the first entry's key.
+		if (state.entries[i].completionKey)
+			keyBitSet(firstKey);
+	}
+
+	state.entryCount = 0;
+}
+
+void ComfyEngine::midiStopAndRemove(uint16 channel) {
+	if (channel >= COMFY_MIDI_CHANNEL_COUNT)
+		return;
+
+	if (_midiPlyrDriver)
+		_midiPlyrDriver->musicStopSong(1, channel);
+
+	midiClearChannel(channel);
+	midiFinishChannel(channel);
+}
+
+void ComfyEngine::midiAddTrackEntry(uint16 channel, uint16 songId, uint16 completionKey, byte loadFlag,
+		uint16 frameCount, uint16 *frames) {
+	if (channel >= COMFY_MIDI_CHANNEL_COUNT)
+		channel = 0;
+
+	MidiChannelState &state = _midiChannels[channel];
+	if (state.entryCount == COMFY_MIDI_TRACK_ENTRY_CAPACITY)
+		return;
+
+	MidiTrackEntry &entry = state.entries[state.entryCount];
+	entry.songId = songId;
+	entry.completionKey = completionKey;
+	entry.loadFlag = loadFlag;
+	entry.frameCount = frameCount;
+	memset(entry.frames, 0, sizeof(entry.frames));
+	for (uint i = 0; i < frameCount && i < COMFY_ANIM_FRAME_CAPACITY; i++)
+		entry.frames[i] = frames ? frames[i] : 0;
+
+	state.entryCount++;
+	if (state.entryCount == 1)
+		midiStartChannel(channel);
+}
+
+void ComfyEngine::midiSetChannelParam(uint16 channel, byte parameter, uint16 value, uint16 ticks) {
+	if (channel >= COMFY_MIDI_CHANNEL_COUNT)
+		return;
+
+	MidiChannelState &state = _midiChannels[channel];
+	if (parameter == 2) {
+		state.rateTarget = value ? value : state.rateDefault;
+		state.rateTicksLeft = ticks;
+	} else if (parameter == 3) {
+		state.pitchTarget = value;
+		state.pitchTicksLeft = ticks;
+	} else if (parameter == 4) {
+		state.volumeTarget = int16(value << 8);
+		state.volumeTicksLeft = ticks;
+	}
+
+	if (!ticks && _midiPlyrDriver) {
+		if (parameter == 2) {
+			state.rateCurrent = state.rateTarget;
+			_midiPlyrDriver->musicSetRate(state.rateCurrent, channel);
+		} else if (parameter == 3) {
+			state.pitchCurrent = state.pitchTarget;
+			_midiPlyrDriver->musicSetPitch(state.pitchCurrent, channel);
+		} else if (parameter == 4) {
+			state.volumeCurrent = state.volumeTarget;
+			_midiPlyrDriver->musicSetVolume(uint16(state.volumeCurrent >> 8), channel);
+		}
+	}
+}
+
+int16 ComfyEngine::midiApproachTarget(int16 current, int16 target, int16 &ticksLeft, int16 ticks) {
+	if (!ticksLeft)
+		return current;
+
+	if (ticksLeft < ticks) {
+		ticksLeft = 0;
+		return target;
+	}
+
+	ticksLeft -= ticks;
+	return int16((int32(current) * ticksLeft + int32(target) * ticks) / (ticksLeft + ticks));
+}
+
+void ComfyEngine::musicSetEnabled(byte value) {
+	_musicEnabled = value;
+	_soundPaused = value != 0;
+	_mixer->pauseHandle(_soundHandle, _soundPaused);
+	if (!_midiPlyrDriver)
+		return;
+
+	_midiPlyrDriver->setIncreaseVocCounter(_soundPaused ? 0 : 1);
+
+	if (_musicEnabled) {
+		_midiPlyrDriver->musicStopAll(0);
+	} else {
+		for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
+			if (_midiChannels[channel].entryCount)
+				_midiPlyrDriver->musicContinueSong(channel);
+		}
+	}
+}
+
 } // End of namespace Comfy
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index 273840f0dfc..c90a3611c3e 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -21,12 +21,61 @@
 
 #include "comfy/comfy.h"
 
+#include "common/endian.h"
+
 namespace Comfy {
 
 void ComfyEngine::scenePackRuntimeState() {
 	if (_sceneMemoryBlock.empty())
 		return;
 
+	for (uint i = 0; i < COMFY_MIDI_QUEUE_CAPACITY; i++) {
+		uint32 trackOffset = _sceneMidiInstanceOffset + i * 6;
+		WRITE_LE_UINT16(&_sceneMemoryBlock[trackOffset], _midiTracks.entries[i].id);
+		WRITE_LE_UINT32(&_sceneMemoryBlock[trackOffset + 2], _midiTracks.entries[i].time);
+		uint32 eventOffset = _sceneMidiInstanceOffset + 0x0C0 + i * 6;
+		WRITE_LE_UINT16(&_sceneMemoryBlock[eventOffset], _midiEvents.entries[i].id);
+		WRITE_LE_UINT32(&_sceneMemoryBlock[eventOffset + 2], _midiEvents.entries[i].time);
+	}
+
+	WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x180], _midiInstanceEventTime);
+	WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x184], _midiInstanceTrackBase);
+	WRITE_LE_UINT16(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x188], _midiEvents.count);
+	WRITE_LE_UINT16(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x18A], _midiTracks.count);
+	byte *sceneEntries = &_sceneMemoryBlock[_sceneEntryListOffset];
+	sceneEntries[0] = _sceneEntryCount != 0;
+	WRITE_LE_UINT16(sceneEntries + 1, _sceneEntryCount);
+	WRITE_LE_UINT16(sceneEntries + 3, _sceneEntryFrameSize);
+	for (uint i = 0; i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
+		WRITE_LE_UINT16(sceneEntries + 5 + i * 2, uint16(_sceneEntryOffsets[i]));
+
+	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
+		MidiChannelState &state = _midiChannels[channel];
+		byte *packed = sceneEntries + 0x25 + channel * 0xA1;
+		WRITE_LE_UINT16(packed + 0x87, state.entryCount);
+		WRITE_LE_UINT16(packed + 0x89, state.volumeCurrent);
+		WRITE_LE_UINT16(packed + 0x8B, state.volumeTarget);
+		WRITE_LE_UINT16(packed + 0x8D, state.volumeTicksLeft);
+		WRITE_LE_UINT16(packed + 0x8F, state.volumeDefault);
+		WRITE_LE_UINT16(packed + 0x91, state.rateCurrent);
+		WRITE_LE_UINT16(packed + 0x93, state.rateTarget);
+		WRITE_LE_UINT16(packed + 0x95, state.rateTicksLeft);
+		WRITE_LE_UINT16(packed + 0x97, state.rateDefault);
+		WRITE_LE_UINT16(packed + 0x99, state.pitchCurrent);
+		WRITE_LE_UINT16(packed + 0x9B, state.pitchTarget);
+		WRITE_LE_UINT16(packed + 0x9D, state.pitchTicksLeft);
+		WRITE_LE_UINT16(packed + 0x9F, state.pitchDefault);
+		for (uint entry = 0; entry < state.entryCount && entry < COMFY_MIDI_TRACK_ENTRY_CAPACITY; entry++) {
+			byte *packedEntry = packed + entry * 0x1B;
+			WRITE_LE_UINT16(packedEntry, state.entries[entry].songId);
+			WRITE_LE_UINT16(packedEntry + 2, state.entries[entry].completionKey);
+			packedEntry[4] = state.entries[entry].loadFlag;
+			WRITE_LE_UINT16(packedEntry + 5, state.entries[entry].frameCount);
+			for (uint frame = 0; frame < COMFY_ANIM_FRAME_CAPACITY; frame++)
+				WRITE_LE_UINT16(packedEntry + 7 + frame * 2, state.entries[entry].frames[frame]);
+		}
+	}
+
 	if (!_stringTable.empty())
 		memcpy(&_sceneMemoryBlock[_sceneStringTableOffset], &_stringTable[0], _stringTable.size() * sizeof(uint16));
 
@@ -62,6 +111,55 @@ bool ComfyEngine::environmentLoad(uint16 index) {
 		return false;
 
 	memcpy(&_sceneMemoryBlock[0], &_environmentData[offset], _sceneMemoryBlock.size());
+	for (uint i = 0; i < COMFY_MIDI_QUEUE_CAPACITY; i++) {
+		uint32 trackOffset = _sceneMidiInstanceOffset + i * 6;
+		_midiTracks.entries[i].id = READ_LE_UINT16(&_sceneMemoryBlock[trackOffset]);
+		_midiTracks.entries[i].time = READ_LE_UINT32(&_sceneMemoryBlock[trackOffset + 2]);
+		uint32 eventOffset = _sceneMidiInstanceOffset + 0x0C0 + i * 6;
+		_midiEvents.entries[i].id = READ_LE_UINT16(&_sceneMemoryBlock[eventOffset]);
+		_midiEvents.entries[i].time = READ_LE_UINT32(&_sceneMemoryBlock[eventOffset + 2]);
+	}
+
+	_midiInstanceEventTime = READ_LE_UINT32(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x180]);
+	_midiInstanceTrackBase = READ_LE_UINT32(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x184]);
+	_midiEvents.count = MIN<uint16>(READ_LE_UINT16(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x188]), COMFY_MIDI_QUEUE_CAPACITY);
+	_midiTracks.count = MIN<uint16>(READ_LE_UINT16(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x18A]), COMFY_MIDI_QUEUE_CAPACITY);
+	_midiEvents.baseTime = _midiInstanceEventTime;
+	_midiTracks.baseTime = _midiInstanceTrackBase;
+	midiFindNext(_midiEvents);
+	midiFindNext(_midiTracks);
+	byte *sceneEntries = &_sceneMemoryBlock[_sceneEntryListOffset];
+	_sceneEntryCount = READ_LE_UINT16(sceneEntries + 1);
+	_sceneEntryFrameSize = READ_LE_UINT16(sceneEntries + 3);
+	for (uint i = 0; i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
+		_sceneEntryOffsets[i] = READ_LE_UINT16(sceneEntries + 5 + i * 2);
+
+	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
+		MidiChannelState &state = _midiChannels[channel];
+		byte *packed = sceneEntries + 0x25 + channel * 0xA1;
+		state.entryCount = MIN<uint16>(READ_LE_UINT16(packed + 0x87), COMFY_MIDI_TRACK_ENTRY_CAPACITY);
+		state.volumeCurrent = READ_LE_UINT16(packed + 0x89);
+		state.volumeTarget = READ_LE_UINT16(packed + 0x8B);
+		state.volumeTicksLeft = READ_LE_UINT16(packed + 0x8D);
+		state.volumeDefault = READ_LE_UINT16(packed + 0x8F);
+		state.rateCurrent = READ_LE_UINT16(packed + 0x91);
+		state.rateTarget = READ_LE_UINT16(packed + 0x93);
+		state.rateTicksLeft = READ_LE_UINT16(packed + 0x95);
+		state.rateDefault = READ_LE_UINT16(packed + 0x97);
+		state.pitchCurrent = READ_LE_UINT16(packed + 0x99);
+		state.pitchTarget = READ_LE_UINT16(packed + 0x9B);
+		state.pitchTicksLeft = READ_LE_UINT16(packed + 0x9D);
+		state.pitchDefault = READ_LE_UINT16(packed + 0x9F);
+		for (uint entry = 0; entry < state.entryCount; entry++) {
+			byte *packedEntry = packed + entry * 0x1B;
+			state.entries[entry].songId = READ_LE_UINT16(packedEntry);
+			state.entries[entry].completionKey = READ_LE_UINT16(packedEntry + 2);
+			state.entries[entry].loadFlag = packedEntry[4];
+			state.entries[entry].frameCount = READ_LE_UINT16(packedEntry + 5);
+			for (uint frame = 0; frame < COMFY_ANIM_FRAME_CAPACITY; frame++)
+				state.entries[entry].frames[frame] = READ_LE_UINT16(packedEntry + 7 + frame * 2);
+		}
+	}
 	memcpy(_actorPcTable, &_sceneMemoryBlock[_sceneActorPcOffset], sizeof(_actorPcTable));
 	memcpy(&_stringTable[0], &_sceneMemoryBlock[_sceneStringTableOffset], _stringTable.size() * sizeof(uint16));
 	memcpy(&_sceneHandles[0], &_sceneMemoryBlock[_sceneHandlesOffset], _sceneHandles.size() * sizeof(uint16));
@@ -118,6 +216,8 @@ bool ComfyEngine::sceneOpen() {
 	}
 
 	_sceneOpen = true;
+	midiInitInstance();
+	midiInitChannels();
 	scenePackRuntimeState();
 	renderSetDirty();
 	return true;
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 5fbeb28fb2a..f69d986eba5 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -22,6 +22,7 @@
 #include "comfy/comfy.h"
 
 #include "common/config-manager.h"
+#include "common/endian.h"
 #include "common/ptr.h"
 
 namespace Comfy {
@@ -209,7 +210,10 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	}
 
 	if (opcode == 0x12) {
+		uint16 id = scriptReadWord(pc);
+		int16 delta = scriptReadStringIndex(pc + 2);
 		pc += 4;
+		midiAddTrack(id, delta);
 		return kScriptContinue;
 	}
 
@@ -260,6 +264,8 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 				spriteGet(int16(id));
 				if (_spriteConversionLoads.count < COMFY_RESOURCE_LIST_CAPACITY)
 					_spriteConversionLoads.ids[_spriteConversionLoads.count++] = id;
+			} else {
+				soundLoadEntry(id);
 			}
 		}
 
@@ -312,18 +318,39 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	}
 
 	if (opcode == 0x1C) {
+		midiRemoveTrack(scriptReadWord(pc));
 		pc += 2;
 		return kScriptContinue;
 	}
 
 	if (opcode == 0x1D) {
-		byte subop = scriptReadByte(pc++) & 0x0F;
+		byte packed = scriptReadByte(pc++);
+		byte channel = (packed >> 4) - 1;
+		byte subop = packed & 0x0F;
 		if (subop == 1) {
-			pc += 4;
-			uint16 count = scriptReadWord(pc);
-			pc += 2 + uint32(count) * 2;
+			uint16 songId = scriptReadWord(pc);
+			uint16 completionKey = scriptReadWord(pc + 2);
+			uint16 count = scriptReadWord(pc + 4);
+			pc += 6;
+			uint16 frames[COMFY_ANIM_FRAME_CAPACITY];
+			memset(frames, 0, sizeof(frames));
+			for (uint i = 0; i < count; i++) {
+				uint16 frame = scriptReadWord(pc);
+				pc += 2;
+				if (i < COMFY_ANIM_FRAME_CAPACITY)
+					frames[i] = frame;
+			}
+
+			midiAddTrackEntry(channel, songId, completionKey, 1, count, frames);
 		} else if (subop >= 2 && subop <= 4) {
+			uint16 value = scriptReadWord(pc);
+			uint16 ticks = scriptReadWord(pc + 2);
 			pc += 4;
+			midiSetChannelParam(channel, subop, value, ticks);
+		} else if (subop == 5 && channel < COMFY_MIDI_CHANNEL_COUNT) {
+			midiStopAndRemove(channel);
+		} else if (subop == 6 && channel < COMFY_MIDI_CHANNEL_COUNT) {
+			midiStopAndFireKeys(channel);
 		}
 
 		return kScriptContinue;
@@ -390,7 +417,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	}
 
 	if (opcode == 0x22) {
-		_musicEnabled = scriptReadByte(pc) != 0;
+		musicSetEnabled(scriptReadByte(pc));
 		pc++;
 		return kScriptContinue;
 	}
@@ -487,9 +514,23 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			pc += 4;
 			sceneEntryLoad(descriptor, index);
 		} else if (subop == 4) {
+			uint16 channel = scriptReadWord(pc);
+			uint16 frame = scriptReadWord(pc + 2);
 			pc += 4;
+			uint32 offset = uint32(_sceneEntryFrameSize) * frame;
+			if (_midiPlyrDriver && channel < COMFY_MIDI_CHANNEL_COUNT && offset + 6 <= _sceneFrameData.size()) {
+				uint16 size = READ_LE_UINT16(&_sceneFrameData[offset + 4]) + 6;
+				if (size <= _sceneFrameData.size() - offset) {
+					_midiPlyrDriver->musicStopSong(1, channel);
+					_midiPlyrDriver->musicPlaySong(&_sceneFrameData[offset], size, channel);
+					_midiPlyrDriver->musicSetVolume(0x64, channel);
+				}
+			}
 		} else if (subop == 5) {
+			uint16 channel = scriptReadWord(pc);
 			pc += 2;
+			if (_midiPlyrDriver && channel < COMFY_MIDI_CHANNEL_COUNT)
+				_midiPlyrDriver->musicStopSong(1, channel);
 		}
 
 		return kScriptContinue;
@@ -683,7 +724,10 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptYield;
 
 	if (opcode == 0x6F) {
+		uint16 id = scriptReadWord(pc);
+		int16 delta = scriptReadStringIndex(pc + 2);
 		pc += 4;
+		midiAddEvent(id, delta);
 		return kScriptContinue;
 	}
 
diff --git a/engines/comfy/sound.cpp b/engines/comfy/sound.cpp
index 409cdeb90bd..f9af4596124 100644
--- a/engines/comfy/sound.cpp
+++ b/engines/comfy/sound.cpp
@@ -19,7 +19,366 @@
  *
  */
 
+#include "comfy/comfy.h"
+#include "comfy/midiplyr/midiplyr.h"
+
+#include "audio/decoders/raw.h"
+#include "audio/audiostream.h"
+#include "common/endian.h"
+
 namespace Comfy {
 
+class SoundBitReader {
+public:
+	SoundBitReader(byte *data, uint32 size) : _data(data), _size(size), _bitPosition(0), _fault(false) {}
+
+	uint32 read(uint bits) {
+		uint32 value = 0;
+		for (uint bit = 0; bit < bits; bit++) {
+			uint32 bytePosition = _bitPosition >> 3;
+			if (bytePosition >= _size) {
+				_fault = true;
+				return value;
+			}
+
+			value |= uint32((_data[bytePosition] >> (_bitPosition & 7)) & 1) << bit;
+			_bitPosition++;
+		}
+
+		return value;
+	}
+
+	uint32 position() { return _bitPosition; }
+	void setPosition(uint32 position) { _bitPosition = position; }
+	bool fault() { return _fault; }
+
+private:
+	byte *_data;
+	uint32 _size;
+	uint32 _bitPosition;
+	bool _fault;
+};
+
+bool ComfyEngine::soundInit() {
+	soundShutdown();
+	if (!readAssetFile(Common::Path("VOCFILE.DAT"), _vocFileData) || _vocFileData.size() < 4)
+		return false;
+
+	if (_vocFileData[0] != 'C' || (_vocFileData[1] != 'V' && _vocFileData[1] != 'W'))
+		return false;
+
+	_soundCompressed = _vocFileData[1] == 'W';
+	_soundTileStride = READ_LE_UINT16(&_vocFileData[2]);
+	_soundEventIndex = 0;
+	_soundEventMaximum = 0;
+	_soundEventSubIndex = 0xFFFF;
+	_soundEventPreviousSubIndex = 0xFFFF;
+	return true;
+}
+
+void ComfyEngine::soundShutdown() {
+	_mixer->stopHandle(_soundHandle);
+	_soundPcm.clear();
+	_soundCues.clear();
+	_vocFileData.clear();
+	_soundTileStride = 0;
+	_soundNextCue = 0;
+	_soundPaused = false;
+	if (_midiPlyrDriver)
+		_midiPlyrDriver->setIncreaseVocCounter(0);
+}
+
+bool ComfyEngine::soundLoadEntry(uint16 index) {
+	uint32 headerOffset = 4 + uint32(index) * 8;
+	if (headerOffset > _vocFileData.size() || 8 > _vocFileData.size() - headerOffset)
+		return false;
+
+	uint32 size = READ_LE_UINT32(&_vocFileData[headerOffset]);
+	uint32 offset = READ_LE_UINT32(&_vocFileData[headerOffset + 4]);
+	return offset <= _vocFileData.size() && size <= _vocFileData.size() - offset;
+}
+
+bool ComfyEngine::soundDecodeEntry(uint16 index) {
+	_soundPcm.clear();
+	_soundCues.clear();
+	_soundNextCue = 0;
+	uint32 headerOffset = 4 + uint32(index) * 8;
+	if (headerOffset > _vocFileData.size() || 8 > _vocFileData.size() - headerOffset)
+		return false;
+
+	uint32 dataSize = READ_LE_UINT32(&_vocFileData[headerOffset]);
+	uint32 dataOffset = READ_LE_UINT32(&_vocFileData[headerOffset + 4]);
+	if (dataOffset > _vocFileData.size() || dataSize > _vocFileData.size() - dataOffset)
+		return false;
+
+	if (_soundCompressed)
+		return soundDecodeCompressedEntry(dataOffset, dataSize);
+
+	uint32 pc = dataOffset;
+	uint32 end = dataOffset + dataSize;
+	byte sample = 0xA5;
+	_soundSampleRate = 0x2B11;
+	uint32 loopPc = 0;
+	int16 loopCount = 0;
+	uint32 commandCount = 0;
+	while (pc < end && commandCount++ < dataSize) {
+		byte command = _vocFileData[pc++];
+		if (!command) {
+			SoundCue cue = {0, uint32((_soundPcm.size() * 100) / _soundSampleRate)};
+			_soundCues.push_back(cue);
+			break;
+		}
+
+		if (3 > end - pc)
+			return false;
+
+		uint32 argument = uint32(_vocFileData[pc]) | (uint32(_vocFileData[pc + 1]) << 8) |
+			(uint32(_vocFileData[pc + 2]) << 16);
+		pc += 3;
+		if (command == 1 || command == 2) {
+			uint32 length = argument;
+			if (command == 1) {
+				if (length < 2 || 2 > end - pc)
+					return false;
+
+				sample = _vocFileData[pc];
+				pc += 2;
+				length -= 2;
+				uint32 denominator = 0x100 - sample;
+				_soundSampleRate = denominator ? 0x0F4240 / denominator : 0x2B11;
+				if (_soundSampleRate > 0x2710 && _soundSampleRate < 0x2EE0)
+					_soundSampleRate = 0x2B11;
+				else if (_soundSampleRate > 0x4E20 && _soundSampleRate < 0x5DC0)
+					_soundSampleRate = 0x5622;
+			}
+
+			if (length > end - pc)
+				return false;
+
+			uint32 oldSize = _soundPcm.size();
+			_soundPcm.resize(oldSize + length);
+			memcpy(&_soundPcm[oldSize], &_vocFileData[pc], length);
+			pc += length;
+		} else if (command == 3) {
+			if (3 > end - pc)
+				return false;
+
+			uint16 fill = READ_LE_UINT16(&_vocFileData[pc]);
+			byte nextSample = _vocFileData[pc + 2];
+			pc += 3;
+			if (nextSample != sample) {
+				uint32 oldRate = _soundSampleRate;
+				uint32 newRate = 0x0F4240 / (0x100 - nextSample);
+				fill = uint16((uint32(fill) * oldRate) / newRate);
+			}
+
+			uint32 oldSize = _soundPcm.size();
+			_soundPcm.resize(oldSize + fill);
+			memset(&_soundPcm[oldSize], 0x80, fill);
+		} else if (command == 4) {
+			if (2 > end - pc)
+				return false;
+
+			SoundCue cue = {READ_LE_UINT16(&_vocFileData[pc]), uint32((_soundPcm.size() * 100) / _soundSampleRate)};
+			_soundCues.push_back(cue);
+			pc += 2;
+		} else if (command == 6) {
+			if (2 > end - pc)
+				return false;
+
+			loopCount = READ_LE_UINT16(&_vocFileData[pc]);
+			pc += 2;
+			loopPc = pc;
+		} else if (command == 7) {
+			if (loopCount > 0 && loopPc) {
+				loopCount--;
+				pc = loopPc;
+			}
+		} else if (command == 99) {
+			if (pc >= end)
+				return false;
+
+			sample = _vocFileData[pc++];
+		}
+	}
+
+	return !_soundPcm.empty();
+}
+
+bool ComfyEngine::soundDecodeCompressedEntry(uint32 dataOffset, uint32 dataSize) {
+	if (dataSize < 5)
+		return false;
+
+	byte sample = _vocFileData[dataOffset + 4];
+	uint32 denominator = 0x100 - sample;
+	_soundSampleRate = denominator ? 0x0F4240 / denominator : 0x2B11;
+	if (_soundSampleRate > 0x2710 && _soundSampleRate < 0x2EE0)
+		_soundSampleRate = 0x2B11;
+	else if (_soundSampleRate > 0x4E20 && _soundSampleRate < 0x5DC0)
+		_soundSampleRate = 0x5622;
+
+	SoundBitReader bits(&_vocFileData[dataOffset + 5], dataSize - 5);
+	uint32 loopPosition = 0;
+	int16 loopCount = 0;
+	byte width = 4;
+	byte predictorDistance = 1;
+	bool needInit = false;
+	uint32 commandCount = 0;
+	while (!bits.fault() && commandCount++ < dataSize * 8) {
+		uint16 command = bits.read(2);
+		uint32 argument = 0;
+		if (!command) {
+			uint16 subcommand = bits.read(2);
+			if (!subcommand)
+				command = 0;
+			else if (subcommand == 1) {
+				command = bits.read(8);
+				argument = bits.read(20);
+			} else if (subcommand == 2)
+				command = 7;
+			else
+				command = 99;
+		} else if (command == 1) {
+			argument = bits.read(20);
+		} else if (command == 2) {
+			command = 3;
+		} else {
+			command = 4;
+		}
+
+		if (command == 0) {
+			SoundCue cue = {0, uint32((_soundPcm.size() * 100) / _soundSampleRate)};
+			_soundCues.push_back(cue);
+			break;
+		} else if (command == 1 || command == 2) {
+			uint32 length = argument;
+			if (command == 1)
+				needInit = true;
+
+			uint32 oldSize = _soundPcm.size();
+			_soundPcm.resize(oldSize + length);
+			uint32 output = oldSize;
+			if (needInit && length) {
+				needInit = false;
+				width = 4;
+				predictorDistance = 1;
+				_soundPcm[output++] = bits.read(8);
+				length--;
+			}
+
+			while (length && !bits.fault()) {
+				uint32 chunk = MIN<uint32>(length, 0x20);
+				if (bits.read(1))
+					width = bits.read(3);
+
+				if (width && bits.read(1))
+					predictorDistance = bits.read(7);
+
+				for (uint i = 0; i < chunk; i++) {
+					byte value;
+					if (!width) {
+						value = bits.read(8);
+					} else {
+						uint16 delta = bits.read(width);
+						if (!delta)
+							value = bits.read(8);
+						else {
+							byte predictor = output >= predictorDistance ? _soundPcm[output - predictorDistance] : 0x80;
+							value = predictor + byte(delta - (1 << (width - 1)));
+						}
+					}
+
+					_soundPcm[output++] = value;
+				}
+
+				length -= chunk;
+			}
+		} else if (command == 3) {
+			uint16 fill = bits.read(16);
+			uint32 oldSize = _soundPcm.size();
+			_soundPcm.resize(oldSize + fill);
+			memset(&_soundPcm[oldSize], 0x80, fill);
+		} else if (command == 4) {
+			uint16 mode = bits.read(2);
+			uint16 value = mode == 0 ? 1 : mode == 1 ? 2 : mode == 2 ? bits.read(8) : bits.read(16);
+			SoundCue cue = {value, uint32((_soundPcm.size() * 100) / _soundSampleRate)};
+			_soundCues.push_back(cue);
+		} else if (command == 6) {
+			loopCount = bits.read(16);
+			loopPosition = bits.position();
+		} else if (command == 7) {
+			if (loopCount > 0 && loopPosition) {
+				loopCount--;
+				bits.setPosition(loopPosition);
+			}
+		} else if (command == 99) {
+			sample = bits.read(8);
+		}
+	}
+
+	return !_soundPcm.empty() && !bits.fault();
+}
+
+void ComfyEngine::soundPlayEntry(uint16 index) {
+	_mixer->stopHandle(_soundHandle);
+	if (!soundDecodeEntry(index)) {
+		_soundEventSubIndex = 0;
+		return;
+	}
+
+	Audio::AudioStream *stream = Audio::makeRawStream(&_soundPcm[0], _soundPcm.size(), _soundSampleRate,
+		Audio::FLAG_UNSIGNED, DisposeAfterUse::NO);
+	if (!stream) {
+		_soundPcm.clear();
+		_soundEventSubIndex = 0;
+		return;
+	}
+
+	_mixer->playStream(Audio::Mixer::kSpeechSoundType, &_soundHandle, stream, -1,
+		Audio::Mixer::kMaxChannelVolume, 0, DisposeAfterUse::YES);
+	_soundPaused = false;
+	_soundEventSubIndex = 0xFFFF;
+	if (_midiPlyrDriver) {
+		_midiPlyrDriver->vocSrResetCounters();
+		_midiPlyrDriver->setVocCounter(0);
+		_midiPlyrDriver->setIncreaseVocCounter(1);
+	}
+}
+
+void ComfyEngine::soundAdvanceTick() {
+	if (_soundPaused)
+		return;
+
+	if (!_mixer->isSoundHandleActive(_soundHandle)) {
+		if (!_soundPcm.empty())
+			_soundEventSubIndex = 0;
+
+		return;
+	}
+
+	uint32 counter = _midiPlyrDriver ? _midiPlyrDriver->getVocCounter() :
+		uint32((_mixer->getSoundElapsedTime(_soundHandle) + 9) / 10);
+	uint32 compareCounter = counter >= 2 ? counter - 2 : 0;
+	bool phaseCueSeen = false;
+	while (_soundNextCue < _soundCues.size() && compareCounter > _soundCues[_soundNextCue].counterThreshold &&
+			(_soundCues[_soundNextCue].value == 1 || _soundCues[_soundNextCue].value == 2)) {
+		phaseCueSeen = true;
+		_soundEventSubIndex = _soundCues[_soundNextCue].value;
+		_soundNextCue++;
+	}
+
+	if (phaseCueSeen || _soundNextCue == _soundCues.size() ||
+			compareCounter <= _soundCues[_soundNextCue].counterThreshold)
+		return;
+
+	_soundEventSubIndex = _soundCues[_soundNextCue].value;
+	_soundNextCue++;
+	if (!_soundEventSubIndex) {
+		_mixer->stopHandle(_soundHandle);
+		if (_midiPlyrDriver)
+			_midiPlyrDriver->setIncreaseVocCounter(0);
+	}
+}
+
 
 } // End of namespace Comfy


Commit: 462bc777a3d9352bb47777adeac12570f58a8062
    https://github.com/scummvm/scummvm/commit/462bc777a3d9352bb47777adeac12570f58a8062
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Connect ImGui keyboard to engine

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/comfy_keyboard_ui.cpp
    engines/comfy/detection.h
    engines/comfy/detection_tables.h
    engines/comfy/game.cpp
    engines/comfy/input.cpp
    engines/comfy/metaengine.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 77cf746545b..b6e1fa653bd 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -114,7 +114,8 @@ Common::Error ComfyEngine::run() {
 
 	uint16 currentScene = _language;
 	uint16 chooserScene = currentScene;
-	if (_multiLanguage && !ConfMan.getBool("comfy_language_chosen")) {
+	if (_multiLanguage && (ConfMan.getBool("force_language_setup") ||
+			!ConfMan.getBool("comfy_language_chosen"))) {
 		if (!iniGetGameDataPath(0x63)) {
 			gameShutdown();
 			return Common::kNoGameDataFoundError;
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 4b98f503693..093749bbeef 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -531,6 +531,7 @@ protected:
 public:
 	ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc);
 	~ComfyEngine() override;
+	void setToyKeyboardState(uint32 activeMask, uint32 latchedMask, uint32 holdMask);
 
 	/**
 	 * Returns the game Id
diff --git a/engines/comfy/comfy_keyboard_ui.cpp b/engines/comfy/comfy_keyboard_ui.cpp
index df09c73257b..45663bafc9a 100644
--- a/engines/comfy/comfy_keyboard_ui.cpp
+++ b/engines/comfy/comfy_keyboard_ui.cpp
@@ -138,9 +138,17 @@ void onImGuiInit() {
 }
 
 void onImGuiRender() {
-	if (_state->_engine->shouldQuit() || !_state || !_state->_engine || !_state->_visible)
+	if (!_state || !_state->_engine || _state->_engine->shouldQuit())
 		return;
 
+	if (!_state->_visible) {
+		_state->_engine->setToyKeyboardState(0, _state->_latchedMask | _state->_activeMask, 0);
+		_state->_activeMask = 0;
+		_state->_latchedMask = 0;
+		_state->_holdMask = 0;
+		return;
+	}
+
 	ImGui::GetIO().ConfigFlags &= ~(ImGuiConfigFlags_NoMouseCursorChange | ImGuiConfigFlags_NoMouse);
 
 	ImGui::SetNextWindowSize(ImVec2(780, 520), ImGuiCond_FirstUseEver);
@@ -227,9 +235,14 @@ void onImGuiRender() {
 	}
 
 	ImGui::End();
+	_state->_engine->setToyKeyboardState(_state->_activeMask, _state->_latchedMask, _state->_holdMask);
+	_state->_latchedMask = 0;
 }
 
 void onImGuiCleanup() {
+	if (_state && _state->_engine)
+		_state->_engine->setToyKeyboardState(0, 0, 0);
+
 	delete _state;
 	_state = nullptr;
 }
diff --git a/engines/comfy/detection.h b/engines/comfy/detection.h
index 542d8c8ed39..78023535eb3 100644
--- a/engines/comfy/detection.h
+++ b/engines/comfy/detection.h
@@ -44,7 +44,7 @@ extern const PlainGameDescriptor comfyGames[];
 
 extern const ADGameDescription gameDescriptions[];
 
-#define GAMEOPTION_ORIGINAL_SAVELOAD GUIO_GAMEOPTIONS1
+#define GAMEOPTION_FORCE_LANGUAGE_SETUP GUIO_GAMEOPTIONS1
 
 } // End of namespace Comfy
 
diff --git a/engines/comfy/detection_tables.h b/engines/comfy/detection_tables.h
index 370c782ca80..9e64ae2672a 100644
--- a/engines/comfy/detection_tables.h
+++ b/engines/comfy/detection_tables.h
@@ -43,7 +43,7 @@ const ADGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GUIO_NONE)
+		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 	},
 
 	{
@@ -57,7 +57,7 @@ const ADGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GUIO_NONE)
+		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 	},
 
 	{
@@ -69,7 +69,7 @@ const ADGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GUIO_NONE)
+		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 	},
 
 	{
@@ -80,7 +80,7 @@ const ADGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GUIO_NONE)
+		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 	},
 
 	{
@@ -91,7 +91,7 @@ const ADGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GUIO_NONE)
+		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 	},
 
 	{
@@ -103,7 +103,7 @@ const ADGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GUIO_NONE)
+		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 	},
 
 	{
@@ -115,7 +115,7 @@ const ADGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GUIO_NONE)
+		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 	},
 
 	{
@@ -127,7 +127,7 @@ const ADGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GUIO_NONE)
+		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 	},
 
 	{
@@ -139,7 +139,7 @@ const ADGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GUIO_NONE)
+		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 	},
 
 	AD_TABLE_END_MARKER
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index 14bf5cdc920..2a669e66a5d 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -103,6 +103,7 @@ void ComfyEngine::gameConfigInit() {
 	findLanguageDirectories();
 	ConfMan.registerDefault("comfy_language", 2);
 	ConfMan.registerDefault("comfy_language_chosen", false);
+	ConfMan.registerDefault("force_language_setup", false);
 	ConfMan.registerDefault("comfy_screen_update_interleaved", false);
 	ConfMan.registerDefault("comfy_input_device", 0);
 }
diff --git a/engines/comfy/input.cpp b/engines/comfy/input.cpp
index 0301ab5812b..b1fafb0f882 100644
--- a/engines/comfy/input.cpp
+++ b/engines/comfy/input.cpp
@@ -201,6 +201,12 @@ void ComfyEngine::setKeyboardContact(uint16 contact, bool pressed, bool keymappe
 	}
 }
 
+void ComfyEngine::setToyKeyboardState(uint32 activeMask, uint32 latchedMask, uint32 holdMask) {
+	_toyKeyboardActiveMask = activeMask & 0x00FFFFFF;
+	_toyKeyboardLatchedMask |= latchedMask & 0x00FFFFFF;
+	_toyKeyboardHoldMask = holdMask & 0x00FFFFFF;
+}
+
 uint32 ComfyEngine::lptKeyboardScan() {
 	// The original wrote eight successive column strobes to the LPT data port, waited 100 busy-loop
 	// iterations after each write, and sampled three bits from the status port. Concatenating those
diff --git a/engines/comfy/metaengine.cpp b/engines/comfy/metaengine.cpp
index 9c1df853030..4046a9302d0 100644
--- a/engines/comfy/metaengine.cpp
+++ b/engines/comfy/metaengine.cpp
@@ -32,11 +32,11 @@ namespace Comfy {
 
 static const ADExtraGuiOptionsMap optionsList[] = {
 	{
-		GAMEOPTION_ORIGINAL_SAVELOAD,
+		GAMEOPTION_FORCE_LANGUAGE_SETUP,
 		{
-			_s("Use original save/load screens"),
-			_s("Use the original save/load screens instead of the ScummVM ones"),
-			"original_menus",
+			_s("Force language setup screen on start-up"),
+			_s("Show the original language setup screen every time the game starts"),
+			"force_language_setup",
 			false,
 			0,
 			0


Commit: a8542b6e560441e639a331e58080a43fac1ce5c7
    https://github.com/scummvm/scummvm/commit/a8542b6e560441e639a331e58080a43fac1ce5c7
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Add ANM system

Changed paths:
  A engines/comfy/anim_file.cpp
    engines/comfy/actor.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/game.cpp
    engines/comfy/module.mk
    engines/comfy/script_vm.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index f5d529dd8fa..08ede5b9773 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -837,6 +837,9 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 	if (!actor)
 		return true;
 
+	if (!animFrameShouldDraw(1))
+		return false;
+
 	int16 drawX = int16(int32(actorReadDword(*actor, kActorXFixed)) >> 12) + x;
 	int16 drawY = int16(int32(actorReadDword(*actor, kActorYFixed)) >> 12) + y;
 	byte oldVisible = actorReadByte(*actor, kActorCachedVisible);
@@ -849,6 +852,7 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 		return true;
 	}
 
+	animFrameRecordVocCounter(1);
 	actorDrawList(actorReadWord(*actor, kActorSiblingHead), drawX, drawY);
 	uint32 selector = actorReadDword(*actor, kActorSpriteSelector);
 	VideoRectRecord newRect = {0, 0, 0, 0, 0};
@@ -865,6 +869,7 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 			spriteBlitClipped(int16(selector), drawX - sprite->header.hotspotX, drawY - sprite->header.hotspotY);
 		}
 	}
+	animFrameRecordVocCounter(2);
 
 	bool rectChanged = oldRect.left != newRect.left || oldRect.top != newRect.top ||
 		oldRect.right != newRect.right || oldRect.bottom != newRect.bottom || oldRect.area != newRect.area;
@@ -880,7 +885,7 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 	actorWriteDword(*actor, kActorCachedSprite, selector);
 	actorWriteCachedRect(*actor, newRect);
 	actorDrawList(actorReadWord(*actor, kActorChildHead), drawX, drawY);
-	return true;
+	return animFrameShouldDraw(2);
 }
 
 
diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
new file mode 100644
index 00000000000..348655374a2
--- /dev/null
+++ b/engines/comfy/anim_file.cpp
@@ -0,0 +1,423 @@
+/* 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 "comfy/comfy.h"
+#include "comfy/midiplyr/midiplyr.h"
+
+#include "common/endian.h"
+
+namespace Comfy {
+
+enum AnimFileCommand {
+	kAnimCommandEnd = 0x2145,
+	kAnimCommandStoreFrameBytes = 0x4356,
+	kAnimCommandDirtyRect = 0x5842,
+	kAnimCommandFrame = 0x5246
+};
+
+bool ComfyEngine::animFileOpen() {
+	animFileShutdown(true);
+	if (!readAssetFile(Common::Path("ANMFILE.DAT"), _animFileData) ||
+			_animFileData.size() < COMFY_ANMFILE_HEADER_BYTES)
+		return false;
+
+	uint16 magic = READ_LE_UINT16(&_animFileData[0]);
+	if (magic != COMFY_ANMFILE_MAGIC && magic != COMFY_ANMFILE_PANTHER_MAGIC)
+		return false;
+
+	uint16 count = READ_LE_UINT16(&_animFileData[2]);
+	if (uint32(COMFY_ANMFILE_HEADER_BYTES) + uint32(count) * 4 > _animFileData.size())
+		return false;
+
+	_animIndexTable.resize(count);
+	for (uint i = 0; i < count; i++)
+		_animIndexTable[i] = READ_LE_UINT32(&_animFileData[COMFY_ANMFILE_HEADER_BYTES + i * 4]);
+
+	_animPantherFormat = magic == COMFY_ANMFILE_PANTHER_MAGIC;
+	_animIndexLoaded = true;
+	return true;
+}
+
+void ComfyEngine::animFileShutdown(bool closeFile) {
+	if (_animActive) {
+		if (_animCurrentFrameKey)
+			keyBitSet(_animCurrentFrameKey);
+
+		if (_animCurrentActorSceneHandle < _sceneHandles.size()) {
+			Actor *actor = actorGet(_sceneHandles[_animCurrentActorSceneHandle]);
+			if (actor)
+				actorWriteDword(*actor, kActorSpriteSelector, 0);
+		}
+	}
+
+	_animActive = false;
+	_animCurrentIndex = 0;
+	_animCurrentActorSceneHandle = 0;
+	_animCurrentFrameKey = 0;
+	_animVocClockHz = 0;
+	_animVocTargetCounter = 0;
+	if (closeFile) {
+		_animFileData.clear();
+		_animIndexTable.clear();
+		_animFrameBuffer.clear();
+		_animFrameStorage.clear();
+		_animPosition = 0;
+		_animIndexLoaded = false;
+		_animPantherFormat = false;
+	}
+}
+
+void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 actorSceneHandle) {
+	if (!_animIndexLoaded || _animActive || animIndex >= _animIndexTable.size()) {
+		_animActive = false;
+		return;
+	}
+
+	uint32 offset = _animIndexTable[animIndex];
+	if (offset > _animFileData.size() || COMFY_ANMFILE_HEADER_BYTES > _animFileData.size() - offset)
+		return;
+
+	memcpy(_animFrameHeader, &_animFileData[offset], sizeof(_animFrameHeader));
+	uint16 expectedMagic = _animPantherFormat ? COMFY_ANMFRAME_PANTHER_MAGIC : COMFY_ANMFRAME_MAGIC;
+	if (READ_LE_UINT16(_animFrameHeader) != expectedMagic)
+		return;
+
+	_animFrameBuffer.resize(_animPantherFormat ? framebufferBytes() : COMFY_ANMFRAME_BYTES);
+	memset(&_animFrameBuffer[0], 0xFF, _animFrameBuffer.size());
+	_animFrameStorage.clear();
+	memset(_animPendingDirtyRect, 0, sizeof(_animPendingDirtyRect));
+	_animPendingDirtyRectSize = 0;
+	_animPosition = offset + COMFY_ANMFILE_HEADER_BYTES;
+	_animCurrentIndex = animIndex;
+	_animCurrentActorSceneHandle = actorSceneHandle;
+	_animCurrentFrameKey = frameKey;
+	_animVocCounterMode = 0;
+	_animVocClockHz = READ_LE_UINT16(_animFrameHeader + 8);
+	_animVocTargetCounter = 0xFFFF;
+	_animVocBaseCounter = 0;
+	_animVocDeltaA = 0;
+	_animActive = true;
+	if (actorSceneHandle < _sceneHandles.size()) {
+		Actor *actor = actorGet(_sceneHandles[actorSceneHandle]);
+		if (actor)
+			actorWriteDword(*actor, kActorSpriteSelector, 0x00FFFFFF);
+	}
+
+	animFileTickCommands();
+}
+
+uint32 ComfyEngine::animDecompressRle(const byte *source, uint32 sourceSize, byte *destination, uint32 destinationSize) {
+	uint32 sourcePosition = 0;
+	uint32 destinationPosition = 0;
+	while (sourcePosition < sourceSize) {
+		byte control = source[sourcePosition++];
+		if (!control) {
+			do {
+				if (sourcePosition + 1 >= sourceSize || destinationPosition >= destinationSize)
+					return destinationPosition;
+
+				sourcePosition++;
+				destination[destinationPosition++] = source[sourcePosition++];
+				if (sourcePosition >= sourceSize)
+					return destinationPosition;
+
+				control = source[sourcePosition++];
+			} while (!control);
+		}
+
+		for (;;) {
+			if (control == 0x80) {
+				if (sourcePosition + 1 >= sourceSize)
+					return destinationPosition;
+
+				uint16 word = READ_LE_UINT16(source + sourcePosition);
+				sourcePosition += 2;
+				if (!word)
+					return destinationPosition;
+
+				if (int16(word) > 0) {
+					destinationPosition = MIN<uint32>(destinationPosition + word, destinationSize);
+					break;
+				}
+
+				uint16 count = word - 0x8000;
+				if ((count & 0x4000) == 0) {
+					count = MIN<uint32>(count, sourceSize - sourcePosition);
+					count = MIN<uint32>(count, destinationSize - destinationPosition);
+					memcpy(destination + destinationPosition, source + sourcePosition, count);
+					sourcePosition += count;
+					destinationPosition += count;
+					break;
+				}
+
+				count -= 0x4000;
+				if (sourcePosition >= sourceSize)
+					return destinationPosition;
+
+				count = MIN<uint32>(count, destinationSize - destinationPosition);
+				memset(destination + destinationPosition, source[sourcePosition++], count);
+				destinationPosition += count;
+				break;
+			}
+
+			if (control & 0x80) {
+				destinationPosition = MIN<uint32>(destinationPosition + control - 0x80, destinationSize);
+				break;
+			}
+
+			if (sourcePosition >= sourceSize || destinationPosition >= destinationSize)
+				return destinationPosition;
+
+			destination[destinationPosition++] = source[sourcePosition++];
+			if (sourcePosition >= sourceSize)
+				return destinationPosition;
+
+			control = source[sourcePosition++];
+			if (!control)
+				break;
+		}
+	}
+
+	return destinationPosition;
+}
+
+uint32 ComfyEngine::animDecodePanther(const byte *source, uint32 sourceSize) {
+	if (sourceSize < 6 || _animFrameBuffer.empty())
+		return 0;
+
+	uint16 kind = READ_LE_UINT16(source + 4);
+	uint32 sourcePosition = 6;
+	uint32 destinationPosition = 0;
+	uint32 written = 0;
+	if (kind == 7) {
+		if (sourcePosition + 2 > sourceSize)
+			return 0;
+
+		uint16 rows = READ_LE_UINT16(source + sourcePosition);
+		sourcePosition += 2;
+		while (rows && sourcePosition + 2 <= sourceSize && destinationPosition < _animFrameBuffer.size()) {
+			uint16 runCount = READ_LE_UINT16(source + sourcePosition);
+			sourcePosition += 2;
+			if (runCount & 0x4000) {
+				destinationPosition += uint32(uint16(0 - runCount)) * _logicalScreenWidth;
+				continue;
+			}
+
+			uint32 rowStart = destinationPosition;
+			while (runCount && sourcePosition < sourceSize && destinationPosition < _animFrameBuffer.size()) {
+				destinationPosition += source[sourcePosition++];
+				if (sourcePosition >= sourceSize || destinationPosition >= _animFrameBuffer.size())
+					return written;
+
+				byte control = source[sourcePosition++];
+				if (control & 0x80) {
+					uint16 count = 0x100 - control;
+					if (sourcePosition + 2 > sourceSize)
+						return written;
+
+					byte low = source[sourcePosition++];
+					byte high = source[sourcePosition++];
+					while (count-- && destinationPosition + 1 < _animFrameBuffer.size()) {
+						_animFrameBuffer[destinationPosition++] = low;
+						_animFrameBuffer[destinationPosition++] = high;
+						written += 2;
+					}
+				} else {
+					uint16 count = MIN<uint32>(control, sourceSize - sourcePosition);
+					count = MIN<uint32>(count, _animFrameBuffer.size() - destinationPosition);
+					memcpy(&_animFrameBuffer[destinationPosition], source + sourcePosition, count);
+					sourcePosition += count;
+					destinationPosition += count;
+					written += count;
+				}
+
+				runCount--;
+			}
+
+			destinationPosition = rowStart + _logicalScreenWidth;
+			rows--;
+		}
+
+		return written;
+	}
+
+	if (kind != 0x0F)
+		return 0;
+
+	uint16 width = READ_LE_UINT16(_animFrameHeader + 10);
+	uint16 height = READ_LE_UINT16(_animFrameHeader + 12);
+	for (uint16 row = 0; row < height && sourcePosition < sourceSize &&
+			destinationPosition < _animFrameBuffer.size(); row++) {
+		sourcePosition++;
+		uint16 remaining = width;
+		while (remaining && sourcePosition < sourceSize && destinationPosition < _animFrameBuffer.size()) {
+			byte control = source[sourcePosition++];
+			uint16 count = control;
+			if (control & 0x80) {
+				count = 0x100 - control;
+				count = MIN(count, remaining);
+				count = MIN<uint32>(count, sourceSize - sourcePosition);
+				count = MIN<uint32>(count, _animFrameBuffer.size() - destinationPosition);
+				memcpy(&_animFrameBuffer[destinationPosition], source + sourcePosition, count);
+				sourcePosition += count;
+			} else {
+				if (sourcePosition >= sourceSize)
+					return written;
+
+				count = MIN(count, remaining);
+				count = MIN<uint32>(count, _animFrameBuffer.size() - destinationPosition);
+				memset(&_animFrameBuffer[destinationPosition], source[sourcePosition++], count);
+			}
+
+			destinationPosition += count;
+			written += count;
+			remaining -= count;
+		}
+
+		if (width < _logicalScreenWidth)
+			destinationPosition += _logicalScreenWidth - width;
+	}
+
+	return written;
+}
+
+void ComfyEngine::animFileTickCommands() {
+	if (!_usesAnimFile || !_animActive || _animVocCounterMode)
+		return;
+
+	_animVocTargetCounter++;
+	if (_animVocTargetCounter == 1 && _midiPlyrDriver) {
+		_midiPlyrDriver->setVocCounter(0);
+		_midiPlyrDriver->setIncreaseVocCounter(1);
+	}
+
+	bool ended = false;
+	bool frameReady = false;
+	while (!ended && !frameReady) {
+		uint32 headerSize = _animPantherFormat ? 8 : 4;
+		if (_animPosition > _animFileData.size() || headerSize > _animFileData.size() - _animPosition) {
+			animFileShutdown(false);
+			return;
+		}
+
+		byte *header = &_animFileData[_animPosition];
+		uint16 command = READ_LE_UINT16(header);
+		uint32 commandSize = _animPantherFormat ? READ_LE_UINT32(header + 2) : READ_LE_UINT16(header + 2);
+		if (commandSize < headerSize || commandSize > _animFileData.size() - _animPosition) {
+			animFileShutdown(false);
+			return;
+		}
+
+		uint32 payloadSize = commandSize - headerSize;
+		byte *payload = header + headerSize;
+		_animPosition += commandSize;
+		if (command == kAnimCommandEnd) {
+			ended = true;
+		} else if (command == kAnimCommandStoreFrameBytes) {
+			uint32 oldSize = _animFrameStorage.size();
+			_animFrameStorage.resize(oldSize + payloadSize);
+			if (payloadSize)
+				memcpy(&_animFrameStorage[oldSize], payload, payloadSize);
+		} else if (command == kAnimCommandDirtyRect) {
+			_animPendingDirtyRectSize = payloadSize;
+			memset(_animPendingDirtyRect, 0, sizeof(_animPendingDirtyRect));
+			memcpy(_animPendingDirtyRect, payload, MIN<uint32>(payloadSize, sizeof(_animPendingDirtyRect)));
+		} else if (command == kAnimCommandFrame) {
+			if (payloadSize) {
+				if (_animPantherFormat)
+					animDecodePanther(payload, payloadSize);
+				else
+					animDecompressRle(payload, payloadSize, &_animFrameBuffer[0], _animFrameBuffer.size());
+			}
+
+			if (_framebufPtr && !_animFrameBuffer.empty()) {
+				memcpy(_framebufPtr, &_animFrameBuffer[0], MIN<uint32>(framebufferBytes(), _animFrameBuffer.size()));
+				renderSetDirty();
+			}
+
+			frameReady = true;
+		} else {
+			animFileShutdown(false);
+			return;
+		}
+	}
+
+	if (ended)
+		animFileShutdown(false);
+}
+
+bool ComfyEngine::animFrameShouldWaitForVoc() {
+	return _animActive && !_animVocCounterMode && _animVocTargetCounter && _animVocClockHz && _midiPlyrDriver;
+}
+
+int16 ComfyEngine::animFrameVocCounterDelta() {
+	if (!animFrameShouldWaitForVoc())
+		return 0;
+
+	int32 expected = (int32(int16(_animVocTargetCounter)) * 100) / int16(_animVocClockHz);
+	return int16(uint16(_midiPlyrDriver->getVocCounter()) - uint16(expected));
+}
+
+bool ComfyEngine::animFrameShouldDraw(uint16 phase) {
+	if (!animFrameShouldWaitForVoc())
+		return true;
+
+	int16 baseStep = 100 / int16(_animVocClockHz);
+	int16 threshold = phase == 1 ? baseStep / 2 : baseStep;
+	int16 delta = animFrameVocCounterDelta();
+	int16 adjustedDelta = int16((phase == 1 ? int16(delta + _animVocDeltaA) : delta) + _animVocBaseCounter);
+	return adjustedDelta <= threshold;
+}
+
+void ComfyEngine::animFrameRecordVocCounter(uint16 phase) {
+	if (!animFrameShouldWaitForVoc())
+		return;
+
+	uint32 counter = _midiPlyrDriver->getVocCounter();
+	if (phase == 1) {
+		_animVocCounterStartA = counter;
+	} else if (phase == 2) {
+		_animVocDeltaA = uint16(counter - _animVocCounterStartA);
+	} else if (phase == 3) {
+		_animVocCounterStartB = counter;
+	} else if (phase == 4) {
+		_animVocBaseCounter = uint16(counter - _animVocCounterStartB);
+	}
+}
+
+void ComfyEngine::animFrameWaitForVocCounter() {
+	if (!animFrameShouldWaitForVoc())
+		return;
+
+	for (uint guard = 0; guard < 1000; guard++) {
+		if (animFrameVocCounterDelta() >= -int16(_animVocBaseCounter))
+			break;
+
+		soundAdvanceTick();
+		processEvents();
+		if (shouldQuit())
+			break;
+
+		_system->delayMillis(1);
+	}
+}
+
+} // End of namespace Comfy
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index b6e1fa653bd..5e6dfede9bf 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -73,10 +73,21 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Eng
 	_scenePoolEvictCursor(0), _activeSceneCount(0), _sceneEntryCount(0), _sceneEntryFrameSize(0),
 	_numObjects(0), _numFrames(0), _numSprites(0), _envNumSprites(0), _midiFileMode(0), _mirrorMode(false),
 	_currentActor(0), _pendingScene(0), _musicEventMask(0), _musicEventFlag(0), _musicEnabled(false),
-	_usesWcomfy99ScriptOps(false), _actorDestroyedCurrent(false), _lastKey(0xFFFF),
+	_usesWcomfy99ScriptOps(false), _wcomfy99FeatureWordCount(0), _wcomfy99Sensitivity(0),
+	_wcomfy99RecordHostEnabled(false), _wcomfy99SubsystemWord(0), _wcomfy99MixedHostFirstWord(0),
+	_wcomfy99MixedHostSecondWord(0), _wcomfy99MixedHostThirdWord(0), _wcomfy99MixedHostFourthWord(0),
+	_wcomfy99HostWordA(0), _wcomfy99HostWordB(0), _wcomfy99WaveVolumePercent(0),
+	_wcomfy99WaveLeftPercent(0), _wcomfy99WaveRightPercent(0), _wcomfy99MixerVolumePercent(0),
+	_wcomfy99MixerAltPercent(0), _wcomfy99RangeHostStart(0), _wcomfy99RangeHostEnd(0),
+	_wcomfy99RangeHostCount(0), _actorDestroyedCurrent(false), _lastKey(0xFFFF),
 	_soundEventIndex(0), _soundEventMaximum(0), _soundEventSubIndex(0xFFFF),
 	_soundEventPreviousSubIndex(0xFFFF), _midiInstanceTrackBase(1),
 	_soundTileStride(0), _soundSampleRate(0x2B11), _soundNextCue(0), _soundCompressed(false), _soundPaused(false),
+	_animPosition(0), _animPendingDirtyRectSize(0), _animCurrentIndex(0),
+	_animCurrentActorSceneHandle(0), _animCurrentFrameKey(0), _animVocCounterMode(0),
+	_animVocClockHz(0), _animVocTargetCounter(0), _animVocBaseCounter(0), _animVocDeltaA(0),
+	_animVocCounterStartA(0), _animVocCounterStartB(0), _animIndexLoaded(false),
+	_animPantherFormat(false), _animActive(false),
 	_exprStackTop(0), _scriptFault(false),
 	_gameInitialized(false), _videoInitialized(false),
 	_timerInitialized(false), _lptKeyboardInitialized(false), _mainLoopRunning(false) {
@@ -90,6 +101,9 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Eng
 	memset(&_midiEvents, 0, sizeof(_midiEvents));
 	memset(&_midiTracks, 0, sizeof(_midiTracks));
 	memset(_midiChannels, 0, sizeof(_midiChannels));
+	memset(_wcomfy99FeatureWords, 0, sizeof(_wcomfy99FeatureWords));
+	memset(_animFrameHeader, 0, sizeof(_animFrameHeader));
+	memset(_animPendingDirtyRect, 0, sizeof(_animPendingDirtyRect));
 	g_engine = this;
 }
 
@@ -316,9 +330,6 @@ void ComfyEngine::midiTrackTickAndRemove() {
 	}
 }
 
-void ComfyEngine::animFileTickCommands() {
-}
-
 void ComfyEngine::sceneTickEvent() {
 	soundAdvanceTick();
 	if (_soundEventIndex == _soundEventMaximum)
@@ -416,7 +427,10 @@ void ComfyEngine::renderFrame() {
 	uint16 rootIndex = _sceneHandles.size() > 1 ? _sceneHandles[1] : 0;
 	if (!rootIndex || actorDraw(rootIndex, 0, 0)) {
 		paletteVsyncFlip();
+		animFrameWaitForVocCounter();
+		animFrameRecordVocCounter(3);
 		videoPresentFrame();
+		animFrameRecordVocCounter(4);
 	} else {
 		renderSetDirty();
 	}
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 093749bbeef..1e71a24def5 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -67,6 +67,12 @@
 #define COMFY_MIDI_CHANNEL_COUNT 2
 #define COMFY_MIDI_TRACK_ENTRY_CAPACITY 5
 #define COMFY_ANIM_FRAME_CAPACITY 10
+#define COMFY_ANMFILE_HEADER_BYTES 16
+#define COMFY_ANMFILE_MAGIC 0x4143
+#define COMFY_ANMFILE_PANTHER_MAGIC 0x4643
+#define COMFY_ANMFRAME_MAGIC 0x4E41
+#define COMFY_ANMFRAME_PANTHER_MAGIC 0x4C46
+#define COMFY_ANMFRAME_BYTES 0xFA00
 
 namespace Comfy {
 
@@ -332,6 +338,25 @@ private:
 	byte _musicEventFlag;
 	bool _musicEnabled;
 	bool _usesWcomfy99ScriptOps;
+	uint16 _wcomfy99FeatureWords[16];
+	byte _wcomfy99FeatureWordCount;
+	uint16 _wcomfy99Sensitivity;
+	bool _wcomfy99RecordHostEnabled;
+	uint16 _wcomfy99SubsystemWord;
+	uint16 _wcomfy99MixedHostFirstWord;
+	uint16 _wcomfy99MixedHostSecondWord;
+	uint16 _wcomfy99MixedHostThirdWord;
+	uint16 _wcomfy99MixedHostFourthWord;
+	uint16 _wcomfy99HostWordA;
+	uint16 _wcomfy99HostWordB;
+	uint16 _wcomfy99WaveVolumePercent;
+	uint16 _wcomfy99WaveLeftPercent;
+	uint16 _wcomfy99WaveRightPercent;
+	uint16 _wcomfy99MixerVolumePercent;
+	uint16 _wcomfy99MixerAltPercent;
+	uint16 _wcomfy99RangeHostStart;
+	uint16 _wcomfy99RangeHostEnd;
+	uint16 _wcomfy99RangeHostCount;
 	bool _actorDestroyedCurrent;
 	uint16 _lastKey;
 	VocQueueEntry _vocQueue[COMFY_VOC_QUEUE_CAPACITY];
@@ -352,6 +377,27 @@ private:
 	uint _soundNextCue;
 	bool _soundCompressed;
 	bool _soundPaused;
+	Common::Array<byte> _animFileData;
+	Common::Array<uint32> _animIndexTable;
+	Common::Array<byte> _animFrameBuffer;
+	Common::Array<byte> _animFrameStorage;
+	byte _animFrameHeader[COMFY_ANMFILE_HEADER_BYTES];
+	byte _animPendingDirtyRect[16];
+	uint32 _animPosition;
+	uint16 _animPendingDirtyRectSize;
+	uint16 _animCurrentIndex;
+	uint16 _animCurrentActorSceneHandle;
+	uint16 _animCurrentFrameKey;
+	byte _animVocCounterMode;
+	uint16 _animVocClockHz;
+	uint16 _animVocTargetCounter;
+	uint16 _animVocBaseCounter;
+	uint16 _animVocDeltaA;
+	uint32 _animVocCounterStartA;
+	uint32 _animVocCounterStartB;
+	bool _animIndexLoaded;
+	bool _animPantherFormat;
+	bool _animActive;
 	uint16 _exprStack[COMFY_EXPR_STACK_CAPACITY];
 	uint16 _exprStackTop;
 	bool _scriptFault;
@@ -486,6 +532,16 @@ private:
 	uint16 timerTick();
 	void midiTrackTickAndRemove();
 	void animFileTickCommands();
+	bool animFileOpen();
+	void animFileShutdown(bool closeFile);
+	void animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 actorSceneHandle);
+	uint32 animDecompressRle(const byte *source, uint32 sourceSize, byte *destination, uint32 destinationSize);
+	uint32 animDecodePanther(const byte *source, uint32 sourceSize);
+	bool animFrameShouldWaitForVoc();
+	bool animFrameShouldDraw(uint16 phase);
+	int16 animFrameVocCounterDelta();
+	void animFrameRecordVocCounter(uint16 phase);
+	void animFrameWaitForVocCounter();
 	void sceneTickEvent();
 	void midiPollChannels(uint16 ticks);
 	void midiInitInstance();
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index 2a669e66a5d..eced14250d1 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -299,6 +299,11 @@ bool ComfyEngine::assetsLoad() {
 		return false;
 	}
 
+	if (_usesAnimFile && !animFileOpen()) {
+		assetsUnload();
+		return false;
+	}
+
 	_stringTable.resize(_stringCount + 1);
 	memset(&_stringTable[0], 0, _stringTable.size() * sizeof(uint16));
 	_sceneHandles.resize(_sceneCount + 1);
@@ -361,6 +366,25 @@ bool ComfyEngine::assetsLoad() {
 	_sceneEntryFrameSize = 0;
 	Common::ScopedPtr<Common::SeekableReadStream> message(pathFOpen(Common::Path("MESSAGE"), true));
 	_usesWcomfy99ScriptOps = bool(message);
+	_wcomfy99FeatureWordCount = 0;
+	_wcomfy99Sensitivity = ConfMan.hasKey("SENSITIVITY") ? ConfMan.getInt("SENSITIVITY") : 0;
+	_wcomfy99RecordHostEnabled = false;
+	_wcomfy99SubsystemWord = 0;
+	_wcomfy99MixedHostFirstWord = 0;
+	_wcomfy99MixedHostSecondWord = 0;
+	_wcomfy99MixedHostThirdWord = 0;
+	_wcomfy99MixedHostFourthWord = 0;
+	_wcomfy99HostWordA = 0;
+	_wcomfy99HostWordB = 0;
+	_wcomfy99WaveVolumePercent = 0;
+	_wcomfy99WaveLeftPercent = 0;
+	_wcomfy99WaveRightPercent = 0;
+	_wcomfy99MixerVolumePercent = 0;
+	_wcomfy99MixerAltPercent = 0;
+	_wcomfy99RangeHostStart = 0;
+	_wcomfy99RangeHostEnd = 0;
+	_wcomfy99RangeHostCount = 0;
+	memset(_wcomfy99FeatureWords, 0, sizeof(_wcomfy99FeatureWords));
 	_pendingScene = 0;
 	_musicEventMask = 0;
 	_musicEventFlag = 0;
@@ -376,6 +400,7 @@ bool ComfyEngine::assetsLoad() {
 }
 
 void ComfyEngine::assetsUnload() {
+	animFileShutdown(true);
 	soundShutdown();
 	keyBitFree();
 	_comfyObjData.clear();
@@ -397,6 +422,25 @@ void ComfyEngine::assetsUnload() {
 	memset(_sceneEntryOffsets, 0, sizeof(_sceneEntryOffsets));
 	memset(_actorPcTable, 0, sizeof(_actorPcTable));
 	_usesWcomfy99ScriptOps = false;
+	_wcomfy99FeatureWordCount = 0;
+	_wcomfy99Sensitivity = 0;
+	_wcomfy99RecordHostEnabled = false;
+	_wcomfy99SubsystemWord = 0;
+	_wcomfy99MixedHostFirstWord = 0;
+	_wcomfy99MixedHostSecondWord = 0;
+	_wcomfy99MixedHostThirdWord = 0;
+	_wcomfy99MixedHostFourthWord = 0;
+	_wcomfy99HostWordA = 0;
+	_wcomfy99HostWordB = 0;
+	_wcomfy99WaveVolumePercent = 0;
+	_wcomfy99WaveLeftPercent = 0;
+	_wcomfy99WaveRightPercent = 0;
+	_wcomfy99MixerVolumePercent = 0;
+	_wcomfy99MixerAltPercent = 0;
+	_wcomfy99RangeHostStart = 0;
+	_wcomfy99RangeHostEnd = 0;
+	_wcomfy99RangeHostCount = 0;
+	memset(_wcomfy99FeatureWords, 0, sizeof(_wcomfy99FeatureWords));
 	_pendingScene = 0;
 	_currentActor = 0;
 	_scriptFault = false;
diff --git a/engines/comfy/module.mk b/engines/comfy/module.mk
index 4545007f2c9..ba53f6b79b1 100644
--- a/engines/comfy/module.mk
+++ b/engines/comfy/module.mk
@@ -2,6 +2,7 @@ MODULE := engines/comfy
 
 MODULE_OBJS = \
 	actor.o \
+	anim_file.o \
 	comfy.o \
 	comfy_keyboard_ui.o \
 	console.o \
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index f69d986eba5..0bc0e053f98 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -351,6 +351,9 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			midiStopAndRemove(channel);
 		} else if (subop == 6 && channel < COMFY_MIDI_CHANNEL_COUNT) {
 			midiStopAndFireKeys(channel);
+		} else if ((subop == 7 || subop == 8) && _engineVersion == kEngineVersion3 &&
+				channel < COMFY_MIDI_CHANNEL_COUNT && _midiPlyrDriver) {
+			_midiPlyrDriver->musicSetLoop(subop == 7 ? 1 : 0, channel);
 		}
 
 		return kScriptContinue;
@@ -554,8 +557,18 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 	if (opcode == 0x30 && _usesAnimFile) {
 		byte subop = scriptReadByte(pc++);
-		if (subop == 1)
+		if (subop == 0) {
+			animFileShutdown(true);
+		} else if (subop == 1) {
+			uint16 animIndex = scriptReadWord(pc);
+			uint16 frameKey = scriptReadWord(pc + 2);
 			pc += 4;
+			animFileLoadFrame(animIndex, frameKey, actorReadWord(actor, kActorSceneHandle));
+		} else if (subop == 2) {
+			_animVocCounterMode = 1;
+		} else if (subop == 3) {
+			_animVocCounterMode = 0;
+		}
 
 		return kScriptContinue;
 	}
@@ -563,7 +576,12 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	if (opcode >= 0x31 && opcode <= 0x36 && _usesWcomfy99ScriptOps) {
 		if (opcode == 0x31) {
 			uint16 count = scriptReadStringIndex(pc);
-			pc += 2 + uint32(count) * 2;
+			pc += 2;
+			_wcomfy99FeatureWordCount = MIN<uint16>(count, ARRAYSIZE(_wcomfy99FeatureWords));
+			for (uint i = 0; i < _wcomfy99FeatureWordCount; i++)
+				_wcomfy99FeatureWords[i] = scriptReadWord(pc + i * 2);
+
+			pc += uint32(count) * 2;
 		} else if (opcode == 0x32) {
 			pc += 4;
 		} else if (opcode == 0x33) {
@@ -585,6 +603,10 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 				_stringTable[value] = ConfMan.hasKey(key) ? ConfMan.getInt(key) : 0;
 			} else if (subop == 1) {
 				ConfMan.setInt(key, value);
+				if (key.equalsIgnoreCase("SENSITIVITY"))
+					_wcomfy99Sensitivity = value;
+
+				ConfMan.flushToDisk();
 			} else if (subop == 4) {
 				if (ConfMan.hasKey(key) && !ConfMan.get(key).equalsIgnoreCase("?????"))
 					keyBitSet(value);
@@ -602,11 +624,31 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 					(Common::isAlpha(last) ? (Common::isUpper(last) ? 0x04 : 0x08) : 0x40);
 			}
 		} else if (opcode == 0x35) {
-			pc++;
+			byte subop = scriptReadByte(pc++);
+			if (subop == 2)
+				_wcomfy99SubsystemWord = 0;
 		} else {
 			byte subop = scriptReadByte(pc++);
-			if (subop >= 3 && subop <= 5)
-				pc += uint32(subop - 1) * 2;
+			if (subop == 1 || subop == 3)
+				_wcomfy99RecordHostEnabled = true;
+			else if (subop == 2)
+				_wcomfy99RecordHostEnabled = false;
+
+			if (subop >= 3 && subop <= 5) {
+				_wcomfy99MixedHostFirstWord = scriptReadWord(pc);
+				_wcomfy99MixedHostSecondWord = scriptReadWord(pc + 2);
+				pc += 4;
+				_wcomfy99RecordHostEnabled = true;
+				if (subop != 3) {
+					_wcomfy99MixedHostThirdWord = scriptReadWord(pc);
+					pc += 2;
+				}
+
+				if (subop == 5) {
+					_wcomfy99MixedHostFourthWord = scriptReadWord(pc);
+					pc += 2;
+				}
+			}
 		}
 
 		return kScriptContinue;
@@ -615,9 +657,31 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	if ((opcode == 0x46 || opcode == 0x47) && _usesWcomfy99ScriptOps) {
 		if (opcode == 0x46) {
 			byte subop = scriptReadByte(pc++);
-			if (subop >= 1 && subop <= 8)
+			if (subop >= 1 && subop <= 8) {
+				uint16 argument = scriptReadWord(pc);
 				pc += 2;
+				uint16 percentage = argument == 0x00FF ? 0x00FF :
+					(int16(argument) < 0 ? 0 : MIN<uint16>(argument, 100));
+				if (subop == 1)
+					_wcomfy99HostWordA = argument;
+				else if (subop == 2 && percentage != 0x00FF)
+					_wcomfy99WaveVolumePercent = percentage;
+				else if (subop == 3 && percentage != 0x00FF)
+					_wcomfy99WaveLeftPercent = percentage;
+				else if (subop == 4 && percentage != 0x00FF)
+					_wcomfy99WaveRightPercent = percentage;
+				else if ((subop == 5 || subop == 6) && percentage != 0x00FF)
+					_wcomfy99MixerVolumePercent = percentage;
+				else if (subop == 7 && percentage != 0x00FF)
+					_wcomfy99MixerAltPercent = percentage;
+				else if (subop == 8)
+					_wcomfy99HostWordB = argument;
+			}
 		} else {
+			_wcomfy99RangeHostStart = scriptReadWord(pc);
+			_wcomfy99RangeHostEnd = scriptReadWord(pc + 2);
+			_wcomfy99RangeHostCount = _wcomfy99RangeHostEnd >= _wcomfy99RangeHostStart ?
+				_wcomfy99RangeHostEnd - _wcomfy99RangeHostStart + 1 : 0;
 			pc += 4;
 		}
 
@@ -774,8 +838,16 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 				condition = argument < _sceneHandles.size() && _sceneHandles[argument];
 			else if (kind == 2)
 				condition = _inputDeviceMode == 1;
-			else if (kind == 14 && argument <= 4)
-				condition = _inputDeviceMode == argument;
+			else if (kind == 14) {
+				if (argument <= 4) {
+					condition = _inputDeviceMode == argument;
+				} else if (argument == 20) {
+					condition = _wcomfy99RecordHostEnabled;
+				} else if (argument == 30) {
+					Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(Common::Path("comfy.htm"), true));
+					condition = bool(stream);
+				}
+			}
 		} else if (kind == 1) {
 			uint16 scene = scriptReadWord(pc);
 			condition = scene < _sceneHandles.size() && _sceneHandles[scene];


Commit: e776afd164cbbdb51a9b9a97b92f691743b27930
    https://github.com/scummvm/scummvm/commit/e776afd164cbbdb51a9b9a97b92f691743b27930
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Fix INTRO movies detection and game names

Changed paths:
    engines/comfy/detection_tables.h
    engines/comfy/game.cpp


diff --git a/engines/comfy/detection_tables.h b/engines/comfy/detection_tables.h
index 9e64ae2672a..f841e83f957 100644
--- a/engines/comfy/detection_tables.h
+++ b/engines/comfy/detection_tables.h
@@ -23,12 +23,12 @@ namespace Comfy {
 
 const PlainGameDescriptor comfyGames[] = {
 	{ "comfyland", "ComfyLand" },
-	{ "boo", "Didi and Boo" },
-	{ "first", "The First Step" },
-	{ "match", "A Purrfect Match" },
-	{ "colors", "Colorful Adventures" },
-	{ "concert", "The Great Concert" },
-	{ "friends", "Playground of Friends" },
+	{ "boo", "Comfy Touch-n-See: Didi and Boo" },
+	{ "first", "Comfy Touch-n-See: The First Step" },
+	{ "match", "Comfy Max: A Purrfect Match" },
+	{ "colors", "Comfy: Colorful Adventures - The Missing Bone" },
+	{ "concert", "Comfy: The Great Concert" },
+	{ "friends", "Comfy: Playground of Friends" },
 	{ "panther", "The Pink Panther's House of Numbers" },
 	{ 0, 0 }
 };
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index eced14250d1..a2462fa6052 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -88,16 +88,16 @@ void ComfyEngine::gameConfigInit() {
 		_introDirectory = Common::Path("MINTRO");
 	} else if (!strcmp(_gameDescription->gameId, "colors")) {
 		_gameDirectory = Common::Path("COLORS");
-		_introDirectory = Common::Path("FINTRO");
+		_introDirectory = Common::Path("INTRO");
 	} else if (!strcmp(_gameDescription->gameId, "concert")) {
 		_gameDirectory = Common::Path("CONCERT");
 		_introDirectory = Common::Path("INTRO");
 	} else if (!strcmp(_gameDescription->gameId, "friends")) {
 		_gameDirectory = Common::Path("FRIENDS");
-		_introDirectory = Common::Path("FINTRO");
+		_introDirectory = Common::Path("INTRO");
 	} else if (!strcmp(_gameDescription->gameId, "panther")) {
 		_gameDirectory = Common::Path("PANTHER");
-		_introDirectory = Common::Path("MINTRO");
+		_introDirectory.clear(); // No intro
 	}
 
 	findLanguageDirectories();


Commit: c248786db882e8efdf248de9dff89262a784dcf4
    https://github.com/scummvm/scummvm/commit/c248786db882e8efdf248de9dff89262a784dcf4
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Make ImGui keyboard non resizeable

Changed paths:
    engines/comfy/comfy_keyboard_ui.cpp


diff --git a/engines/comfy/comfy_keyboard_ui.cpp b/engines/comfy/comfy_keyboard_ui.cpp
index 45663bafc9a..0ba66a06c99 100644
--- a/engines/comfy/comfy_keyboard_ui.cpp
+++ b/engines/comfy/comfy_keyboard_ui.cpp
@@ -151,9 +151,10 @@ void onImGuiRender() {
 
 	ImGui::GetIO().ConfigFlags &= ~(ImGuiConfigFlags_NoMouseCursorChange | ImGuiConfigFlags_NoMouse);
 
-	ImGui::SetNextWindowSize(ImVec2(780, 520), ImGuiCond_FirstUseEver);
+	ImGui::SetNextWindowPos(ImVec2(8, 8), ImGuiCond_FirstUseEver);
+	ImGui::SetNextWindowSize(ImVec2(740, 440), ImGuiCond_FirstUseEver);
 
-	if (ImGui::Begin("Comfy Keyboard", &_state->_visible)) {
+	if (ImGui::Begin("Comfy Keyboard", &_state->_visible, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoResize)) {
 		ImU32 shell = keyboardColor(232, 228, 208);
 		ImU32 red = keyboardColor(199, 31, 27);
 		ImU32 handset = keyboardColor(211, 48, 38);


Commit: 16cebcb434ce27f22edc820dfef1f77214925f62
    https://github.com/scummvm/scummvm/commit/16cebcb434ce27f22edc820dfef1f77214925f62
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Refactoring

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/anim_file.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/expr.cpp
    engines/comfy/game.cpp
    engines/comfy/midi.cpp
    engines/comfy/scene.cpp
    engines/comfy/script_vm.cpp
    engines/comfy/sound.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index 08ede5b9773..821259fa05b 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -137,21 +137,142 @@ bool ComfyEngine::spriteDecompressTile(SpriteResource &sprite, const byte *sourc
 	return outputPos == outputSize;
 }
 
-bool ComfyEngine::spriteLoad(int16 spriteId) {
-	if (spriteId <= 0 || uint16(spriteId) >= _spriteResources.size())
-		return false;
+void ComfyEngine::spriteInvalidateHostCache(SpriteResource &sprite) {
+	sprite.loaded = false;
+	sprite.pixels.clear();
+}
+
+void ComfyEngine::objHdrReadFromXms(byte *destination, uint32 base, uint16 size, uint16 row) {
+	if (!destination)
+		return;
+
+	uint32 offset = base + uint32(size) * row;
+	if (offset >= _headerXmsData.size())
+		return;
+
+	uint16 copySize = MIN<uint32>(size, _headerXmsData.size() - offset);
+	memcpy(destination, &_headerXmsData[offset], copySize);
+}
+
+void ComfyEngine::objHdrRead(SpriteObjectHeader &destination, uint16 index) {
+	byte raw[0x11];
+	memset(raw, 0, sizeof(raw));
+	objHdrReadFromXms(raw, _headerXmsObjectTableBase, sizeof(raw), index);
+	destination.fileOffset = READ_LE_UINT32(raw);
+	destination.dataSize = READ_LE_UINT16(raw + 0x04);
+	destination.width = READ_LE_UINT16(raw + 0x06);
+	destination.height = READ_LE_UINT16(raw + 0x08);
+	destination.hotspotX = int16(READ_LE_UINT16(raw + 0x0A));
+	destination.hotspotY = int16(READ_LE_UINT16(raw + 0x0C));
+	destination.reserved = raw[0x0E];
+	destination.tiledSize = READ_LE_UINT16(raw + 0x0F);
+}
+
+void ComfyEngine::scenePoolEvict() {
+	if (_scenePoolEvictCursor >= _scenePoolData.size())
+		return;
+
+	byte *entry = &_scenePoolData[_scenePoolEvictCursor];
+	int16 id = int16(READ_LE_UINT16(entry));
+	uint16 slotSize = READ_LE_UINT16(entry + 2);
+	if (id > 0 && uint16(id) < _spriteResources.size()) {
+		spriteInvalidateHostCache(_spriteResources[id]);
+		_objectCacheEntries[id].slotSize = 0xFFFF;
+	} else if (id < 0) {
+		uint16 frameId = uint16(-id);
+		if (_frameSpriteResource.id == id)
+			spriteInvalidateHostCache(_frameSpriteResource);
+
+		if (frameId < _frameCacheEntries.size())
+			_frameCacheEntries[frameId].slotSize = 0xFFFF;
+	}
+
+	_scenePoolEvictCursor += slotSize;
+	if (_scenePoolEvictCursor < _scenePoolData.size() &&
+			READ_LE_UINT16(&_scenePoolData[_scenePoolEvictCursor]) == 0x8000)
+		_scenePoolEvictCursor = 0;
+}
+
+void ComfyEngine::scenePoolReserveSlot(uint32 size) {
+	if (!_scenePoolSize || size >= _scenePoolSize)
+		return;
+
+	for (;;) {
+		if (_scenePoolCursor >= _scenePoolEvictCursor) {
+			uint32 tailFree = _scenePoolSize - _scenePoolCursor;
+			if (tailFree > size)
+				return;
+
+			if (!_scenePoolEvictCursor)
+				scenePoolEvict();
+			else
+				_scenePoolCursor = 0;
+		} else {
+			uint32 gapFree = _scenePoolEvictCursor - _scenePoolCursor;
+			if (gapFree > size)
+				return;
+
+			scenePoolEvict();
+		}
+	}
+}
+
+void ComfyEngine::spriteCache(int16 spriteId) {
+	if (!spriteId)
+		return;
+
+	if (spriteId < 0) {
+		uint16 frameId = uint16(-spriteId);
+		uint32 fileOffset = uint32(frameId - 1) * COMFY_TILE_SIZE;
+		if (fileOffset >= _picDataSize || fileOffset >= _comfyObjData.size())
+			return;
+
+		uint32 size = MIN<uint32>(COMFY_TILE_SIZE,
+			MIN<uint32>(_picDataSize - fileOffset, _comfyObjData.size() - fileOffset));
+		uint16 slotSize = uint16(size + (size & 1) + 0x0C);
+		scenePoolReserveSlot(uint32(slotSize) + 2);
+		if (_scenePoolCursor > _scenePoolData.size() || slotSize > _scenePoolData.size() - _scenePoolCursor)
+			return;
+
+		byte *entryData = &_scenePoolData[_scenePoolCursor];
+		WRITE_LE_UINT16(entryData, uint16(spriteId));
+		WRITE_LE_UINT16(entryData + 2, slotSize);
+		memcpy(entryData + 0x0C, &_comfyObjData[fileOffset], size);
+		_frameSpriteResource.id = spriteId;
+		memset(&_frameSpriteResource.header, 0, sizeof(_frameSpriteResource.header));
+		_frameSpriteResource.header.dataSize = size;
+		_frameSpriteResource.header.tiledSize = size;
+		_frameSpriteResource.pixels.resize(size);
+		memcpy(&_frameSpriteResource.pixels[0], entryData + 0x0C, size);
+		_frameSpriteResource.loaded = true;
+		if (frameId < _frameCacheEntries.size()) {
+			SpriteCacheEntry &entry = _frameCacheEntries[frameId];
+			entry.poolOffset = _scenePoolCursor;
+			entry.slotSize = slotSize;
+		}
+
+		_scenePoolCursor += slotSize;
+		if (_scenePoolCursor < _scenePoolData.size())
+			WRITE_LE_UINT16(&_scenePoolData[_scenePoolCursor], 0x8000);
+
+		return;
+	}
+
+	if (uint16(spriteId) >= _spriteResources.size())
+		return;
 
 	SpriteResource &sprite = _spriteResources[spriteId];
 	if (sprite.loaded && _objectCacheEntries[spriteId].slotSize != 0xFFFF)
-		return true;
+		return;
 
-	sprite.loaded = false;
-	sprite.pixels.clear();
+	spriteInvalidateHostCache(sprite);
 
-	SpriteObjectHeader &header = sprite.header;
+	SpriteObjectHeader header;
+	objHdrRead(header, spriteId);
+	sprite.header = header;
 	if (!header.dataSize || header.fileOffset > _picFileData.size() ||
 			header.dataSize > _picFileData.size() - header.fileOffset)
-		return false;
+		return;
 
 	byte *source = &_picFileData[header.fileOffset];
 	if (header.width == _logicalScreenWidth && header.height == _logicalScreenHeight) {
@@ -159,61 +280,53 @@ bool ComfyEngine::spriteLoad(int16 spriteId) {
 		memcpy(&sprite.pixels[0], source, header.dataSize);
 	} else if (!spriteDecompressTile(sprite, source, header.dataSize)) {
 		sprite.pixels.clear();
-		return false;
+		return;
 	}
 
-	sprite.loaded = true;
-	uint32 slotSize = (sprite.pixels.size() + (sprite.pixels.size() & 1) + 0x0C);
-	if (slotSize <= _scenePoolData.size()) {
-		if (_scenePoolCursor > _scenePoolData.size() - slotSize) {
-			_scenePoolCursor = 0;
-			_scenePoolEvictCursor = 0;
-			for (uint i = 0; i < _objectCacheEntries.size(); i++)
-				_objectCacheEntries[i].slotSize = 0xFFFF;
-
-			for (uint i = 0; i < _frameCacheEntries.size(); i++)
-				_frameCacheEntries[i].slotSize = 0xFFFF;
-		}
+	uint16 payloadSize = sprite.pixels.size() + (sprite.pixels.size() & 1);
+	uint16 slotSize = payloadSize + 0x0C;
+	scenePoolReserveSlot(uint32(slotSize) + 2);
+	if (_scenePoolCursor > _scenePoolData.size() || slotSize > _scenePoolData.size() - _scenePoolCursor)
+		return;
 
-		SpriteCacheEntry &entry = _objectCacheEntries[spriteId];
-		entry.poolOffset = _scenePoolCursor;
-		entry.slotSize = slotSize;
-		WRITE_LE_UINT16(&_scenePoolData[_scenePoolCursor], uint16(spriteId));
-		WRITE_LE_UINT16(&_scenePoolData[_scenePoolCursor + 2], slotSize);
-		memcpy(&_scenePoolData[_scenePoolCursor + 0x0C], &sprite.pixels[0], sprite.pixels.size());
-		_scenePoolCursor += slotSize;
-	}
+	byte *entryData = &_scenePoolData[_scenePoolCursor];
+	WRITE_LE_UINT16(entryData, uint16(spriteId));
+	WRITE_LE_UINT16(entryData + 2, slotSize);
+	WRITE_LE_UINT16(entryData + 4, header.width);
+	WRITE_LE_UINT16(entryData + 6, header.height);
+	WRITE_LE_UINT16(entryData + 8, uint16(header.hotspotX));
+	WRITE_LE_UINT16(entryData + 0x0A, uint16(header.hotspotY));
+	memcpy(entryData + 0x0C, &sprite.pixels[0], sprite.pixels.size());
+	SpriteCacheEntry &entry = _objectCacheEntries[spriteId];
+	entry.poolOffset = _scenePoolCursor;
+	entry.slotSize = slotSize;
+	_scenePoolCursor += slotSize;
+	if (_scenePoolCursor < _scenePoolData.size())
+		WRITE_LE_UINT16(&_scenePoolData[_scenePoolCursor], 0x8000);
 
-	return true;
+	sprite.loaded = true;
 }
 
-ComfyEngine::SpriteResource *ComfyEngine::spriteGet(int16 spriteId) {
-	if (spriteId > 0)
-		return spriteLoad(spriteId) ? &_spriteResources[spriteId] : nullptr;
+ComfyEngine::SpriteResource *ComfyEngine::spriteGetPtr(int16 spriteId) {
+	if (spriteId > 0) {
+		if (uint16(spriteId) >= _spriteResources.size())
+			return nullptr;
 
-	if (!spriteId)
-		return nullptr;
+		if (_objectCacheEntries[spriteId].slotSize == 0xFFFF)
+			spriteCache(spriteId);
+
+		return &_spriteResources[spriteId];
+	}
 
-	uint16 tile = uint16(-spriteId) - 1;
-	uint32 offset = uint32(tile) * COMFY_TILE_SIZE;
-	if (offset >= _picDataSize || offset >= _comfyObjData.size())
+	if (!spriteId)
 		return nullptr;
 
-	uint32 size = MIN<uint32>(COMFY_TILE_SIZE, MIN<uint32>(_picDataSize - offset, _comfyObjData.size() - offset));
-	_frameSpriteResource.id = spriteId;
-	memset(&_frameSpriteResource.header, 0, sizeof(_frameSpriteResource.header));
-	_frameSpriteResource.header.dataSize = size;
-	_frameSpriteResource.header.tiledSize = size;
-	_frameSpriteResource.pixels.resize(size);
-	memcpy(&_frameSpriteResource.pixels[0], &_comfyObjData[offset], size);
-	_frameSpriteResource.loaded = true;
-	if (uint16(-spriteId) < _frameCacheEntries.size()) {
-		SpriteCacheEntry &entry = _frameCacheEntries[-spriteId];
-		entry.poolOffset = offset;
-		entry.slotSize = uint16(size + (size & 1) + 0x0C);
-	}
+	uint16 frameId = uint16(-spriteId);
+	if (frameId >= _frameCacheEntries.size() || _frameCacheEntries[frameId].slotSize == 0xFFFF ||
+			!_frameSpriteResource.loaded || _frameSpriteResource.id != spriteId)
+		spriteCache(spriteId);
 
-	return &_frameSpriteResource;
+	return _frameSpriteResource.loaded && _frameSpriteResource.id == spriteId ? &_frameSpriteResource : nullptr;
 }
 
 void ComfyEngine::spriteBlitRle(const byte *source, uint32 sourceSize) {
@@ -248,7 +361,7 @@ void ComfyEngine::spriteBlitRle(const byte *source, uint32 sourceSize) {
 }
 
 void ComfyEngine::spriteBlitClipped(int16 spriteId, int16 x, int16 y) {
-	SpriteResource *loadedSprite = spriteGet(spriteId);
+	SpriteResource *loadedSprite = spriteGetPtr(spriteId);
 	if (!loadedSprite)
 		return;
 
@@ -302,7 +415,7 @@ void ComfyEngine::spriteBlitClipped(int16 spriteId, int16 x, int16 y) {
 	renderSetDirty();
 }
 
-uint32 ComfyEngine::actorReadDword(Actor &actor, uint offset) {
+uint32 ComfyEngine::actorReadU32(Actor &actor, uint offset) {
 	if (offset + 4 > COMFY_ACTOR_SIZE) {
 		_scriptFault = true;
 		return 0;
@@ -311,7 +424,7 @@ uint32 ComfyEngine::actorReadDword(Actor &actor, uint offset) {
 	return READ_LE_UINT32(actor.raw + offset);
 }
 
-uint16 ComfyEngine::actorReadWord(Actor &actor, uint offset) {
+uint16 ComfyEngine::actorReadU16(Actor &actor, uint offset) {
 	if (offset + 2 > COMFY_ACTOR_SIZE) {
 		_scriptFault = true;
 		return 0;
@@ -320,7 +433,7 @@ uint16 ComfyEngine::actorReadWord(Actor &actor, uint offset) {
 	return READ_LE_UINT16(actor.raw + offset);
 }
 
-byte ComfyEngine::actorReadByte(Actor &actor, uint offset) {
+byte ComfyEngine::actorReadU8(Actor &actor, uint offset) {
 	if (offset >= COMFY_ACTOR_SIZE) {
 		_scriptFault = true;
 		return 0;
@@ -329,21 +442,21 @@ byte ComfyEngine::actorReadByte(Actor &actor, uint offset) {
 	return actor.raw[offset];
 }
 
-void ComfyEngine::actorWriteDword(Actor &actor, uint offset, uint32 value) {
+void ComfyEngine::actorWriteU32(Actor &actor, uint offset, uint32 value) {
 	if (offset + 4 <= COMFY_ACTOR_SIZE)
 		WRITE_LE_UINT32(actor.raw + offset, value);
 	else
 		_scriptFault = true;
 }
 
-void ComfyEngine::actorWriteWord(Actor &actor, uint offset, uint16 value) {
+void ComfyEngine::actorWriteU16(Actor &actor, uint offset, uint16 value) {
 	if (offset + 2 <= COMFY_ACTOR_SIZE)
 		WRITE_LE_UINT16(actor.raw + offset, value);
 	else
 		_scriptFault = true;
 }
 
-void ComfyEngine::actorWriteByte(Actor &actor, uint offset, byte value) {
+void ComfyEngine::actorWriteU8(Actor &actor, uint offset, byte value) {
 	if (offset < COMFY_ACTOR_SIZE)
 		actor.raw[offset] = value;
 	else
@@ -354,6 +467,21 @@ ComfyEngine::Actor *ComfyEngine::actorGet(uint16 actorIndex) {
 	return actorIndex < _actors.size() ? &_actors[actorIndex] : nullptr;
 }
 
+ComfyEngine::Actor *ComfyEngine::rootActor() {
+	return !_actors.empty() ? &_actors[0] : nullptr;
+}
+
+void ComfyEngine::actorSetFrame(int16 frame) {
+	Actor *root = rootActor();
+	if (root)
+		actorWriteU32(*root, kActorSpriteSelector, uint32(int32(frame)));
+}
+
+uint16 ComfyEngine::actorGetFrame() {
+	Actor *root = rootActor();
+	return root ? uint16(actorReadU32(*root, kActorSpriteSelector)) : 0;
+}
+
 ComfyEngine::Actor *ComfyEngine::actorResolve(uint16 sceneOrActor, uint16 fallbackActor) {
 	if (!sceneOrActor)
 		return actorGet(fallbackActor);
@@ -363,14 +491,14 @@ ComfyEngine::Actor *ComfyEngine::actorResolve(uint16 sceneOrActor, uint16 fallba
 
 uint16 ComfyEngine::actorAllocate(uint16 sceneSlot) {
 	Actor *root = actorGet(0);
-	uint16 actorIndex = root ? actorReadWord(*root, kActorNextLink) : 0;
+	uint16 actorIndex = root ? actorReadU16(*root, kActorNextLink) : 0;
 	if (!actorIndex || sceneSlot >= _sceneHandles.size())
 		return 0;
 
 	Actor *actor = actorGet(actorIndex);
-	actorWriteWord(*root, kActorNextLink, actorReadWord(*actor, kActorNextLink));
+	actorWriteU16(*root, kActorNextLink, actorReadU16(*actor, kActorNextLink));
 	_sceneHandles[sceneSlot] = actorIndex;
-	actorWriteWord(*actor, kActorSceneHandle, sceneSlot);
+	actorWriteU16(*actor, kActorSceneHandle, sceneSlot);
 	return actorIndex;
 }
 
@@ -384,10 +512,10 @@ void ComfyEngine::actorFree(uint16 sceneSlot) {
 		return;
 
 	Actor *root = actorGet(0);
-	actorWriteWord(*actor, kActorNextLink, root ? actorReadWord(*root, kActorNextLink) : 0);
-	actorWriteWord(*actor, kActorSceneHandle, 0);
+	actorWriteU16(*actor, kActorNextLink, root ? actorReadU16(*root, kActorNextLink) : 0);
+	actorWriteU16(*actor, kActorSceneHandle, 0);
 	if (root)
-		actorWriteWord(*root, kActorNextLink, actorIndex);
+		actorWriteU16(*root, kActorNextLink, actorIndex);
 	_sceneHandles[sceneSlot] = 0;
 }
 
@@ -397,17 +525,17 @@ void ComfyEngine::actorInsertChild(uint16 childIndex, uint16 parentIndex) {
 	if (!child || !parent)
 		return;
 
-	uint16 tail = actorReadWord(*parent, kActorChildTail);
+	uint16 tail = actorReadU16(*parent, kActorChildTail);
 	if (tail) {
-		actorWriteWord(*actorGet(tail), kActorNextLink, childIndex);
-		actorWriteWord(*child, kActorPrevLink, tail);
+		actorWriteU16(*actorGet(tail), kActorNextLink, childIndex);
+		actorWriteU16(*child, kActorPrevLink, tail);
 	} else {
-		actorWriteWord(*parent, kActorChildHead, childIndex);
-		actorWriteWord(*child, kActorPrevLink, 0);
+		actorWriteU16(*parent, kActorChildHead, childIndex);
+		actorWriteU16(*child, kActorPrevLink, 0);
 	}
 
-	actorWriteWord(*child, kActorNextLink, 0);
-	actorWriteWord(*parent, kActorChildTail, childIndex);
+	actorWriteU16(*child, kActorNextLink, 0);
+	actorWriteU16(*parent, kActorChildTail, childIndex);
 }
 
 void ComfyEngine::actorInsertSibling(uint16 actorIndex, uint16 ownerIndex) {
@@ -416,13 +544,13 @@ void ComfyEngine::actorInsertSibling(uint16 actorIndex, uint16 ownerIndex) {
 	if (!actor || !owner)
 		return;
 
-	uint16 head = actorReadWord(*owner, kActorSiblingHead);
+	uint16 head = actorReadU16(*owner, kActorSiblingHead);
 	if (head)
-		actorWriteWord(*actorGet(head), kActorPrevLink, actorIndex);
+		actorWriteU16(*actorGet(head), kActorPrevLink, actorIndex);
 
-	actorWriteWord(*actor, kActorNextLink, head);
-	actorWriteWord(*actor, kActorPrevLink, 0);
-	actorWriteWord(*owner, kActorSiblingHead, actorIndex);
+	actorWriteU16(*actor, kActorNextLink, head);
+	actorWriteU16(*actor, kActorPrevLink, 0);
+	actorWriteU16(*owner, kActorSiblingHead, actorIndex);
 }
 
 void ComfyEngine::actorUnlink(uint16 actorIndex) {
@@ -430,23 +558,23 @@ void ComfyEngine::actorUnlink(uint16 actorIndex) {
 	if (!actor)
 		return;
 
-	Actor *parent = actorGet(actorReadWord(*actor, kActorParent));
+	Actor *parent = actorGet(actorReadU16(*actor, kActorParent));
 	if (!parent)
 		return;
 
-	uint16 next = actorReadWord(*actor, kActorNextLink);
-	uint16 previous = actorReadWord(*actor, kActorPrevLink);
+	uint16 next = actorReadU16(*actor, kActorNextLink);
+	uint16 previous = actorReadU16(*actor, kActorPrevLink);
 	if (next)
-		actorWriteWord(*actorGet(next), kActorPrevLink, previous);
-	else if (actorReadWord(*parent, kActorChildTail) == actorIndex)
-		actorWriteWord(*parent, kActorChildTail, previous);
+		actorWriteU16(*actorGet(next), kActorPrevLink, previous);
+	else if (actorReadU16(*parent, kActorChildTail) == actorIndex)
+		actorWriteU16(*parent, kActorChildTail, previous);
 
 	if (previous)
-		actorWriteWord(*actorGet(previous), kActorNextLink, next);
-	else if (actorReadWord(*parent, kActorSiblingHead) == actorIndex)
-		actorWriteWord(*parent, kActorSiblingHead, next);
+		actorWriteU16(*actorGet(previous), kActorNextLink, next);
+	else if (actorReadU16(*parent, kActorSiblingHead) == actorIndex)
+		actorWriteU16(*parent, kActorSiblingHead, next);
 	else
-		actorWriteWord(*parent, kActorChildHead, next);
+		actorWriteU16(*parent, kActorChildHead, next);
 }
 
 uint16 ComfyEngine::actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible, byte active,
@@ -456,19 +584,19 @@ uint16 ComfyEngine::actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible,
 	if (!actor)
 		return 8;
 
-	actorWriteWord(*actor, kActorSceneHandle, sceneSlot);
-	actorWriteByte(*actor, kActorVisible, visible);
-	actorWriteByte(*actor, kActorActive, active);
-	actorWriteDword(*actor, kActorCurrentPc, pc);
-	actorWriteDword(*actor, kActorResetPc, pc);
-	actorWriteDword(*actor, kActorXFixed, uint32(int32(x) * 0x1000));
-	actorWriteDword(*actor, kActorYFixed, uint32(int32(y) * 0x1000));
-	actorWriteDword(*actor, kActorSpriteSelector, uint32(int32(sprite)));
-	actorWriteByte(*actor, kActorDirty, 1);
+	actorWriteU16(*actor, kActorSceneHandle, sceneSlot);
+	actorWriteU8(*actor, kActorVisible, visible);
+	actorWriteU8(*actor, kActorActive, active);
+	actorWriteU32(*actor, kActorCurrentPc, pc);
+	actorWriteU32(*actor, kActorResetPc, pc);
+	actorWriteU32(*actor, kActorXFixed, uint32(int32(x) * 0x1000));
+	actorWriteU32(*actor, kActorYFixed, uint32(int32(y) * 0x1000));
+	actorWriteU32(*actor, kActorSpriteSelector, uint32(int32(sprite)));
+	actorWriteU8(*actor, kActorDirty, 1);
 
 	if (parentSlot) {
 		uint16 parentIndex = parentSlot < _sceneHandles.size() ? _sceneHandles[parentSlot] : 0;
-		actorWriteWord(*actor, kActorParent, parentIndex);
+		actorWriteU16(*actor, kActorParent, parentIndex);
 		if (insertAsChild)
 			actorInsertChild(actorIndex, parentIndex);
 		else
@@ -479,7 +607,7 @@ uint16 ComfyEngine::actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible,
 }
 
 void ComfyEngine::actorSetPc(Actor &actor, uint32 pc) {
-	uint32 previous = actorReadDword(actor, kActorCallPc);
+	uint32 previous = actorReadU32(actor, kActorCallPc);
 	uint32 packed = pc;
 	if (previous) {
 		byte entry = _actorPcTable[0] >> 24;
@@ -498,14 +626,14 @@ void ComfyEngine::actorSetPc(Actor &actor, uint32 pc) {
 		packed = (uint32(entry) << 24) | (pc & 0x00FFFFFF);
 	}
 
-	actorWriteDword(actor, kActorCallPc, packed);
+	actorWriteU32(actor, kActorCallPc, packed);
 }
 
 uint32 ComfyEngine::actorPopPc(Actor &actor) {
-	uint32 packed = actorReadDword(actor, kActorCallPc);
+	uint32 packed = actorReadU32(actor, kActorCallPc);
 	byte entry = packed >> 24;
 	if (entry && entry < COMFY_ACTOR_PC_TABLE_COUNT) {
-		actorWriteDword(actor, kActorCallPc, _actorPcTable[entry]);
+		actorWriteU32(actor, kActorCallPc, _actorPcTable[entry]);
 		_actorPcTable[entry] = _actorPcTable[0];
 		_actorPcTable[0] = uint32(entry) << 24;
 		if (_sceneActorPcOffset + sizeof(_actorPcTable) <= _sceneMemoryBlock.size()) {
@@ -513,14 +641,14 @@ uint32 ComfyEngine::actorPopPc(Actor &actor) {
 			WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneActorPcOffset + entry * 4], _actorPcTable[entry]);
 		}
 	} else {
-		actorWriteDword(actor, kActorCallPc, 0);
+		actorWriteU32(actor, kActorCallPc, 0);
 	}
 
 	return packed & 0x00FFFFFF;
 }
 
 void ComfyEngine::actorFreePcChain(Actor &actor) {
-	byte first = actorReadDword(actor, kActorCallPc) >> 24;
+	byte first = actorReadU32(actor, kActorCallPc) >> 24;
 	byte entry = first;
 	while (entry && entry < COMFY_ACTOR_PC_TABLE_COUNT) {
 		byte next = _actorPcTable[entry] >> 24;
@@ -537,7 +665,7 @@ void ComfyEngine::actorFreePcChain(Actor &actor) {
 		entry = next;
 	}
 
-	actorWriteDword(actor, kActorCallPc, 0);
+	actorWriteU32(actor, kActorCallPc, 0);
 }
 
 void ComfyEngine::actorFreeTree(uint16 actorIndex) {
@@ -545,23 +673,23 @@ void ComfyEngine::actorFreeTree(uint16 actorIndex) {
 	if (!actor)
 		return;
 
-	uint16 child = actorReadWord(*actor, kActorSiblingHead);
+	uint16 child = actorReadU16(*actor, kActorSiblingHead);
 	while (child) {
 		Actor *childActor = actorGet(child);
-		uint16 next = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		actorFreeTree(child);
 		child = next;
 	}
 
-	child = actorReadWord(*actor, kActorChildHead);
+	child = actorReadU16(*actor, kActorChildHead);
 	while (child) {
 		Actor *childActor = actorGet(child);
-		uint16 next = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		actorFreeTree(child);
 		child = next;
 	}
 
-	uint16 sceneSlot = actorReadWord(*actor, kActorSceneHandle);
+	uint16 sceneSlot = actorReadU16(*actor, kActorSceneHandle);
 	actorFreePcChain(*actor);
 	actorFree(sceneSlot);
 }
@@ -571,27 +699,27 @@ void ComfyEngine::actorClearDirtyTree(uint16 actorIndex) {
 	if (!actor)
 		return;
 
-	actorWriteByte(*actor, kActorDirty, 0);
-	uint16 child = actorReadWord(*actor, kActorSiblingHead);
+	actorWriteU8(*actor, kActorDirty, 0);
+	uint16 child = actorReadU16(*actor, kActorSiblingHead);
 	while (child) {
 		Actor *childActor = actorGet(child);
-		uint16 next = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		actorClearDirtyTree(child);
 		child = next;
 	}
 
-	child = actorReadWord(*actor, kActorChildHead);
+	child = actorReadU16(*actor, kActorChildHead);
 	while (child) {
 		Actor *childActor = actorGet(child);
-		uint16 next = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		actorClearDirtyTree(child);
 		child = next;
 	}
 }
 
-void ComfyEngine::actorSetAllDirty() {
+void ComfyEngine::actorSetAllVisible() {
 	for (uint i = 0; i + 1 < _actors.size(); i++)
-		actorWriteByte(_actors[i], kActorDirty, 1);
+		actorWriteU8(_actors[i], kActorDirty, 1);
 }
 
 bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
@@ -603,28 +731,28 @@ bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
 	_currentActor = actorIndex;
 	_actorDestroyedCurrent = false;
 	if (_stringTable.size() > 3) {
-		_stringTable[2] = actorReadWord(*actor, kActorStringRef);
-		_stringTable[3] = actorReadWord(*actor, kActorStringRef + 2);
+		_stringTable[2] = actorReadU16(*actor, kActorStringRef);
+		_stringTable[3] = actorReadU16(*actor, kActorStringRef + 2);
 	}
 
-	uint16 triggerKey = actorReadWord(*actor, kActorTriggerKey);
+	uint16 triggerKey = actorReadU16(*actor, kActorTriggerKey);
 	if (triggerKey && keyBitTest(triggerKey)) {
-		byte triggerFlags = actorReadByte(*actor, kActorTriggerFlags);
+		byte triggerFlags = actorReadU8(*actor, kActorTriggerFlags);
 		if (triggerFlags & 1)
-			actorSetPc(*actor, actorReadDword(*actor, kActorCurrentPc));
+			actorSetPc(*actor, actorReadU32(*actor, kActorCurrentPc));
 
 		if (triggerFlags & 4)
 			keyBitClear(triggerKey);
 
 		if (triggerFlags & 2)
-			actorWriteWord(*actor, kActorTriggerKey, 0);
+			actorWriteU16(*actor, kActorTriggerKey, 0);
 
-		actorWriteWord(*actor, kActorWaitTarget, 0);
-		actorWriteWord(*actor, kActorWaitAccum, 0);
-		actorWriteDword(*actor, kActorCurrentPc, actorReadDword(*actor, kActorTriggerPc));
+		actorWriteU16(*actor, kActorWaitTarget, 0);
+		actorWriteU16(*actor, kActorWaitAccum, 0);
+		actorWriteU32(*actor, kActorCurrentPc, actorReadU32(*actor, kActorTriggerPc));
 	}
 
-	int16 moveTicks = actorReadWord(*actor, kActorMoveTicks);
+	int16 moveTicks = actorReadU16(*actor, kActorMoveTicks);
 	if (moveTicks) {
 		int16 stepTicks = int16(uint16(_timerCurrent + _timer0 + _timer1 + _timer2 + 2)) / 4;
 		if (stepTicks > 20)
@@ -632,43 +760,43 @@ bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
 
 		if (moveTicks < stepTicks) {
 			moveTicks = stepTicks;
-			actorWriteWord(*actor, kActorMoveTicks, moveTicks);
+			actorWriteU16(*actor, kActorMoveTicks, moveTicks);
 		}
 
-		int32 moveDx = actorReadDword(*actor, kActorMoveDx);
-		int32 moveDy = actorReadDword(*actor, kActorMoveDy);
+		int32 moveDx = actorReadU32(*actor, kActorMoveDx);
+		int32 moveDy = actorReadU32(*actor, kActorMoveDy);
 		int32 stepDx = (int32(stepTicks) * moveDx) / moveTicks;
 		int32 stepDy = (int32(stepTicks) * moveDy) / moveTicks;
-		actorWriteDword(*actor, kActorXFixed, actorReadDword(*actor, kActorXFixed) + stepDx);
-		actorWriteDword(*actor, kActorYFixed, actorReadDword(*actor, kActorYFixed) + stepDy);
-		actorWriteDword(*actor, kActorMoveDx, moveDx - stepDx);
-		actorWriteDword(*actor, kActorMoveDy, moveDy - stepDy);
+		actorWriteU32(*actor, kActorXFixed, actorReadU32(*actor, kActorXFixed) + stepDx);
+		actorWriteU32(*actor, kActorYFixed, actorReadU32(*actor, kActorYFixed) + stepDy);
+		actorWriteU32(*actor, kActorMoveDx, moveDx - stepDx);
+		actorWriteU32(*actor, kActorMoveDy, moveDy - stepDy);
 		moveTicks -= stepTicks;
 		if (moveTicks < 0)
 			moveTicks = 0;
 
-		actorWriteWord(*actor, kActorMoveTicks, moveTicks);
-		if (moveTicks && actorReadByte(*actor, kActorBlockingMove)) {
+		actorWriteU16(*actor, kActorMoveTicks, moveTicks);
+		if (moveTicks && actorReadU8(*actor, kActorBlockingMove)) {
 			if (_stringTable.size() > 3) {
-				actorWriteWord(*actor, kActorStringRef, _stringTable[2]);
-				actorWriteWord(*actor, kActorStringRef + 2, _stringTable[3]);
+				actorWriteU16(*actor, kActorStringRef, _stringTable[2]);
+				actorWriteU16(*actor, kActorStringRef + 2, _stringTable[3]);
 			}
 
 			descendChildren = true;
 			return false;
 		}
 
-		if (!moveTicks && actorReadWord(*actor, kActorCompletionKey))
-			keyBitSet(actorReadWord(*actor, kActorCompletionKey));
+		if (!moveTicks && actorReadU16(*actor, kActorCompletionKey))
+			keyBitSet(actorReadU16(*actor, kActorCompletionKey));
 	}
 
-	int16 waitTarget = actorReadWord(*actor, kActorWaitTarget);
+	int16 waitTarget = actorReadU16(*actor, kActorWaitTarget);
 	if (waitTarget) {
 		if (waitTarget > _timerCurrent) {
-			actorWriteWord(*actor, kActorWaitTarget, waitTarget - _timerCurrent);
+			actorWriteU16(*actor, kActorWaitTarget, waitTarget - _timerCurrent);
 			if (_stringTable.size() > 3) {
-				actorWriteWord(*actor, kActorStringRef, _stringTable[2]);
-				actorWriteWord(*actor, kActorStringRef + 2, _stringTable[3]);
+				actorWriteU16(*actor, kActorStringRef, _stringTable[2]);
+				actorWriteU16(*actor, kActorStringRef + 2, _stringTable[3]);
 			}
 
 			descendChildren = true;
@@ -676,21 +804,21 @@ bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
 		}
 
 		int16 elapsed = _timerCurrent - waitTarget;
-		actorWriteWord(*actor, kActorWaitAccum, actorReadWord(*actor, kActorWaitAccum) + elapsed);
-		actorWriteWord(*actor, kActorWaitTarget, 0);
+		actorWriteU16(*actor, kActorWaitAccum, actorReadU16(*actor, kActorWaitAccum) + elapsed);
+		actorWriteU16(*actor, kActorWaitTarget, 0);
 	}
 
-	uint32 pc = actorReadDword(*actor, kActorCurrentPc);
+	uint32 pc = actorReadU32(*actor, kActorCurrentPc);
 	for (;;) {
 		ScriptDispatchStatus status = scriptStep(*actor, pc);
 		if (status == kScriptContinue) {
-			actorWriteDword(*actor, kActorCurrentPc, pc);
+			actorWriteU32(*actor, kActorCurrentPc, pc);
 			continue;
 		}
 
 		if (status == kScriptYield && _stringTable.size() > 3) {
-			actorWriteWord(*actor, kActorStringRef, _stringTable[2]);
-			actorWriteWord(*actor, kActorStringRef + 2, _stringTable[3]);
+			actorWriteU16(*actor, kActorStringRef, _stringTable[2]);
+			actorWriteU16(*actor, kActorStringRef + 2, _stringTable[3]);
 		}
 
 		descendChildren = status == kScriptYield && !_actorDestroyedCurrent;
@@ -698,7 +826,7 @@ bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
 	}
 }
 
-bool ComfyEngine::actorTickTreeInternal(uint16 actorIndex) {
+bool ComfyEngine::actorTickTree(uint16 actorIndex) {
 	if (_pendingScene)
 		return false;
 
@@ -706,7 +834,7 @@ bool ComfyEngine::actorTickTreeInternal(uint16 actorIndex) {
 	if (!actor)
 		return false;
 
-	if (!actorReadByte(*actor, kActorActive)) {
+	if (!actorReadU8(*actor, kActorActive)) {
 		actorClearDirtyTree(actorIndex);
 		return false;
 	}
@@ -717,27 +845,27 @@ bool ComfyEngine::actorTickTreeInternal(uint16 actorIndex) {
 	if (stopBranch || !descendChildren || !actor)
 		return stopBranch;
 
-	uint16 child = actorReadWord(*actor, kActorSiblingHead);
+	uint16 child = actorReadU16(*actor, kActorSiblingHead);
 	while (child) {
 		Actor *childActor = actorGet(child);
-		uint16 savedNext = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
-		if (actorTickTreeInternal(child))
+		uint16 savedNext = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
+		if (actorTickTree(child))
 			child = savedNext;
 		else {
 			childActor = actorGet(child);
-			child = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+			child = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		}
 	}
 
-	child = actorReadWord(*actor, kActorChildHead);
+	child = actorReadU16(*actor, kActorChildHead);
 	while (child) {
 		Actor *childActor = actorGet(child);
-		uint16 savedNext = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
-		if (actorTickTreeInternal(child))
+		uint16 savedNext = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
+		if (actorTickTree(child))
 			child = savedNext;
 		else {
 			childActor = actorGet(child);
-			child = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+			child = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		}
 	}
 
@@ -748,7 +876,7 @@ void ComfyEngine::actorDrawList(uint16 actorIndex, int16 x, int16 y) {
 	while (actorIndex) {
 		actorDraw(actorIndex, x, y);
 		Actor *actor = actorGet(actorIndex);
-		actorIndex = actor ? actorReadWord(*actor, kActorNextLink) : 0;
+		actorIndex = actor ? actorReadU16(*actor, kActorNextLink) : 0;
 	}
 }
 
@@ -775,7 +903,7 @@ void ComfyEngine::actorDrawScripted(uint16 actorIndex, uint32 selector, int16 x,
 		}
 
 		if (spriteId) {
-			SpriteResource *sprite = spriteGet(int16(spriteId));
+			SpriteResource *sprite = spriteGetPtr(int16(spriteId));
 			if (sprite)
 				spriteBlitClipped(int16(spriteId), x + dx - sprite->header.hotspotX, y + dy - sprite->header.hotspotY);
 		}
@@ -786,20 +914,20 @@ void ComfyEngine::actorDrawScripted(uint16 actorIndex, uint32 selector, int16 x,
 
 ComfyEngine::VideoRectRecord ComfyEngine::actorReadCachedRect(Actor &actor) {
 	VideoRectRecord rect;
-	rect.left = actorReadWord(actor, kActorCachedRect);
-	rect.top = actorReadWord(actor, kActorCachedRect + 2);
-	rect.right = actorReadWord(actor, kActorCachedRect + 4);
-	rect.bottom = actorReadWord(actor, kActorCachedRect + 6);
-	rect.area = actorReadWord(actor, kActorCachedRect + 8);
+	rect.left = actorReadU16(actor, kActorCachedRect);
+	rect.top = actorReadU16(actor, kActorCachedRect + 2);
+	rect.right = actorReadU16(actor, kActorCachedRect + 4);
+	rect.bottom = actorReadU16(actor, kActorCachedRect + 6);
+	rect.area = actorReadU16(actor, kActorCachedRect + 8);
 	return rect;
 }
 
 void ComfyEngine::actorWriteCachedRect(Actor &actor, VideoRectRecord rect) {
-	actorWriteWord(actor, kActorCachedRect, rect.left);
-	actorWriteWord(actor, kActorCachedRect + 2, rect.top);
-	actorWriteWord(actor, kActorCachedRect + 4, rect.right);
-	actorWriteWord(actor, kActorCachedRect + 6, rect.bottom);
-	actorWriteWord(actor, kActorCachedRect + 8, rect.area);
+	actorWriteU16(actor, kActorCachedRect, rect.left);
+	actorWriteU16(actor, kActorCachedRect + 2, rect.top);
+	actorWriteU16(actor, kActorCachedRect + 4, rect.right);
+	actorWriteU16(actor, kActorCachedRect + 6, rect.bottom);
+	actorWriteU16(actor, kActorCachedRect + 8, rect.area);
 }
 
 void ComfyEngine::actorInvalidateDrawTree(uint16 actorIndex) {
@@ -811,22 +939,22 @@ void ComfyEngine::actorInvalidateDrawTree(uint16 actorIndex) {
 	if (rect.area)
 		videoFindBestMode(rect);
 
-	actorWriteByte(*actor, kActorCachedVisible, 0);
-	actorWriteDword(*actor, kActorCachedSprite, 0);
+	actorWriteU8(*actor, kActorCachedVisible, 0);
+	actorWriteU32(*actor, kActorCachedSprite, 0);
 	VideoRectRecord empty = {0, 0, 0, 0, 0};
 	actorWriteCachedRect(*actor, empty);
-	uint16 child = actorReadWord(*actor, kActorSiblingHead);
+	uint16 child = actorReadU16(*actor, kActorSiblingHead);
 	while (child) {
 		Actor *childActor = actorGet(child);
-		uint16 next = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		actorInvalidateDrawTree(child);
 		child = next;
 	}
 
-	child = actorReadWord(*actor, kActorChildHead);
+	child = actorReadU16(*actor, kActorChildHead);
 	while (child) {
 		Actor *childActor = actorGet(child);
-		uint16 next = childActor ? actorReadWord(*childActor, kActorNextLink) : 0;
+		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		actorInvalidateDrawTree(child);
 		child = next;
 	}
@@ -840,12 +968,12 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 	if (!animFrameShouldDraw(1))
 		return false;
 
-	int16 drawX = int16(int32(actorReadDword(*actor, kActorXFixed)) >> 12) + x;
-	int16 drawY = int16(int32(actorReadDword(*actor, kActorYFixed)) >> 12) + y;
-	byte oldVisible = actorReadByte(*actor, kActorCachedVisible);
-	uint32 oldSelector = actorReadDword(*actor, kActorCachedSprite);
+	int16 drawX = int16(int32(actorReadU32(*actor, kActorXFixed)) >> 12) + x;
+	int16 drawY = int16(int32(actorReadU32(*actor, kActorYFixed)) >> 12) + y;
+	byte oldVisible = actorReadU8(*actor, kActorCachedVisible);
+	uint32 oldSelector = actorReadU32(*actor, kActorCachedSprite);
 	VideoRectRecord oldRect = actorReadCachedRect(*actor);
-	if (!actorReadByte(*actor, kActorVisible)) {
+	if (!actorReadU8(*actor, kActorVisible)) {
 		if (oldVisible)
 			actorInvalidateDrawTree(actorIndex);
 
@@ -853,13 +981,13 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 	}
 
 	animFrameRecordVocCounter(1);
-	actorDrawList(actorReadWord(*actor, kActorSiblingHead), drawX, drawY);
-	uint32 selector = actorReadDword(*actor, kActorSpriteSelector);
+	actorDrawList(actorReadU16(*actor, kActorSiblingHead), drawX, drawY);
+	uint32 selector = actorReadU32(*actor, kActorSpriteSelector);
 	VideoRectRecord newRect = {0, 0, 0, 0, 0};
 	if (selector & 0xFF000000) {
 		actorDrawScripted(actorIndex, selector, drawX, drawY);
 	} else if (selector) {
-		SpriteResource *sprite = spriteGet(int16(selector));
+		SpriteResource *sprite = spriteGetPtr(int16(selector));
 		if (sprite) {
 			newRect.left = drawX - sprite->header.hotspotX;
 			newRect.top = drawY - sprite->header.hotspotY;
@@ -873,7 +1001,7 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 
 	bool rectChanged = oldRect.left != newRect.left || oldRect.top != newRect.top ||
 		oldRect.right != newRect.right || oldRect.bottom != newRect.bottom || oldRect.area != newRect.area;
-	if (oldSelector != selector || oldVisible != actorReadByte(*actor, kActorVisible) || rectChanged) {
+	if (oldSelector != selector || oldVisible != actorReadU8(*actor, kActorVisible) || rectChanged) {
 		if (oldRect.area)
 			videoFindBestMode(oldRect);
 
@@ -881,10 +1009,10 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 			videoFindBestMode(newRect);
 	}
 
-	actorWriteByte(*actor, kActorCachedVisible, actorReadByte(*actor, kActorVisible));
-	actorWriteDword(*actor, kActorCachedSprite, selector);
+	actorWriteU8(*actor, kActorCachedVisible, actorReadU8(*actor, kActorVisible));
+	actorWriteU32(*actor, kActorCachedSprite, selector);
 	actorWriteCachedRect(*actor, newRect);
-	actorDrawList(actorReadWord(*actor, kActorChildHead), drawX, drawY);
+	actorDrawList(actorReadU16(*actor, kActorChildHead), drawX, drawY);
 	return animFrameShouldDraw(2);
 }
 
diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
index 348655374a2..d39addf6c7c 100644
--- a/engines/comfy/anim_file.cpp
+++ b/engines/comfy/anim_file.cpp
@@ -64,7 +64,7 @@ void ComfyEngine::animFileShutdown(bool closeFile) {
 		if (_animCurrentActorSceneHandle < _sceneHandles.size()) {
 			Actor *actor = actorGet(_sceneHandles[_animCurrentActorSceneHandle]);
 			if (actor)
-				actorWriteDword(*actor, kActorSpriteSelector, 0);
+				actorWriteU32(*actor, kActorSpriteSelector, 0);
 		}
 	}
 
@@ -118,7 +118,7 @@ void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 ac
 	if (actorSceneHandle < _sceneHandles.size()) {
 		Actor *actor = actorGet(_sceneHandles[actorSceneHandle]);
 		if (actor)
-			actorWriteDword(*actor, kActorSpriteSelector, 0x00FFFFFF);
+			actorWriteU32(*actor, kActorSpriteSelector, 0x00FFFFFF);
 	}
 
 	animFileTickCommands();
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 5e6dfede9bf..4a3341945c3 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -67,10 +67,13 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Eng
 	_toyKeyboardLatchedMask(0), _toyKeyboardHoldMask(0), _lptPrevScanState(0), _inputDeviceMode(0),
 	_keyboardUiInitialized(false), _keyboardUiVisible(true),
 	_stringCount(0), _sceneCount(0), _keyBitCount(0), _resourceHandleCount(0), _midiEntryCount(0),
-	_picDataSize(0), _usesAnimFile(false), _sceneOpen(false),
+	_picDataSize(0), _usesAnimFile(false), _sceneOpen(false), _sceneEntryListActive(false),
 	_sceneMidiInstanceOffset(0), _sceneEntryListOffset(0), _sceneActorPcOffset(0), _sceneStringTableOffset(0),
 	_sceneHandlesOffset(0), _sceneActorsOffset(0), _sceneKeyBitsOffset(0), _scenePoolCursor(0),
-	_scenePoolEvictCursor(0), _activeSceneCount(0), _sceneEntryCount(0), _sceneEntryFrameSize(0),
+	_scenePoolEvictCursor(0), _scenePoolSize(0), _headerXmsObjectTableBase(0),
+	_headerXmsObjectTableBytes(0), _headerXmsPicEntriesBase(0), _headerXmsPicEntriesBytes(0),
+	_headerXmsSoundHeadersBase(0), _headerXmsSoundHeadersBytes(0), _selectorRing(0),
+	_selectorPoolInitialized(false), _activeSceneCount(0), _sceneEntryCount(0), _sceneEntryFrameSize(0),
 	_numObjects(0), _numFrames(0), _numSprites(0), _envNumSprites(0), _midiFileMode(0), _mirrorMode(false),
 	_currentActor(0), _pendingScene(0), _musicEventMask(0), _musicEventFlag(0), _musicEnabled(false),
 	_usesWcomfy99ScriptOps(false), _wcomfy99FeatureWordCount(0), _wcomfy99Sensitivity(0),
@@ -101,6 +104,10 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Eng
 	memset(&_midiEvents, 0, sizeof(_midiEvents));
 	memset(&_midiTracks, 0, sizeof(_midiTracks));
 	memset(_midiChannels, 0, sizeof(_midiChannels));
+	_frameSpriteResource.id = 0;
+	memset(&_frameSpriteResource.header, 0, sizeof(_frameSpriteResource.header));
+	_frameSpriteResource.loaded = false;
+	memset(_selectorPoolEntries, 0, sizeof(_selectorPoolEntries));
 	memset(_wcomfy99FeatureWords, 0, sizeof(_wcomfy99FeatureWords));
 	memset(_animFrameHeader, 0, sizeof(_animFrameHeader));
 	memset(_animPendingDirtyRect, 0, sizeof(_animPendingDirtyRect));
@@ -122,10 +129,6 @@ Common::Error ComfyEngine::run() {
 	if (result.getCode() != Common::kNoError)
 		return result;
 
-	int saveSlot = ConfMan.getInt("save_slot");
-	if (saveSlot != -1)
-		(void)loadGameState(saveSlot);
-
 	uint16 currentScene = _language;
 	uint16 chooserScene = currentScene;
 	if (_multiLanguage && (ConfMan.getBool("force_language_setup") ||
@@ -155,9 +158,9 @@ Common::Error ComfyEngine::run() {
 			return Common::kNoGameDataFoundError;
 		}
 
-		if (currentScene == 0x63)
+		if (currentScene == 0x63) {
 			currentScene = sceneRun(chooserScene, _multiLanguage, false);
-		else {
+		} else {
 			chooserScene = currentScene;
 			currentScene = sceneRun(currentScene, _multiLanguage, false);
 		}
@@ -188,8 +191,7 @@ void ComfyEngine::gameShutdown() {
 	if (_lptKeyboardInitialized)
 		lptKeyboardShutdown();
 
-	sceneClose();
-	assetsUnload();
+	assetsUnload(1);
 
 	midiPlyrStop();
 
@@ -214,34 +216,16 @@ void ComfyEngine::timerShutdown() {
 	_timerInitialized = false;
 }
 
-void ComfyEngine::gameMainLoop() {
-	_mainLoopRunning = true;
-
-	while (_mainLoopRunning && !shouldQuit()) {
-		processEvents();
-		if (shouldQuit())
-			break;
-
-		gameMainLoopTick();
-	}
-
-	_mainLoopRunning = false;
-}
-
 uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
-	if (!assetsLoad() || !sceneOpen()) {
-		assetsUnload();
+	Common::Array<byte> sceneRunBuffer;
+	sceneRunBuffer.resize(0x10010);
+	memset(&sceneRunBuffer[0], 0, sceneRunBuffer.size());
+	if (!assetsLoad(0x4000, &sceneRunBuffer[0])) {
+		assetsUnload(0);
 		return 0;
 	}
 
-	keyBitSet(2);
-	lptKeyboardInit();
-	paletteVsyncFlip();
-	paletteVsyncFlip();
-	if (_activeSceneCount && _midiHandles.size() > 1)
-		_midiHandles[1] += sceneId;
-
-	gameMainLoop();
+	gameMainLoop(sceneId);
 	uint16 nextScene = 0;
 	if (checkNext && _activeSceneCount > 1 && _midiHandles.size() > 1)
 		nextScene = _midiHandles[1];
@@ -249,9 +233,8 @@ uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
 	if (nextScene == sceneId || int16(nextScene) <= 0 || int16(nextScene) >= 0x65)
 		nextScene = 0;
 
-	lptKeyboardShutdown();
-	sceneClose();
-	assetsUnload();
+	midiShutdown();
+	assetsUnload(0);
 	inputQueueReset();
 	if (!exitFlag && nextScene)
 		renderSetDirty();
@@ -299,24 +282,112 @@ void ComfyEngine::processEvents() {
 	}
 }
 
-void ComfyEngine::gameMainLoopTick() {
-	_pendingScene = 0;
-	_musicEventMask = 0;
-	_musicEventFlag = 0;
-	uint16 ticks = timerTick();
-
-	midiTrackTickAndRemove();
-	animFileTickCommands();
-	sceneTickEvent();
-	if (!_musicEnabled)
-		midiPollChannels(ticks);
-	paletteFadeStep(ticks);
-	lptKeyboardScanAndProcess();
-	actorTickTree();
-	renderFrame();
-	processInput();
-	processMusicEvents();
-	processSceneTransition();
+void ComfyEngine::gameMainLoop(uint16 argument) {
+	byte keepRunning = 1;
+	uint16 lastKey = 0xFFFF;
+	actorInit(1, 0, 1, 1, 0x14, 0, 0, 0, 1);
+	keyBitSet(2);
+	lptKeyboardInit();
+
+	uint16 rootIndex = _sceneHandles.size() > 1 ? _sceneHandles[1] : 0;
+	Actor *mainLoopActor = actorGet(rootIndex);
+	paletteLoadWithFade(0, 0);
+	paletteVsyncFlip();
+	paletteVsyncFlip();
+	if (_activeSceneCount && _midiHandles.size() > 1)
+		_midiHandles[1] += argument;
+
+	while (keepRunning && !shouldQuit()) {
+		_pendingScene = 0;
+		_musicEventMask = 0;
+		_musicEventFlag = 0;
+
+		uint16 ticks = timerTick();
+		midiTrackTickAndRemove();
+		animFileTickCommands();
+		sceneTickEvent();
+		if (!_musicEnabled)
+			midiPollChannels(ticks);
+
+		paletteFadeStep(ticks);
+		lptKeyboardScanAndProcess();
+		lptKeyToFlags(lastKey);
+		actorTickTree(rootIndex);
+
+		uint16 frame = actorGetFrame();
+		if (frame) {
+			SpriteResource *background = spriteGetPtr(int16(frame));
+			if (background && background->header.width == _logicalScreenWidth &&
+					background->header.height == _logicalScreenHeight && !background->pixels.empty()) {
+				spriteBlitRle(&background->pixels[0], background->pixels.size());
+				videoSetResolution();
+			} else {
+				uint16 clear = background && background->pixels.size() > 3 ? background->pixels[3] : 0;
+				framebufClear(clear);
+				videoSetResolution();
+			}
+		}
+
+		if (actorDraw(rootIndex, 0, 0)) {
+			paletteVsyncFlip();
+			animFrameWaitForVocCounter();
+			animFrameRecordVocCounter(3);
+			videoPresentFrame();
+			animFrameRecordVocCounter(4);
+		} else {
+			renderSetDirty();
+		}
+
+		lastKey = 0xFFFF;
+		if (inputQueueHasItems())
+			lastKey = lptReadKeyOrNext();
+
+		_lastKey = lastKey;
+		if (lastKey == 0x0101)
+			keepRunning = 0;
+		else if (mainLoopActor)
+			keepRunning = actorReadU8(*mainLoopActor, kActorActive);
+
+		processEvents();
+		if (shouldQuit())
+			keepRunning = 0;
+
+		if (_musicEventMask) {
+			if (_musicEventFlag)
+				vocQueuePlayAll();
+
+			if (vocQueueIsIdle() || _musicEnabled) {
+				uint16 track = 1;
+				for (;;) {
+					_musicEventMask = uint16(int16(_musicEventMask) >> 1);
+					if (!_musicEventMask)
+						break;
+
+					if (_musicEventMask & 1)
+						envConvToXms(&_sceneMemoryBlock[_sceneMidiInstanceOffset], track);
+
+					track++;
+				}
+			}
+		}
+
+		keyBitClear(0x42);
+		if (_pendingScene) {
+			sceneStartWithMusic(_pendingScene);
+			if (!_musicEnabled)
+				vocQueuePlayAll();
+
+			keyBitSet(0x42);
+		} else {
+			actorSetAllVisible();
+		}
+	}
+
+	if (_sceneHandles.size() > 1 && _sceneHandles[1])
+		actorFree(1);
+
+	lptKeyboardShutdown();
+	sceneBlockPackRuntimeState();
 }
 
 void ComfyEngine::midiTrackTickAndRemove() {
@@ -403,112 +474,6 @@ void ComfyEngine::midiPollChannels(uint16 ticks) {
 	}
 }
 
-void ComfyEngine::actorTickTree() {
-	if (_sceneHandles.size() > 1 && _sceneHandles[1])
-		actorTickTreeInternal(_sceneHandles[1]);
-
-	scenePackRuntimeState();
-}
-
-void ComfyEngine::renderFrame() {
-	Actor *root = actorGet(0);
-	uint16 frame = root ? actorReadDword(*root, kActorSpriteSelector) : 0;
-	if (frame) {
-		SpriteResource *background = spriteGet(int16(frame));
-		if (background && background->header.width == _logicalScreenWidth &&
-				background->header.height == _logicalScreenHeight && !background->pixels.empty()) {
-			spriteBlitRle(&background->pixels[0], background->pixels.size());
-		} else {
-			uint16 clear = background && background->pixels.size() > 3 ? background->pixels[3] : 0;
-			framebufClear(clear);
-		}
-	}
-
-	uint16 rootIndex = _sceneHandles.size() > 1 ? _sceneHandles[1] : 0;
-	if (!rootIndex || actorDraw(rootIndex, 0, 0)) {
-		paletteVsyncFlip();
-		animFrameWaitForVocCounter();
-		animFrameRecordVocCounter(3);
-		videoPresentFrame();
-		animFrameRecordVocCounter(4);
-	} else {
-		renderSetDirty();
-	}
-}
-
-void ComfyEngine::processInput() {
-	_lastKey = 0xFFFF;
-	if (inputQueueHasItems())
-		_lastKey = lptReadKeyOrNext();
-
-	lptKeyToFlags(_lastKey);
-	if (_lastKey == 0x0101) {
-		_mainLoopRunning = false;
-		return;
-	}
-
-	uint16 rootIndex = _sceneHandles.size() > 1 ? _sceneHandles[1] : 0;
-	Actor *root = actorGet(rootIndex);
-	if (root && !actorReadByte(*root, kActorActive))
-		_mainLoopRunning = false;
-}
-
-void ComfyEngine::processMusicEvents() {
-	if (!_musicEventMask)
-		return;
-
-	if (_musicEventFlag)
-		vocQueuePlayAll();
-
-	if (vocQueueIsIdle() || _musicEnabled) {
-		uint16 track = 1;
-		while ((_musicEventMask = uint16(int16(_musicEventMask) >> 1)) != 0) {
-			if (_musicEventMask & 1)
-				environmentStore(track);
-
-			track++;
-		}
-	}
-}
-
-void ComfyEngine::processSceneTransition() {
-	keyBitClear(0x42);
-	if (!_pendingScene) {
-		actorSetAllDirty();
-		return;
-	}
-
-	byte keySnapshot[15];
-	memset(keySnapshot, 0, sizeof(keySnapshot));
-	if (_keyBits)
-		memcpy(keySnapshot, _keyBits, MIN<uint32>(sizeof(keySnapshot), _keyBitsSize));
-
-	if (!_musicEnabled && _midiPlyrDriver)
-		_midiPlyrDriver->musicStopAll(1);
-
-	if (environmentLoad(_pendingScene)) {
-		if (!_musicEnabled) {
-			for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
-				_midiChannels[channel].playing = false;
-				if (_midiChannels[channel].entryCount)
-					midiStartChannel(channel);
-			}
-		}
-
-		Actor *root = actorGet(0);
-		if (root) {
-			paletteLoadWithFade(actorReadWord(*root, kActorXFixed), 0);
-			if (actorReadDword(*root, kActorYFixed))
-				paletteApplyBrightness(actorReadWord(*root, kActorYFixed));
-		}
-	}
-
-	if (_keyBits)
-		memcpy(_keyBits, keySnapshot, MIN<uint32>(sizeof(keySnapshot), _keyBitsSize));
-
-	keyBitSet(0x42);
-}
-
 void ComfyEngine::vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc) {
 	uint16 next = (_soundEventMaximum + 1) % COMFY_VOC_QUEUE_CAPACITY;
 	if (next == _soundEventIndex)
@@ -552,15 +517,4 @@ bool ComfyEngine::vocQueueIsIdle() {
 	return _soundEventIndex == _soundEventMaximum;
 }
 
-Common::Error ComfyEngine::syncGame(Common::Serializer &s) {
-	// The Serializer has methods isLoading() and isSaving()
-	// if you need to specific steps; for example setting
-	// an array size after reading it's length, whereas
-	// for saving it would write the existing array's length
-	int dummy = 0;
-	s.syncAsUint32LE(dummy);
-
-	return Common::kNoError;
-}
-
 } // End of namespace Comfy
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 1e71a24def5..3ec724800b1 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -301,6 +301,7 @@ private:
 	uint32 _picDataSize;
 	bool _usesAnimFile;
 	bool _sceneOpen;
+	bool _sceneEntryListActive;
 	Common::Array<uint16> _stringTable;
 	Common::Array<uint16> _sceneHandles;
 	Common::Array<uint16> _midiHandles;
@@ -308,6 +309,7 @@ private:
 	Common::Array<byte> _sceneMemoryBlock;
 	Common::Array<byte> _scenePoolData;
 	Common::Array<byte> _environmentData;
+	Common::Array<byte> _headerXmsData;
 	Common::Array<byte> _sceneFrameData;
 	Common::Array<SpriteCacheEntry> _objectCacheEntries;
 	Common::Array<SpriteCacheEntry> _frameCacheEntries;
@@ -322,6 +324,16 @@ private:
 	uint32 _sceneKeyBitsOffset;
 	uint32 _scenePoolCursor;
 	uint32 _scenePoolEvictCursor;
+	uint32 _scenePoolSize;
+	uint32 _headerXmsObjectTableBase;
+	uint32 _headerXmsObjectTableBytes;
+	uint32 _headerXmsPicEntriesBase;
+	uint32 _headerXmsPicEntriesBytes;
+	uint32 _headerXmsSoundHeadersBase;
+	uint32 _headerXmsSoundHeadersBytes;
+	uint16 _selectorPoolEntries[10];
+	uint16 _selectorRing;
+	bool _selectorPoolInitialized;
 	uint16 _activeSceneCount;
 	uint16 _sceneEntryCount;
 	uint16 _sceneEntryFrameSize;
@@ -464,21 +476,43 @@ private:
 	void lptKeyboardDispatchEvents(uint32 scanState);
 	void setKeyboardContact(uint16 contact, bool pressed, bool keymapper);
 	bool readAssetFile(const Common::Path &filename, Common::Array<byte> &data);
-	bool assetsLoad();
-	void assetsUnload();
+	uint32 assetsAlignEven32(uint32 value);
+	uint16 assetsReadLe16At(Common::Array<byte> &data, uint32 offset);
+	uint32 assetsReadLe32At(Common::Array<byte> &data, uint32 offset);
+	int32 assetsXmsCopy(byte *destination, uint32 destinationSize, uint32 destinationOffset,
+		const byte *source, uint32 sourceSize, uint32 sourceOffset, uint32 size);
+	bool selPoolInit();
+	void selPoolFree();
+	bool assetsLoad(uint32 budget, byte *scenePtr);
+	void assetsUnload(byte freeAudio);
+	bool sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount,
+		uint16 handleCount, uint32 &numSprites);
+	void midiShutdown();
 	bool comfyObjOpen();
 	bool picFileOpen();
 	bool midiFileOpen();
-	bool spriteLoad(int16 spriteId);
-	SpriteResource *spriteGet(int16 spriteId);
+	void objFileReadEntries(byte *destination);
+	byte *soundReadTiledData();
+	void soundGetTileParams(uint16 *tileStride, uint16 *fieldCount);
+	void spriteCache(int16 spriteId);
+	void spriteInvalidateHostCache(SpriteResource &sprite);
+	void objHdrReadFromXms(byte *destination, uint32 base, uint16 size, uint16 row);
+	void objHdrRead(SpriteObjectHeader &destination, uint16 index);
+	void scenePoolEvict();
+	void scenePoolReserveSlot(uint32 size);
+	SpriteResource *spriteGetPtr(int16 spriteId);
 	bool spriteDecompressTile(SpriteResource &sprite, const byte *source, uint32 sourceSize);
 	void spriteBlitClipped(int16 spriteId, int16 x, int16 y);
 	void spriteBlitRle(const byte *source, uint32 sourceSize);
-	bool sceneOpen();
-	void sceneClose();
-	void scenePackRuntimeState();
-	bool environmentLoad(uint16 index);
-	bool environmentStore(uint16 index);
+	bool sceneOpen(uint32 sceneEntryListOffset);
+	void sceneShutdown();
+	void sceneEntryReadFromXms(byte *destination, uint16 row, uint16 size);
+	byte *sceneFrameGetPtr(uint16 kind, uint16 size);
+	byte *spriteLoadFromFile(uint16 fileOffset, uint16 index);
+	void sceneBlockPackRuntimeState();
+	void sceneBlockUnpackRuntimeState();
+	bool envXmsToConv(byte *destination, uint16 index);
+	void envConvToXms(byte *source, uint16 index);
 	void sceneGoto(uint16 count);
 	void sceneStop();
 	bool sceneEntryLoad(uint16 descriptor, uint16 index);
@@ -491,13 +525,16 @@ private:
 	uint16 scriptEvalExpr(uint32 &pc, uint16 fallbackActor);
 	ScriptDispatchStatus scriptDispatch(Actor &actor, byte opcode, uint32 &pc);
 	ScriptDispatchStatus scriptStep(Actor &actor, uint32 &pc);
-	uint32 actorReadDword(Actor &actor, uint offset);
-	uint16 actorReadWord(Actor &actor, uint offset);
-	byte actorReadByte(Actor &actor, uint offset);
-	void actorWriteDword(Actor &actor, uint offset, uint32 value);
-	void actorWriteWord(Actor &actor, uint offset, uint16 value);
-	void actorWriteByte(Actor &actor, uint offset, byte value);
+	uint32 actorReadU32(Actor &actor, uint offset);
+	uint16 actorReadU16(Actor &actor, uint offset);
+	byte actorReadU8(Actor &actor, uint offset);
+	void actorWriteU32(Actor &actor, uint offset, uint32 value);
+	void actorWriteU16(Actor &actor, uint offset, uint16 value);
+	void actorWriteU8(Actor &actor, uint offset, byte value);
+	Actor *rootActor();
 	Actor *actorGet(uint16 actorIndex);
+	void actorSetFrame(int16 frame);
+	uint16 actorGetFrame();
 	Actor *actorResolve(uint16 sceneOrActor, uint16 fallbackActor);
 	uint16 actorAllocate(uint16 sceneSlot);
 	void actorFree(uint16 sceneSlot);
@@ -509,11 +546,11 @@ private:
 	void actorFreePcChain(Actor &actor);
 	void actorFreeTree(uint16 actorIndex);
 	void actorClearDirtyTree(uint16 actorIndex);
-	void actorSetAllDirty();
+	void actorSetAllVisible();
 	uint16 actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible, byte active,
 		uint32 pc, int16 x, int16 y, int16 sprite, byte insertAsChild);
 	bool actorRunScript(uint16 actorIndex, bool &descendChildren);
-	bool actorTickTreeInternal(uint16 actorIndex);
+	bool actorTickTree(uint16 actorIndex);
 	bool actorDraw(uint16 actorIndex, int16 x, int16 y);
 	void actorDrawList(uint16 actorIndex, int16 x, int16 y);
 	void actorDrawScripted(uint16 actorIndex, uint32 selector, int16 x, int16 y);
@@ -524,9 +561,8 @@ private:
 	void timerShutdown();
 	void lptKeyboardInit();
 	void lptKeyboardShutdown();
-	void gameMainLoop();
+	void gameMainLoop(uint16 argument);
 	uint16 sceneRun(uint16 sceneId, bool checkNext, bool exitFlag);
-	void gameMainLoopTick();
 	void processEvents();
 
 	uint16 timerTick();
@@ -543,9 +579,11 @@ private:
 	void animFrameRecordVocCounter(uint16 phase);
 	void animFrameWaitForVocCounter();
 	void sceneTickEvent();
+	void sceneStartWithMusic(uint16 scene);
 	void midiPollChannels(uint16 ticks);
 	void midiInitInstance();
 	void midiInitChannels();
+	void midiSyncAndScan();
 	void midiFindNext(MidiQueue &queue);
 	void midiQueueAdd(MidiQueue &queue, uint16 id, int16 delta);
 	void midiQueueRemove(MidiQueue &queue, uint16 id);
@@ -555,7 +593,11 @@ private:
 	void midiAddTrackEntry(uint16 channel, uint16 songId, uint16 completionKey, byte loadFlag,
 		uint16 frameCount, uint16 *frames);
 	void midiClearChannel(uint16 channel);
-	void midiStartChannel(uint16 channel);
+	void midiResumeAll();
+	void midiStopChannel(uint16 channel);
+	void midiStopAll();
+	void midiStopSong(uint16 channel);
+	void midiPlaySongAtFrame(uint16 channel, uint16 frame);
 	void midiFinishChannel(uint16 channel);
 	void midiStopAndFireKeys(uint16 channel);
 	void midiStopAndRemove(uint16 channel);
@@ -564,16 +606,12 @@ private:
 	void musicSetEnabled(byte value);
 	void paletteFadeStep(uint16 ticks);
 	void lptKeyboardScanAndProcess();
-	void actorTickTree();
-	void renderFrame();
-	void processInput();
-	void processMusicEvents();
-	void processSceneTransition();
 	void vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc);
 	void vocQueuePlayAll();
 	bool vocQueueIsIdle();
 	bool soundInit();
 	void soundShutdown();
+	void soundHdrReadFromXms(byte *destination, uint16 index, uint16 size);
 	bool soundDecodeEntry(uint16 index);
 	bool soundDecodeCompressedEntry(uint32 dataOffset, uint32 dataSize);
 	bool soundLoadEntry(uint16 index);
@@ -602,33 +640,14 @@ public:
 	}
 
 	bool hasFeature(EngineFeature f) const override {
-		return
-		    (f == kSupportsLoadingDuringRuntime) ||
-		    (f == kSupportsSavingDuringRuntime) ||
-		    (f == kSupportsReturnToLauncher) ||
-		    (f == kSupportsQuitDialogOverride);
+		return (f == kSupportsReturnToLauncher);
 	};
 
 	bool canLoadGameStateCurrently(Common::U32String *msg = nullptr) override {
-		return true;
+		return false;
 	}
 	bool canSaveGameStateCurrently(Common::U32String *msg = nullptr) override {
-		return true;
-	}
-
-	/**
-	 * Uses a serializer to allow implementing savegame
-	 * loading and saving using a single method
-	 */
-	Common::Error syncGame(Common::Serializer &s);
-
-	Common::Error saveGameStream(Common::WriteStream *stream, bool isAutosave = false) override {
-		Common::Serializer s(nullptr, stream);
-		return syncGame(s);
-	}
-	Common::Error loadGameStream(Common::SeekableReadStream *stream) override {
-		Common::Serializer s(stream, nullptr);
-		return syncGame(s);
+		return false;
 	}
 };
 
diff --git a/engines/comfy/expr.cpp b/engines/comfy/expr.cpp
index 30c9d3415fa..688ebf5a4f1 100644
--- a/engines/comfy/expr.cpp
+++ b/engines/comfy/expr.cpp
@@ -61,23 +61,23 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 
 			uint16 value = 0;
 			if (opcode == 0x10)
-				value = actorReadDword(*actor, kActorXFixed) >> 12;
+				value = actorReadU32(*actor, kActorXFixed) >> 12;
 			else if (opcode == 0x11)
-				value = actorReadDword(*actor, kActorYFixed) >> 12;
+				value = actorReadU32(*actor, kActorYFixed) >> 12;
 			else if (opcode == 0x12 || opcode == 0x13) {
 				uint offset = opcode == 0x12 ? kActorXFixed : kActorYFixed;
-				int32 position = actorReadDword(*actor, offset);
-				while (actorReadWord(*actor, kActorParent)) {
-					actor = actorGet(actorReadWord(*actor, kActorParent));
+				int32 position = actorReadU32(*actor, offset);
+				while (actorReadU16(*actor, kActorParent)) {
+					actor = actorGet(actorReadU16(*actor, kActorParent));
 					if (!actor)
 						break;
 
-					position += actorReadDword(*actor, offset);
+					position += actorReadU32(*actor, offset);
 				}
 
 				value = uint16(position >> 12);
 			} else if (opcode == 0x14)
-				value = actorReadWord(*actor, kActorSpriteSelector);
+				value = actorReadU16(*actor, kActorSpriteSelector);
 
 			if (_exprStackTop < COMFY_EXPR_STACK_CAPACITY)
 				_exprStack[_exprStackTop++] = value;
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index a2462fa6052..76d1bcd258b 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -230,21 +230,21 @@ bool ComfyEngine::comfyObjOpen() {
 	if (!readAssetFile(Common::Path("COMFY.OBJ"), _comfyObjData) || _comfyObjData.size() < 0x14)
 		return false;
 
-	_stringCount = READ_LE_UINT16(&_comfyObjData[0x08]);
-	_sceneCount = READ_LE_UINT16(&_comfyObjData[0x0A]);
-	_keyBitCount = READ_LE_UINT16(&_comfyObjData[0x0C]);
-	_picDataSize = READ_LE_UINT32(&_comfyObjData[0x0E]);
-	_resourceHandleCount = READ_LE_UINT16(&_comfyObjData[0x12]);
+	_stringCount = assetsReadLe16At(_comfyObjData, 0x08);
+	_sceneCount = assetsReadLe16At(_comfyObjData, 0x0A);
+	_keyBitCount = assetsReadLe16At(_comfyObjData, 0x0C);
+	_picDataSize = assetsReadLe32At(_comfyObjData, 0x0E);
+	_resourceHandleCount = assetsReadLe16At(_comfyObjData, 0x12);
 	_usesAnimFile = (_resourceHandleCount & 0x8000) != 0;
 	_resourceHandleCount &= 0x7FFF;
-	return keyBitAllocate(_keyBitCount);
+	return true;
 }
 
 bool ComfyEngine::picFileOpen() {
 	if (!readAssetFile(Common::Path("PICFILE.DAT"), _picFileData) || _picFileData.size() < 2)
 		return false;
 
-	uint16 count = READ_LE_UINT16(&_picFileData[0]);
+	uint16 count = assetsReadLe16At(_picFileData, 0);
 	uint32 tableSize = 2 + uint32(count) * 0x11;
 	if (tableSize > _picFileData.size())
 		return false;
@@ -252,24 +252,11 @@ bool ComfyEngine::picFileOpen() {
 	_spriteHeaders.resize(count);
 	_spriteResources.resize(count);
 	for (uint i = 0; i < count; i++) {
-		byte *entry = &_picFileData[2 + i * 0x11];
-		SpriteObjectHeader &header = _spriteHeaders[i];
-		header.fileOffset = READ_LE_UINT32(entry);
-		header.dataSize = READ_LE_UINT16(entry + 0x04);
-		header.width = READ_LE_UINT16(entry + 0x06);
-		header.height = READ_LE_UINT16(entry + 0x08);
-		header.hotspotX = int16(READ_LE_UINT16(entry + 0x0A));
-		header.hotspotY = int16(READ_LE_UINT16(entry + 0x0C));
-		header.reserved = entry[0x0E];
-		header.tiledSize = READ_LE_UINT16(entry + 0x0F);
-		_spriteResources[i].header = header;
+		memset(&_spriteHeaders[i], 0, sizeof(SpriteObjectHeader));
+		memset(&_spriteResources[i].header, 0, sizeof(SpriteObjectHeader));
 		_spriteResources[i].id = i;
 		_spriteResources[i].pixels.clear();
 		_spriteResources[i].loaded = false;
-
-		if (header.fileOffset > _picFileData.size() ||
-				header.dataSize > _picFileData.size() - header.fileOffset)
-			return false;
 	}
 
 	return true;
@@ -282,68 +269,166 @@ bool ComfyEngine::midiFileOpen() {
 	if (_midiFileData[0] != 'C' || (_midiFileData[1] != 'M' && _midiFileData[1] != 'm'))
 		return false;
 
-	_midiEntryCount = READ_LE_UINT16(&_midiFileData[2]);
+	_midiEntryCount = assetsReadLe16At(_midiFileData, 2);
 	_midiFileMode = _midiFileData[1] == 'm' ? 1 : 0;
 	return true;
 }
 
-bool ComfyEngine::assetsLoad() {
-	assetsUnload();
-	if (!comfyObjOpen() || !picFileOpen() || !midiFileOpen()) {
-		assetsUnload();
-		return false;
-	}
+uint32 ComfyEngine::assetsAlignEven32(uint32 value) {
+	return value + (value & 1);
+}
 
-	if (!soundInit()) {
-		assetsUnload();
-		return false;
-	}
+uint16 ComfyEngine::assetsReadLe16At(Common::Array<byte> &data, uint32 offset) {
+	return offset <= data.size() && 2 <= data.size() - offset ? READ_LE_UINT16(&data[offset]) : 0;
+}
 
-	if (_usesAnimFile && !animFileOpen()) {
-		assetsUnload();
-		return false;
-	}
+uint32 ComfyEngine::assetsReadLe32At(Common::Array<byte> &data, uint32 offset) {
+	return offset <= data.size() && 4 <= data.size() - offset ? READ_LE_UINT32(&data[offset]) : 0;
+}
+
+int32 ComfyEngine::assetsXmsCopy(byte *destination, uint32 destinationSize, uint32 destinationOffset,
+		const byte *source, uint32 sourceSize, uint32 sourceOffset, uint32 size) {
+	if (!size)
+		return 0;
+
+	if (!destination || !source || destinationOffset > destinationSize || size > destinationSize - destinationOffset ||
+			sourceOffset > sourceSize || size > sourceSize - sourceOffset)
+		return -1;
+
+	memcpy(destination + destinationOffset, source + sourceOffset, size);
+	return 0;
+}
+
+void ComfyEngine::objFileReadEntries(byte *destination) {
+	if (!destination || _midiFileData.size() <= 4)
+		return;
+
+	uint32 size = uint32(_midiEntryCount) * 6;
+	memcpy(destination, &_midiFileData[4], MIN<uint32>(size, _midiFileData.size() - 4));
+}
+
+byte *ComfyEngine::soundReadTiledData() {
+	return _vocFileData.size() > 4 ? &_vocFileData[4] : nullptr;
+}
+
+void ComfyEngine::soundGetTileParams(uint16 *tileStride, uint16 *fieldCount) {
+	if (tileStride)
+		*tileStride = _soundTileStride;
 
+	if (fieldCount)
+		*fieldCount = 8;
+}
+
+bool ComfyEngine::selPoolInit() {
+	if (_selectorPoolInitialized)
+		return true;
+
+	for (uint i = 0; i < ARRAYSIZE(_selectorPoolEntries); i++)
+		_selectorPoolEntries[i] = i + 1;
+
+	_selectorRing = 0;
+	_selectorPoolInitialized = true;
+	return true;
+}
+
+void ComfyEngine::selPoolFree() {
+	if (!_selectorPoolInitialized)
+		return;
+
+	memset(_selectorPoolEntries, 0, sizeof(_selectorPoolEntries));
+	_selectorRing = 0;
+	_selectorPoolInitialized = false;
+}
+
+bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount,
+		uint16 handleCount, uint32 &numSprites) {
 	_stringTable.resize(_stringCount + 1);
 	memset(&_stringTable[0], 0, _stringTable.size() * sizeof(uint16));
-	_sceneHandles.resize(_sceneCount + 1);
+	_sceneHandles.resize(sceneCount + 1);
 	memset(&_sceneHandles[0], 0, _sceneHandles.size() * sizeof(uint16));
-	_midiHandles.resize(_resourceHandleCount + 1);
+	_midiHandles.resize(handleCount + 1);
 	memset(&_midiHandles[0], 0, _midiHandles.size() * sizeof(uint16));
-	_actors.resize(COMFY_ACTOR_COUNT);
+	_actors.resize(actorCount + 1);
 	memset(&_actors[0], 0, _actors.size() * sizeof(Actor));
-	memset(_actorPcTable, 0, sizeof(_actorPcTable));
-	for (uint i = 1; i + 1 < _actors.size(); i++)
-		actorWriteWord(_actors[i], kActorNextLink, i + 1);
+	if (!keyBitAllocate(keyBitCount))
+		return false;
 
-	actorWriteWord(_actors[0], kActorNextLink, _actors.size() > 1 ? 1 : 0);
-	for (uint i = 1; i < COMFY_ACTOR_PC_TABLE_COUNT; i++)
+	memset(_actorPcTable, 0, sizeof(_actorPcTable));
+	for (uint i = 0; i < 0xC7 && i < ARRAYSIZE(_actorPcTable); i++)
 		_actorPcTable[i] = uint32(i + 1) << 24;
 
-	_actorPcTable[COMFY_ACTOR_PC_TABLE_COUNT - 1] = 0;
-	_actorPcTable[0] = 1 << 24;
+	if (0xC7 < ARRAYSIZE(_actorPcTable))
+		_actorPcTable[0xC7] = 0;
+
+	uint32 midiVersionBytes = 0x167;
 	uint32 stringBytes = _stringTable.size() * sizeof(uint16);
 	uint32 handleBytes = _sceneHandles.size() * sizeof(uint16);
 	uint32 actorBytes = _actors.size() * sizeof(Actor);
-	uint32 keyBytes = (_keyBitCount + 1) / 8 + 1;
+	uint32 keyBytes = (uint32(keyBitCount) + 1) / 8 + 1;
 	_sceneMidiInstanceOffset = 0;
 	_sceneEntryListOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES;
-	_sceneActorPcOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES + 0x167;
+	_sceneActorPcOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES + midiVersionBytes;
 	_sceneStringTableOffset = _sceneActorPcOffset + COMFY_SCENE_ACTOR_PC_BYTES;
 	_sceneHandlesOffset = _sceneStringTableOffset + stringBytes;
 	_sceneActorsOffset = _sceneHandlesOffset + handleBytes;
 	_sceneKeyBitsOffset = _sceneActorsOffset + actorBytes;
-	uint32 sceneBytes = (_sceneKeyBitsOffset + keyBytes + 1) & ~1U;
+	uint32 sceneBytes = assetsAlignEven32(_sceneKeyBitsOffset + keyBytes);
 	_sceneMemoryBlock.resize(sceneBytes);
-	memset(&_sceneMemoryBlock[0], 0, _sceneMemoryBlock.size());
-	memcpy(&_sceneMemoryBlock[_sceneActorPcOffset], _actorPcTable, sizeof(_actorPcTable));
-	_sceneFrameData.resize(COMFY_SCENE_FRAME_BYTES);
-	memset(&_sceneFrameData[0], 0, _sceneFrameData.size());
-	memset(_sceneEntryOffsets, 0, sizeof(_sceneEntryOffsets));
+	memset(&_sceneMemoryBlock[0], 0, sceneBytes);
+	numSprites = sceneBytes;
+	_numSprites = numSprites;
+	_envNumSprites = numSprites;
+	_activeSceneCount = handleCount;
+
+	if (!sceneOpen(_sceneEntryListOffset))
+		return false;
+
+	for (uint i = 0; i + 1 < _actors.size(); i++) {
+		actorWriteU16(_actors[i], kActorNextLink, i + 1);
+		actorWriteU16(_actors[i], kActorSceneHandle, 0);
+	}
+
+	actorWriteU16(_actors[_actors.size() - 1], kActorNextLink, 0);
+	actorWriteU16(_actors[_actors.size() - 1], kActorSceneHandle, 0);
+	actorSetFrame(0);
+	return true;
+}
+
+bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
+	if (!selPoolInit())
+		return false;
+
+	if (!comfyObjOpen() || !picFileOpen() || !midiFileOpen()) {
+		return false;
+	}
+
+	if (!soundInit()) {
+		return false;
+	}
+
 	_numFrames = _picDataSize / COMFY_TILE_SIZE + (_picDataSize % COMFY_TILE_SIZE ? 2 : 1);
 	_numObjects = _spriteHeaders.size();
-	_numSprites = sceneBytes;
-	_envNumSprites = _numSprites;
+	uint32 numSprites = 0;
+	if (!sceneLoadAndInit(_sceneCount, 0x78, _keyBitCount, _resourceHandleCount, numSprites))
+		return false;
+
+	uint32 environmentBytes = ((_envNumSprites * 5 + 0x3FF) / 0x400) * 0x400;
+	_environmentData.resize(environmentBytes);
+	if (environmentBytes)
+		memset(&_environmentData[0], 0, environmentBytes);
+
+	uint32 midiHeaderBytes = assetsAlignEven32(uint32(_midiEntryCount) * 6);
+	uint16 soundTileStride = 0;
+	uint16 soundFieldCount = 0;
+	soundGetTileParams(&soundTileStride, &soundFieldCount);
+	uint32 soundHeaderBytes = assetsAlignEven32(uint32(soundTileStride) * soundFieldCount);
+	uint32 objectTableBytes = assetsAlignEven32(uint32(_numObjects) * 0x11);
+	uint32 headerTotalBytes = midiHeaderBytes + soundHeaderBytes + objectTableBytes;
+	uint16 headerPages = (headerTotalBytes + 0x400) / 0x400;
+	_headerXmsData.resize(uint32(headerPages) * 0x400);
+	if (!_headerXmsData.empty())
+		memset(&_headerXmsData[0], 0, _headerXmsData.size());
+
 	_objectCacheEntries.resize(_spriteHeaders.size());
 	_frameCacheEntries.resize(_numFrames + 1);
 	if (!_objectCacheEntries.empty())
@@ -351,15 +436,67 @@ bool ComfyEngine::assetsLoad() {
 
 	if (!_frameCacheEntries.empty())
 		memset(&_frameCacheEntries[0], 0xFF, _frameCacheEntries.size() * sizeof(SpriteCacheEntry));
+
 	memset(&_spriteConversionLoads, 0, sizeof(_spriteConversionLoads));
-	_scenePoolData.resize(0x1FC000);
-	memset(&_scenePoolData[0], 0, _scenePoolData.size());
+
+	for (uint i = 0; i < _spriteResources.size(); i++)
+		spriteInvalidateHostCache(_spriteResources[i]);
+
+	if (_usesAnimFile && !animFileOpen())
+		return false;
+
+	uint32 xmsLimit = 0x0800 << 10;
+	_scenePoolSize = xmsLimit > budget ? xmsLimit - budget : 0;
+	_scenePoolSize &= 0xFFFFFFFE;
+	_scenePoolData.resize(_scenePoolSize);
+	if (_scenePoolSize)
+		memset(&_scenePoolData[0], 0, _scenePoolSize);
+
 	_scenePoolCursor = 0;
 	_scenePoolEvictCursor = 0;
-	uint32 environmentBytes = ((_envNumSprites * 5 + 0x3FF) / 0x400) * 0x400;
-	_environmentData.resize(environmentBytes);
-	if (environmentBytes)
-		memset(&_environmentData[0], 0, environmentBytes);
+	if (_scenePoolSize >= 2)
+		WRITE_LE_UINT16(&_scenePoolData[0], 0x8000);
+
+	uint32 xmsOffset = 0;
+	uint32 fileOffset = 2;
+	uint32 remaining = objectTableBytes;
+	_headerXmsObjectTableBase = xmsOffset;
+	_headerXmsObjectTableBytes = objectTableBytes;
+	while (remaining) {
+		uint32 chunk = MIN<uint32>(remaining, 0x8000);
+		if (assetsXmsCopy(&_headerXmsData[0], _headerXmsData.size(), xmsOffset,
+				&_picFileData[0], _picFileData.size(), fileOffset, chunk) < 0)
+			return false;
+
+		xmsOffset += chunk;
+		fileOffset += chunk;
+		remaining -= chunk;
+	}
+
+	_headerXmsPicEntriesBase = xmsOffset;
+	_headerXmsPicEntriesBytes = midiHeaderBytes;
+	if (midiHeaderBytes && scenePtr) {
+		memset(scenePtr, 0, midiHeaderBytes);
+		objFileReadEntries(scenePtr);
+
+		if (assetsXmsCopy(&_headerXmsData[0], _headerXmsData.size(), xmsOffset,
+				scenePtr, midiHeaderBytes, 0, midiHeaderBytes) < 0)
+			return false;
+
+		xmsOffset += midiHeaderBytes;
+	}
+
+	_headerXmsSoundHeadersBase = xmsOffset;
+	_headerXmsSoundHeadersBytes = soundHeaderBytes;
+	if (soundHeaderBytes) {
+		byte *soundTiledData = soundReadTiledData();
+		uint32 available = _vocFileData.size() > 4 ? MIN<uint32>(soundHeaderBytes, _vocFileData.size() - 4) : 0;
+		if (available && assetsXmsCopy(&_headerXmsData[0], _headerXmsData.size(), xmsOffset,
+				soundTiledData, available, 0, available) < 0)
+			return false;
+
+		xmsOffset += soundHeaderBytes;
+	}
 
 	_activeSceneCount = _resourceHandleCount;
 	_sceneEntryCount = 0;
@@ -399,15 +536,12 @@ bool ComfyEngine::assetsLoad() {
 	return true;
 }
 
-void ComfyEngine::assetsUnload() {
+void ComfyEngine::assetsUnload(byte freeAudio) {
 	animFileShutdown(true);
-	soundShutdown();
-	keyBitFree();
-	_comfyObjData.clear();
-	_picFileData.clear();
-	_midiFileData.clear();
 	_spriteHeaders.clear();
 	_spriteResources.clear();
+	spriteInvalidateHostCache(_frameSpriteResource);
+	_frameSpriteResource.id = 0;
 	_stringTable.clear();
 	_sceneHandles.clear();
 	_midiHandles.clear();
@@ -415,9 +549,20 @@ void ComfyEngine::assetsUnload() {
 	_sceneMemoryBlock.clear();
 	_scenePoolData.clear();
 	_environmentData.clear();
-	_sceneFrameData.clear();
+	_headerXmsData.clear();
 	_objectCacheEntries.clear();
 	_frameCacheEntries.clear();
+	keyBitFree();
+	if (!_vocFileData.empty())
+		soundShutdown();
+
+	if (_sceneOpen)
+		sceneShutdown();
+
+	_comfyObjData.clear();
+	_picFileData.clear();
+	_midiFileData.clear();
+	selPoolFree();
 	memset(&_spriteConversionLoads, 0, sizeof(_spriteConversionLoads));
 	memset(_sceneEntryOffsets, 0, sizeof(_sceneEntryOffsets));
 	memset(_actorPcTable, 0, sizeof(_actorPcTable));
@@ -459,6 +604,18 @@ void ComfyEngine::assetsUnload() {
 	_sceneEntryFrameSize = 0;
 	_midiFileMode = 0;
 	_usesAnimFile = false;
+	_sceneEntryListActive = false;
+	_scenePoolCursor = 0;
+	_scenePoolEvictCursor = 0;
+	_scenePoolSize = 0;
+	_headerXmsObjectTableBase = 0;
+	_headerXmsPicEntriesBase = 0;
+	_headerXmsSoundHeadersBase = 0;
+	_headerXmsObjectTableBytes = 0;
+	_headerXmsPicEntriesBytes = 0;
+	_headerXmsSoundHeadersBytes = 0;
+	// The original consumes one UI character here; ScummVM has no teardown prompt to acknowledge.
+	(void)freeAudio;
 }
 
 } // End of namespace Comfy
diff --git a/engines/comfy/midi.cpp b/engines/comfy/midi.cpp
index b061d960553..c0e6cde32ca 100644
--- a/engines/comfy/midi.cpp
+++ b/engines/comfy/midi.cpp
@@ -193,6 +193,15 @@ void ComfyEngine::midiInitChannels() {
 	}
 }
 
+void ComfyEngine::midiSyncAndScan() {
+	_midiTimeCounter = _midiInstanceEventTime;
+	if (_midiPlyrDriver)
+		_midiPlyrDriver->setTimeCounter(_midiTimeCounter);
+
+	midiFindNext(_midiEvents);
+	midiFindNext(_midiTracks);
+}
+
 void ComfyEngine::midiQueueAdd(MidiQueue &queue, uint16 id, int16 delta) {
 	if (queue.count == COMFY_MIDI_QUEUE_CAPACITY)
 		return;
@@ -237,32 +246,67 @@ void ComfyEngine::midiClearChannel(uint16 channel) {
 	_midiChannels[channel].playing = false;
 }
 
-void ComfyEngine::midiStartChannel(uint16 channel) {
+void ComfyEngine::midiResumeAll() {
+	if (!_midiPlyrDriver)
+		return;
+
+	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
+		if (_midiChannels[channel].entryCount)
+			_midiPlyrDriver->musicContinueSong(channel);
+	}
+}
+
+void ComfyEngine::midiStopChannel(uint16 channel) {
 	if (!_midiPlyrDriver || channel >= COMFY_MIDI_CHANNEL_COUNT || !_midiChannels[channel].entryCount)
 		return;
 
 	MidiChannelState &state = _midiChannels[channel];
-	uint32 descriptorOffset = 4 + uint32(state.entries[0].songId) * 6;
-	if (descriptorOffset > _midiFileData.size() || 6 > _midiFileData.size() - descriptorOffset) {
+	byte *song = spriteLoadFromFile(state.entries[0].songId, channel);
+	if (!song) {
 		midiClearChannel(channel);
 		return;
 	}
 
-	uint16 size = READ_LE_UINT16(&_midiFileData[descriptorOffset]);
-	uint32 fileOffset = READ_LE_UINT32(&_midiFileData[descriptorOffset + 2]);
-	if (!size || fileOffset > _midiFileData.size() || size > _midiFileData.size() - fileOffset || size > _sceneFrameData.size()) {
+	uint16 size = state.loadedFrameSize;
+	state.rateCurrent = state.rateDefault = size >= 4 ? READ_LE_UINT16(song + 2) : 0x07D0;
+	state.rateTarget = state.rateCurrent;
+	_midiPlyrDriver->musicPlaySong(song, size, channel);
+	_midiPlyrDriver->musicSetVolume(uint16(state.volumeCurrent >> 8), channel);
+	state.playing = true;
+}
+
+void ComfyEngine::midiStopAll() {
+	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++)
 		midiClearChannel(channel);
+
+	if (_midiPlyrDriver)
+		_midiPlyrDriver->musicStopAll(1);
+
+	if (_sceneEntryListActive) {
+		for (uint i = 0; i < _sceneEntryCount && i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++) {
+			if (_sceneEntryOffsets[i] != 0xFFFF)
+				sceneEntryLoad(_sceneEntryOffsets[i], i);
+		}
+
 		return;
 	}
 
-	uint32 destinationOffset = channel ? _sceneFrameData.size() - size : 0;
-	memcpy(&_sceneFrameData[destinationOffset], &_midiFileData[fileOffset], size);
-	state.loadedFrameSize = size;
-	state.rateCurrent = state.rateDefault = size >= 4 ? READ_LE_UINT16(&_sceneFrameData[destinationOffset + 2]) : 0x07D0;
-	state.rateTarget = state.rateCurrent;
-	_midiPlyrDriver->musicPlaySong(&_sceneFrameData[destinationOffset], size, channel);
-	_midiPlyrDriver->musicSetVolume(uint16(state.volumeCurrent >> 8), channel);
-	state.playing = true;
+	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
+		if (_midiChannels[channel].entryCount)
+			midiStopChannel(channel);
+	}
+}
+
+void ComfyEngine::midiShutdown() {
+	_midiHandles.clear();
+	_sceneMemoryBlock.clear();
+	_sceneMidiInstanceOffset = 0;
+	_sceneEntryListOffset = 0;
+	_sceneActorPcOffset = 0;
+	_sceneStringTableOffset = 0;
+	_sceneHandlesOffset = 0;
+	_sceneActorsOffset = 0;
+	_sceneKeyBitsOffset = 0;
 }
 
 void ComfyEngine::midiFinishChannel(uint16 channel) {
@@ -285,7 +329,7 @@ void ComfyEngine::midiFinishChannel(uint16 channel) {
 	state.entryCount--;
 	midiClearChannel(channel);
 	if (state.entryCount)
-		midiStartChannel(channel);
+		midiStopChannel(channel);
 }
 
 void ComfyEngine::midiStopAndFireKeys(uint16 channel) {
@@ -338,7 +382,7 @@ void ComfyEngine::midiAddTrackEntry(uint16 channel, uint16 songId, uint16 comple
 
 	state.entryCount++;
 	if (state.entryCount == 1)
-		midiStartChannel(channel);
+		midiStopChannel(channel);
 }
 
 void ComfyEngine::midiSetChannelParam(uint16 channel, byte parameter, uint16 value, uint16 ticks) {
@@ -396,10 +440,7 @@ void ComfyEngine::musicSetEnabled(byte value) {
 	if (_musicEnabled) {
 		_midiPlyrDriver->musicStopAll(0);
 	} else {
-		for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
-			if (_midiChannels[channel].entryCount)
-				_midiPlyrDriver->musicContinueSong(channel);
-		}
+		midiResumeAll();
 	}
 }
 
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index c90a3611c3e..524202aa885 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -25,7 +25,7 @@
 
 namespace Comfy {
 
-void ComfyEngine::scenePackRuntimeState() {
+void ComfyEngine::sceneBlockPackRuntimeState() {
 	if (_sceneMemoryBlock.empty())
 		return;
 
@@ -43,7 +43,7 @@ void ComfyEngine::scenePackRuntimeState() {
 	WRITE_LE_UINT16(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x188], _midiEvents.count);
 	WRITE_LE_UINT16(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x18A], _midiTracks.count);
 	byte *sceneEntries = &_sceneMemoryBlock[_sceneEntryListOffset];
-	sceneEntries[0] = _sceneEntryCount != 0;
+	sceneEntries[0] = _sceneEntryListActive;
 	WRITE_LE_UINT16(sceneEntries + 1, _sceneEntryCount);
 	WRITE_LE_UINT16(sceneEntries + 3, _sceneEntryFrameSize);
 	for (uint i = 0; i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
@@ -75,6 +75,7 @@ void ComfyEngine::scenePackRuntimeState() {
 				WRITE_LE_UINT16(packedEntry + 7 + frame * 2, state.entries[entry].frames[frame]);
 		}
 	}
+	memcpy(&_sceneMemoryBlock[_sceneActorPcOffset], _actorPcTable, sizeof(_actorPcTable));
 
 	if (!_stringTable.empty())
 		memcpy(&_sceneMemoryBlock[_sceneStringTableOffset], &_stringTable[0], _stringTable.size() * sizeof(uint16));
@@ -89,20 +90,19 @@ void ComfyEngine::scenePackRuntimeState() {
 		memcpy(&_sceneMemoryBlock[_sceneKeyBitsOffset], _keyBits, _keyBitsSize);
 }
 
-bool ComfyEngine::environmentStore(uint16 index) {
+void ComfyEngine::envConvToXms(byte *source, uint16 index) {
 	if (!index || _sceneMemoryBlock.empty())
-		return false;
+		return;
 
-	scenePackRuntimeState();
+	sceneBlockPackRuntimeState();
 	uint32 offset = uint32(index - 1) * _sceneMemoryBlock.size();
 	if (offset > _environmentData.size() || _sceneMemoryBlock.size() > _environmentData.size() - offset)
-		return false;
+		return;
 
-	memcpy(&_environmentData[offset], &_sceneMemoryBlock[0], _sceneMemoryBlock.size());
-	return true;
+	memcpy(&_environmentData[offset], source, _sceneMemoryBlock.size());
 }
 
-bool ComfyEngine::environmentLoad(uint16 index) {
+bool ComfyEngine::envXmsToConv(byte *destination, uint16 index) {
 	if (!index || _sceneMemoryBlock.empty())
 		return false;
 
@@ -110,7 +110,15 @@ bool ComfyEngine::environmentLoad(uint16 index) {
 	if (offset > _environmentData.size() || _sceneMemoryBlock.size() > _environmentData.size() - offset)
 		return false;
 
-	memcpy(&_sceneMemoryBlock[0], &_environmentData[offset], _sceneMemoryBlock.size());
+	memcpy(destination, &_environmentData[offset], _sceneMemoryBlock.size());
+	sceneBlockUnpackRuntimeState();
+	return true;
+}
+
+void ComfyEngine::sceneBlockUnpackRuntimeState() {
+	if (_sceneMemoryBlock.empty())
+		return;
+
 	for (uint i = 0; i < COMFY_MIDI_QUEUE_CAPACITY; i++) {
 		uint32 trackOffset = _sceneMidiInstanceOffset + i * 6;
 		_midiTracks.entries[i].id = READ_LE_UINT16(&_sceneMemoryBlock[trackOffset]);
@@ -129,6 +137,7 @@ bool ComfyEngine::environmentLoad(uint16 index) {
 	midiFindNext(_midiEvents);
 	midiFindNext(_midiTracks);
 	byte *sceneEntries = &_sceneMemoryBlock[_sceneEntryListOffset];
+	_sceneEntryListActive = sceneEntries[0] != 0;
 	_sceneEntryCount = READ_LE_UINT16(sceneEntries + 1);
 	_sceneEntryFrameSize = READ_LE_UINT16(sceneEntries + 3);
 	for (uint i = 0; i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
@@ -167,10 +176,13 @@ bool ComfyEngine::environmentLoad(uint16 index) {
 	if (_keyBits && _keyBitsSize)
 		memcpy(_keyBits, &_sceneMemoryBlock[_sceneKeyBitsOffset], _keyBitsSize);
 
-	return true;
 }
 
 void ComfyEngine::sceneGoto(uint16 count) {
+	if (_midiPlyrDriver)
+		_midiPlyrDriver->musicStopAll(1);
+
+	_sceneEntryListActive = true;
 	_sceneEntryCount = count;
 	_sceneEntryFrameSize = count ? COMFY_SCENE_FRAME_BYTES / int16(count) : 0;
 	for (uint i = 0; i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
@@ -178,17 +190,45 @@ void ComfyEngine::sceneGoto(uint16 count) {
 }
 
 void ComfyEngine::sceneStop() {
-	_sceneEntryCount = 0;
-	_sceneEntryFrameSize = 0;
+	if (_midiPlyrDriver)
+		_midiPlyrDriver->musicStopAll(1);
+
+	_sceneEntryListActive = false;
 }
 
-bool ComfyEngine::sceneEntryLoad(uint16 descriptor, uint16 index) {
-	uint32 descriptorOffset = 4 + uint32(descriptor) * 6;
-	if (descriptorOffset > _midiFileData.size() || 6 > _midiFileData.size() - descriptorOffset)
-		return false;
+void ComfyEngine::sceneStartWithMusic(uint16 scene) {
+	byte keySnapshot[15];
+	memset(keySnapshot, 0, sizeof(keySnapshot));
+	if (_keyBits)
+		memcpy(keySnapshot, _keyBits, MIN<uint32>(sizeof(keySnapshot), _keyBitsSize));
+
+	if (!_musicEnabled && _midiPlyrDriver)
+		_midiPlyrDriver->musicStopAll(1);
+
+	if (!envXmsToConv(&_sceneMemoryBlock[_sceneMidiInstanceOffset], scene))
+		return;
+
+	midiSyncAndScan();
+	if (!_musicEnabled)
+		midiStopAll();
+
+	Actor *root = actorGet(0);
+	if (root) {
+		paletteLoadWithFade(actorReadU16(*root, kActorXFixed), 0);
+		if (actorReadU32(*root, kActorYFixed))
+			paletteApplyBrightness(actorReadU16(*root, kActorYFixed));
+	}
+
+	if (_keyBits)
+		memcpy(_keyBits, keySnapshot, MIN<uint32>(sizeof(keySnapshot), _keyBitsSize));
+}
 
-	uint16 size = READ_LE_UINT16(&_midiFileData[descriptorOffset]);
-	uint32 fileOffset = READ_LE_UINT32(&_midiFileData[descriptorOffset + 2]);
+bool ComfyEngine::sceneEntryLoad(uint16 descriptor, uint16 index) {
+	byte header[6];
+	memset(header, 0, sizeof(header));
+	sceneEntryReadFromXms(header, descriptor, sizeof(header));
+	uint16 size = READ_LE_UINT16(header);
+	uint32 fileOffset = READ_LE_UINT32(header + 2);
 	uint32 destinationOffset = uint32(_sceneEntryFrameSize) * index;
 	if (fileOffset > _midiFileData.size() || size > _midiFileData.size() - fileOffset ||
 			destinationOffset > _sceneFrameData.size() || size > _sceneFrameData.size() - destinationOffset)
@@ -201,42 +241,91 @@ bool ComfyEngine::sceneEntryLoad(uint16 descriptor, uint16 index) {
 	return true;
 }
 
-bool ComfyEngine::sceneOpen() {
-	if (_sceneOpen)
-		sceneClose();
+void ComfyEngine::sceneEntryReadFromXms(byte *destination, uint16 row, uint16 size) {
+	objHdrReadFromXms(destination, _headerXmsPicEntriesBase, size, row);
+}
 
-	if (_comfyObjData.empty() || _picFileData.empty() || _midiFileData.empty() || !midiPlyrStart())
-		return false;
+byte *ComfyEngine::sceneFrameGetPtr(uint16 kind, uint16 size) {
+	byte *result = nullptr;
+	if (kind == 0 && !_sceneFrameData.empty())
+		result = &_sceneFrameData[0];
+	else if (kind == 1 && size <= _sceneFrameData.size())
+		result = &_sceneFrameData[_sceneFrameData.size() - size];
 
-	paletteLoadWithFade(0, 0);
-	framebufClear(0);
-	if (actorInit(1, 0, 1, 1, 0x14, 0, 0, 0, 1) != 1) {
-		midiPlyrStop();
-		return false;
+	if (result && kind < COMFY_MIDI_CHANNEL_COUNT)
+		_midiChannels[kind].loadedFrameSize = size;
+
+	return result;
+}
+
+byte *ComfyEngine::spriteLoadFromFile(uint16 fileOffset, uint16 index) {
+	byte header[6];
+	memset(header, 0, sizeof(header));
+	sceneEntryReadFromXms(header, fileOffset, sizeof(header));
+	uint16 size = READ_LE_UINT16(header);
+	uint32 position = READ_LE_UINT32(header + 2);
+	if (!size)
+		return nullptr;
+
+	byte *destination = sceneFrameGetPtr(index, size);
+	if (!destination || position > _midiFileData.size() || size > _midiFileData.size() - position) {
+		if (index < COMFY_MIDI_CHANNEL_COUNT)
+			_midiChannels[index].loadedFrameSize = 0;
+
+		return nullptr;
 	}
 
+	memcpy(destination, &_midiFileData[position], size);
+	return destination;
+}
+
+void ComfyEngine::midiStopSong(uint16 channel) {
+	if (_midiPlyrDriver && channel < COMFY_MIDI_CHANNEL_COUNT)
+		_midiPlyrDriver->musicStopSong(1, channel);
+}
+
+void ComfyEngine::midiPlaySongAtFrame(uint16 channel, uint16 frame) {
+	midiStopSong(channel);
+	uint32 offset = uint32(_sceneEntryFrameSize) * frame;
+	if (!_midiPlyrDriver || channel >= COMFY_MIDI_CHANNEL_COUNT ||
+			offset > _sceneFrameData.size() || 6 > _sceneFrameData.size() - offset)
+		return;
+
+	byte *song = &_sceneFrameData[offset];
+	uint16 size = READ_LE_UINT16(song + 4) + 6;
+	if (size > _sceneFrameData.size() - offset)
+		return;
+
+	_midiPlyrDriver->musicPlaySong(song, size, channel);
+	_midiPlyrDriver->musicSetVolume(0x64, channel);
+}
+
+bool ComfyEngine::sceneOpen(uint32 sceneEntryListOffset) {
+	_sceneEntryListOffset = sceneEntryListOffset;
+	_sceneEntryListActive = false;
+	_sceneEntryCount = 0;
+	_sceneEntryFrameSize = 0x4E20;
+	if (_sceneFrameData.empty()) {
+		_sceneFrameData.resize(0x4E20);
+		memset(&_sceneFrameData[0], 0, _sceneFrameData.size());
+	}
+
+	if (_midiFileData.empty() || !midiPlyrStart())
+		return false;
+
 	_sceneOpen = true;
+	memset(_sceneEntryOffsets, 0, sizeof(_sceneEntryOffsets));
 	midiInitInstance();
 	midiInitChannels();
-	scenePackRuntimeState();
-	renderSetDirty();
 	return true;
 }
 
-void ComfyEngine::sceneClose() {
+void ComfyEngine::sceneShutdown() {
 	if (!_sceneOpen)
 		return;
 
-	if (_sceneHandles.size() > 1 && _sceneHandles[1])
-		actorFreeTree(_sceneHandles[1]);
-
-	scenePackRuntimeState();
 	midiPlyrStop();
-	for (uint i = 0; i < _spriteResources.size(); i++) {
-		_spriteResources[i].pixels.clear();
-		_spriteResources[i].loaded = false;
-	}
-
+	_sceneFrameData.clear();
 	_sceneOpen = false;
 }
 
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 0bc0e053f98..06d4367e736 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -44,14 +44,14 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			if (!other)
 				return kScriptUnhandled;
 
-			x = int16(int32(actorReadDword(*other, kActorXFixed)) >> 12);
-			y = int16(int32(actorReadDword(*other, kActorYFixed)) >> 12);
+			x = int16(int32(actorReadU32(*other, kActorXFixed)) >> 12);
+			y = int16(int32(actorReadU32(*other, kActorYFixed)) >> 12);
 		} else if (opcode == 0x01 && x == int16(0xF448)) {
-			x = int16(-int32(actorReadDword(*target, kActorXFixed)) >> 12);
+			x = int16(-int32(actorReadU32(*target, kActorXFixed)) >> 12);
 		}
 
 		if (opcode == 0x01 && y == int16(0xF448))
-			y = int16(-int32(actorReadDword(*target, kActorYFixed)) >> 12);
+			y = int16(-int32(actorReadU32(*target, kActorYFixed)) >> 12);
 
 		if (randomize) {
 			if (x != int16(0xFC18))
@@ -63,13 +63,13 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 		if (opcode == 0x01) {
 			if (x != int16(0xFC18))
-				actorWriteDword(*target, kActorXFixed, uint32(int32(x) * 0x1000));
+				actorWriteU32(*target, kActorXFixed, uint32(int32(x) * 0x1000));
 
 			if (y != int16(0xFC18))
-				actorWriteDword(*target, kActorYFixed, uint32(int32(y) * 0x1000));
+				actorWriteU32(*target, kActorYFixed, uint32(int32(y) * 0x1000));
 		} else {
-			actorWriteDword(*target, kActorXFixed, actorReadDword(*target, kActorXFixed) + uint32(int32(x) * 0x1000));
-			actorWriteDword(*target, kActorYFixed, actorReadDword(*target, kActorYFixed) + uint32(int32(y) * 0x1000));
+			actorWriteU32(*target, kActorXFixed, actorReadU32(*target, kActorXFixed) + uint32(int32(x) * 0x1000));
+			actorWriteU32(*target, kActorYFixed, actorReadU32(*target, kActorYFixed) + uint32(int32(y) * 0x1000));
 		}
 
 		return kScriptContinue;
@@ -81,7 +81,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint16 frame = scriptReadStringIndex(pc);
 		pc += 2;
 		if (target)
-			actorWriteDword(*target, kActorSpriteSelector, uint32(int32(int16(frame))));
+			actorWriteU32(*target, kActorSpriteSelector, uint32(int32(int16(frame))));
 
 		return kScriptContinue;
 	}
@@ -151,17 +151,14 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		int16 sprite = scriptReadWord(pc);
 		pc += 2;
 		if (!parentSlot)
-			parentSlot = actorReadWord(actor, kActorSceneHandle);
+			parentSlot = actorReadU16(actor, kActorSceneHandle);
 
 		actorInit(sceneSlot, parentSlot, flags & 1, flags & 2, newPc, x, y, sprite, flags & 4);
 		return kScriptContinue;
 	}
 
 	if (opcode == 0x09) {
-		Actor *root = actorGet(0);
-		if (root)
-			actorWriteDword(*root, kActorSpriteSelector, uint32(int32(int16(scriptReadWord(pc)))));
-
+		actorSetFrame(int16(scriptReadWord(pc)));
 		pc += 2;
 		return kScriptContinue;
 	}
@@ -173,14 +170,14 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			return kScriptUnhandled;
 
 		if (opcode == 0x0A)
-			actorWriteByte(*target, kActorVisible, 1);
+			actorWriteU8(*target, kActorVisible, 1);
 		else if (opcode == 0x0B)
-			actorWriteByte(*target, kActorVisible, 0);
+			actorWriteU8(*target, kActorVisible, 0);
 		else if (opcode == 0x0C)
-			actorWriteByte(*target, kActorActive, 1);
+			actorWriteU8(*target, kActorActive, 1);
 		else {
-			actorWriteWord(*target, kActorMoveTicks, 0);
-			actorWriteByte(*target, kActorActive, 0);
+			actorWriteU16(*target, kActorMoveTicks, 0);
+			actorWriteU8(*target, kActorActive, 0);
 			if (target == &actor)
 				return kScriptYield;
 		}
@@ -197,7 +194,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		if (!target)
 			return kScriptUnhandled;
 
-		int16 actual = int32(actorReadDword(*target, opcode == 0x0E || opcode == 0x10 ? kActorXFixed : kActorYFixed)) >> 12;
+		int16 actual = int32(actorReadU32(*target, opcode == 0x0E || opcode == 0x10 ? kActorXFixed : kActorYFixed)) >> 12;
 		bool matched = ((mode & 2) && expected == actual) || ((mode & 4) && expected < actual) || ((mode & 1) && expected > actual);
 		if (matched) {
 			if (opcode == 0x0E || opcode == 0x0F)
@@ -245,7 +242,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			return kScriptUnhandled;
 
 		uint16 targetIndex = uint16(target - &_actors[0]);
-		uint16 oldParent = actorReadWord(*target, kActorParent);
+		uint16 oldParent = actorReadU16(*target, kActorParent);
 		actorUnlink(targetIndex);
 		if (mode == 'O')
 			actorInsertChild(targetIndex, oldParent);
@@ -261,7 +258,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			uint16 id = scriptReadWord(pc);
 			pc += 2;
 			if (opcode == 0x15) {
-				spriteGet(int16(id));
+				spriteGetPtr(int16(id));
 				if (_spriteConversionLoads.count < COMFY_RESOURCE_LIST_CAPACITY)
 					_spriteConversionLoads.ids[_spriteConversionLoads.count++] = id;
 			} else {
@@ -292,14 +289,14 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		if (!target)
 			return kScriptUnhandled;
 
-		uint32 resetPc = actorReadDword(*target, kActorResetPc);
-		actorWriteDword(*target, kActorCurrentPc, resetPc);
-		actorWriteByte(*target, kActorActive, 1);
-		actorWriteWord(*target, kActorWaitTarget, 0);
-		actorWriteWord(*target, kActorWaitAccum, 0);
-		if (actorReadWord(*target, kActorMoveTicks)) {
-			actorWriteWord(*target, kActorMoveTicks, 0);
-			uint16 completionKey = actorReadWord(*target, kActorCompletionKey);
+		uint32 resetPc = actorReadU32(*target, kActorResetPc);
+		actorWriteU32(*target, kActorCurrentPc, resetPc);
+		actorWriteU8(*target, kActorActive, 1);
+		actorWriteU16(*target, kActorWaitTarget, 0);
+		actorWriteU16(*target, kActorWaitAccum, 0);
+		if (actorReadU16(*target, kActorMoveTicks)) {
+			actorWriteU16(*target, kActorMoveTicks, 0);
+			uint16 completionKey = actorReadU16(*target, kActorCompletionKey);
 			if (completionKey)
 				keyBitSet(completionKey);
 		}
@@ -369,13 +366,13 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			return kScriptUnhandled;
 
 		if (key != 0xFC18)
-			actorWriteWord(*target, kActorTriggerKey, key);
+			actorWriteU16(*target, kActorTriggerKey, key);
 
 		if (triggerPc != 0xFFFFFC18) {
-			actorWriteDword(*target, kActorTriggerPc, triggerPc);
-			actorWriteByte(*target, kActorTriggerFlags, flags);
+			actorWriteU32(*target, kActorTriggerPc, triggerPc);
+			actorWriteU8(*target, kActorTriggerFlags, flags);
 		} else {
-			actorWriteByte(*target, kActorTriggerFlags, (actorReadByte(*target, kActorTriggerFlags) & 1) | flags);
+			actorWriteU8(*target, kActorTriggerFlags, (actorReadU8(*target, kActorTriggerFlags) & 1) | flags);
 		}
 
 		return kScriptContinue;
@@ -482,7 +479,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint32 selector = scriptReadDword(pc + 2);
 		pc += 6;
 		if (target)
-			actorWriteDword(*target, kActorSpriteSelector, (selector + 1) | 0xFF000000);
+			actorWriteU32(*target, kActorSpriteSelector, (selector + 1) | 0xFF000000);
 
 		return kScriptContinue;
 	}
@@ -520,20 +517,11 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			uint16 channel = scriptReadWord(pc);
 			uint16 frame = scriptReadWord(pc + 2);
 			pc += 4;
-			uint32 offset = uint32(_sceneEntryFrameSize) * frame;
-			if (_midiPlyrDriver && channel < COMFY_MIDI_CHANNEL_COUNT && offset + 6 <= _sceneFrameData.size()) {
-				uint16 size = READ_LE_UINT16(&_sceneFrameData[offset + 4]) + 6;
-				if (size <= _sceneFrameData.size() - offset) {
-					_midiPlyrDriver->musicStopSong(1, channel);
-					_midiPlyrDriver->musicPlaySong(&_sceneFrameData[offset], size, channel);
-					_midiPlyrDriver->musicSetVolume(0x64, channel);
-				}
-			}
+			midiPlaySongAtFrame(channel, frame);
 		} else if (subop == 5) {
 			uint16 channel = scriptReadWord(pc);
 			pc += 2;
-			if (_midiPlyrDriver && channel < COMFY_MIDI_CHANNEL_COUNT)
-				_midiPlyrDriver->musicStopSong(1, channel);
+			midiStopSong(channel);
 		}
 
 		return kScriptContinue;
@@ -563,7 +551,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			uint16 animIndex = scriptReadWord(pc);
 			uint16 frameKey = scriptReadWord(pc + 2);
 			pc += 4;
-			animFileLoadFrame(animIndex, frameKey, actorReadWord(actor, kActorSceneHandle));
+			animFileLoadFrame(animIndex, frameKey, actorReadU16(actor, kActorSceneHandle));
 		} else if (subop == 2) {
 			_animVocCounterMode = 1;
 		} else if (subop == 3) {
@@ -728,11 +716,11 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 				return kScriptUnhandled;
 
 			if (moveTo) {
-				x = int16(int32(actorReadDword(*other, kActorXFixed)) >> 12);
-				y = int16(int32(actorReadDword(*other, kActorYFixed)) >> 12);
+				x = int16(int32(actorReadU32(*other, kActorXFixed)) >> 12);
+				y = int16(int32(actorReadU32(*other, kActorYFixed)) >> 12);
 			} else {
-				x = int16(actorReadWord(*other, kActorXFixed)) >> 12;
-				y = int16(actorReadWord(*other, kActorYFixed)) >> 12;
+				x = int16(actorReadU16(*other, kActorXFixed)) >> 12;
+				y = int16(actorReadU16(*other, kActorYFixed)) >> 12;
 			}
 		}
 
@@ -747,8 +735,8 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		int32 dx = int32(x) * 0x1000;
 		int32 dy = int32(y) * 0x1000;
 		if (moveTo) {
-			dx = x == int16(0xFC18) ? 0 : dx - int32(actorReadDword(*target, kActorXFixed));
-			dy = y == int16(0xFC18) ? 0 : dy - int32(actorReadDword(*target, kActorYFixed));
+			dx = x == int16(0xFC18) ? 0 : dx - int32(actorReadU32(*target, kActorXFixed));
+			dy = y == int16(0xFC18) ? 0 : dy - int32(actorReadU32(*target, kActorYFixed));
 		}
 
 		if (opcode == 0x51 || opcode == 0x52 || (moveTo && duration < 0)) {
@@ -763,11 +751,11 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 				duration = 1;
 		}
 
-		actorWriteDword(*target, kActorMoveDx, dx);
-		actorWriteDword(*target, kActorMoveDy, dy);
-		actorWriteWord(*target, kActorMoveTicks, duration);
-		actorWriteByte(*target, kActorBlockingMove, blocking);
-		actorWriteWord(*target, kActorCompletionKey, completionKey);
+		actorWriteU32(*target, kActorMoveDx, dx);
+		actorWriteU32(*target, kActorMoveDy, dy);
+		actorWriteU16(*target, kActorMoveTicks, duration);
+		actorWriteU8(*target, kActorBlockingMove, blocking);
+		actorWriteU16(*target, kActorCompletionKey, completionKey);
 		return blocking && target == &actor ? kScriptYield : kScriptContinue;
 	}
 
@@ -798,17 +786,17 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	if (opcode == 0x72) {
 		uint16 requested = scriptReadStringIndex(pc);
 		pc += 2;
-		uint16 balance = actorReadWord(actor, kActorWaitAccum);
+		uint16 balance = actorReadU16(actor, kActorWaitAccum);
 		if (!requested)
 			balance = 0;
 
 		if (balance) {
 			uint16 step = balance < 5 ? balance : 5;
 			balance = step < uint16(requested - 1) ? step : uint16(requested - 1);
-			actorWriteWord(actor, kActorWaitAccum, actorReadWord(actor, kActorWaitAccum) - balance);
+			actorWriteU16(actor, kActorWaitAccum, actorReadU16(actor, kActorWaitAccum) - balance);
 		}
 
-		actorWriteWord(actor, kActorWaitTarget, requested - balance);
+		actorWriteU16(actor, kActorWaitTarget, requested - balance);
 		return kScriptYield;
 	}
 
@@ -891,7 +879,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	    (opcode >= 0x53 && opcode <= 0x6D) || (opcode >= 0x78 && opcode <= 0x7E)) {
 		Actor *root = actorGet(0);
 		if (root)
-			actorWriteByte(*root, kActorActive, 0);
+			actorWriteU8(*root, kActorActive, 0);
 
 		return kScriptDeactivatedRoot;
 	}
@@ -907,7 +895,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptStep(Actor &actor, uint32 &
 	if (status == kScriptUnhandled)
 		pc = originalPc;
 	else if (status == kScriptYield)
-		actorWriteDword(actor, kActorCurrentPc, pc);
+		actorWriteU32(actor, kActorCurrentPc, pc);
 
 	return status;
 }
diff --git a/engines/comfy/sound.cpp b/engines/comfy/sound.cpp
index f9af4596124..4859eda1bb9 100644
--- a/engines/comfy/sound.cpp
+++ b/engines/comfy/sound.cpp
@@ -68,7 +68,7 @@ bool ComfyEngine::soundInit() {
 		return false;
 
 	_soundCompressed = _vocFileData[1] == 'W';
-	_soundTileStride = READ_LE_UINT16(&_vocFileData[2]);
+	_soundTileStride = assetsReadLe16At(_vocFileData, 2);
 	_soundEventIndex = 0;
 	_soundEventMaximum = 0;
 	_soundEventSubIndex = 0xFFFF;
@@ -88,13 +88,16 @@ void ComfyEngine::soundShutdown() {
 		_midiPlyrDriver->setIncreaseVocCounter(0);
 }
 
-bool ComfyEngine::soundLoadEntry(uint16 index) {
-	uint32 headerOffset = 4 + uint32(index) * 8;
-	if (headerOffset > _vocFileData.size() || 8 > _vocFileData.size() - headerOffset)
-		return false;
+void ComfyEngine::soundHdrReadFromXms(byte *destination, uint16 index, uint16 size) {
+	objHdrReadFromXms(destination, _headerXmsSoundHeadersBase, size, index);
+}
 
-	uint32 size = READ_LE_UINT32(&_vocFileData[headerOffset]);
-	uint32 offset = READ_LE_UINT32(&_vocFileData[headerOffset + 4]);
+bool ComfyEngine::soundLoadEntry(uint16 index) {
+	byte header[8];
+	memset(header, 0, sizeof(header));
+	soundHdrReadFromXms(header, index, sizeof(header));
+	uint32 size = READ_LE_UINT32(header);
+	uint32 offset = READ_LE_UINT32(header + 4);
 	return offset <= _vocFileData.size() && size <= _vocFileData.size() - offset;
 }
 
@@ -102,12 +105,11 @@ bool ComfyEngine::soundDecodeEntry(uint16 index) {
 	_soundPcm.clear();
 	_soundCues.clear();
 	_soundNextCue = 0;
-	uint32 headerOffset = 4 + uint32(index) * 8;
-	if (headerOffset > _vocFileData.size() || 8 > _vocFileData.size() - headerOffset)
-		return false;
-
-	uint32 dataSize = READ_LE_UINT32(&_vocFileData[headerOffset]);
-	uint32 dataOffset = READ_LE_UINT32(&_vocFileData[headerOffset + 4]);
+	byte header[8];
+	memset(header, 0, sizeof(header));
+	soundHdrReadFromXms(header, index, sizeof(header));
+	uint32 dataSize = READ_LE_UINT32(header);
+	uint32 dataOffset = READ_LE_UINT32(header + 4);
 	if (dataOffset > _vocFileData.size() || dataSize > _vocFileData.size() - dataOffset)
 		return false;
 


Commit: e147d24469ea57bc668d87513e25e85802325ba0
    https://github.com/scummvm/scummvm/commit/e147d24469ea57bc668d87513e25e85802325ba0
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Refactoring & fixes

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/anim_file.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/expr.cpp
    engines/comfy/game.cpp
    engines/comfy/metaengine.cpp
    engines/comfy/midiplyr/midiplyr.cpp
    engines/comfy/scene.cpp
    engines/comfy/script_vm.cpp
    engines/comfy/video.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index 821259fa05b..c02ad57a44c 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -463,7 +463,7 @@ void ComfyEngine::actorWriteU8(Actor &actor, uint offset, byte value) {
 		_scriptFault = true;
 }
 
-ComfyEngine::Actor *ComfyEngine::actorGet(uint16 actorIndex) {
+ComfyEngine::Actor *ComfyEngine::actorGetPtr(uint16 actorIndex) {
 	return actorIndex < _actors.size() ? &_actors[actorIndex] : nullptr;
 }
 
@@ -484,34 +484,34 @@ uint16 ComfyEngine::actorGetFrame() {
 
 ComfyEngine::Actor *ComfyEngine::actorResolve(uint16 sceneOrActor, uint16 fallbackActor) {
 	if (!sceneOrActor)
-		return actorGet(fallbackActor);
+		return actorGetPtr(fallbackActor);
 
-	return sceneOrActor < _sceneHandles.size() ? actorGet(_sceneHandles[sceneOrActor]) : nullptr;
+	return actorGetPtr(sceneGetHandle(sceneOrActor));
 }
 
-uint16 ComfyEngine::actorAllocate(uint16 sceneSlot) {
-	Actor *root = actorGet(0);
+uint16 ComfyEngine::actorAlloc(uint16 sceneSlot) {
+	Actor *root = actorGetPtr(0);
 	uint16 actorIndex = root ? actorReadU16(*root, kActorNextLink) : 0;
 	if (!actorIndex || sceneSlot >= _sceneHandles.size())
 		return 0;
 
-	Actor *actor = actorGet(actorIndex);
+	Actor *actor = actorGetPtr(actorIndex);
 	actorWriteU16(*root, kActorNextLink, actorReadU16(*actor, kActorNextLink));
 	_sceneHandles[sceneSlot] = actorIndex;
 	actorWriteU16(*actor, kActorSceneHandle, sceneSlot);
 	return actorIndex;
 }
 
-void ComfyEngine::actorFree(uint16 sceneSlot) {
+void ComfyEngine::actorFreeSlot(uint16 sceneSlot) {
 	if (sceneSlot >= _sceneHandles.size())
 		return;
 
 	uint16 actorIndex = _sceneHandles[sceneSlot];
-	Actor *actor = actorGet(actorIndex);
+	Actor *actor = actorGetPtr(actorIndex);
 	if (!actor)
 		return;
 
-	Actor *root = actorGet(0);
+	Actor *root = actorGetPtr(0);
 	actorWriteU16(*actor, kActorNextLink, root ? actorReadU16(*root, kActorNextLink) : 0);
 	actorWriteU16(*actor, kActorSceneHandle, 0);
 	if (root)
@@ -520,14 +520,14 @@ void ComfyEngine::actorFree(uint16 sceneSlot) {
 }
 
 void ComfyEngine::actorInsertChild(uint16 childIndex, uint16 parentIndex) {
-	Actor *child = actorGet(childIndex);
-	Actor *parent = actorGet(parentIndex);
+	Actor *child = actorGetPtr(childIndex);
+	Actor *parent = actorGetPtr(parentIndex);
 	if (!child || !parent)
 		return;
 
 	uint16 tail = actorReadU16(*parent, kActorChildTail);
 	if (tail) {
-		actorWriteU16(*actorGet(tail), kActorNextLink, childIndex);
+		actorWriteU16(*actorGetPtr(tail), kActorNextLink, childIndex);
 		actorWriteU16(*child, kActorPrevLink, tail);
 	} else {
 		actorWriteU16(*parent, kActorChildHead, childIndex);
@@ -539,14 +539,14 @@ void ComfyEngine::actorInsertChild(uint16 childIndex, uint16 parentIndex) {
 }
 
 void ComfyEngine::actorInsertSibling(uint16 actorIndex, uint16 ownerIndex) {
-	Actor *actor = actorGet(actorIndex);
-	Actor *owner = actorGet(ownerIndex);
+	Actor *actor = actorGetPtr(actorIndex);
+	Actor *owner = actorGetPtr(ownerIndex);
 	if (!actor || !owner)
 		return;
 
 	uint16 head = actorReadU16(*owner, kActorSiblingHead);
 	if (head)
-		actorWriteU16(*actorGet(head), kActorPrevLink, actorIndex);
+		actorWriteU16(*actorGetPtr(head), kActorPrevLink, actorIndex);
 
 	actorWriteU16(*actor, kActorNextLink, head);
 	actorWriteU16(*actor, kActorPrevLink, 0);
@@ -554,23 +554,23 @@ void ComfyEngine::actorInsertSibling(uint16 actorIndex, uint16 ownerIndex) {
 }
 
 void ComfyEngine::actorUnlink(uint16 actorIndex) {
-	Actor *actor = actorGet(actorIndex);
+	Actor *actor = actorGetPtr(actorIndex);
 	if (!actor)
 		return;
 
-	Actor *parent = actorGet(actorReadU16(*actor, kActorParent));
+	Actor *parent = actorGetPtr(actorReadU16(*actor, kActorParent));
 	if (!parent)
 		return;
 
 	uint16 next = actorReadU16(*actor, kActorNextLink);
 	uint16 previous = actorReadU16(*actor, kActorPrevLink);
 	if (next)
-		actorWriteU16(*actorGet(next), kActorPrevLink, previous);
+		actorWriteU16(*actorGetPtr(next), kActorPrevLink, previous);
 	else if (actorReadU16(*parent, kActorChildTail) == actorIndex)
 		actorWriteU16(*parent, kActorChildTail, previous);
 
 	if (previous)
-		actorWriteU16(*actorGet(previous), kActorNextLink, next);
+		actorWriteU16(*actorGetPtr(previous), kActorNextLink, next);
 	else if (actorReadU16(*parent, kActorSiblingHead) == actorIndex)
 		actorWriteU16(*parent, kActorSiblingHead, next);
 	else
@@ -579,8 +579,8 @@ void ComfyEngine::actorUnlink(uint16 actorIndex) {
 
 uint16 ComfyEngine::actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible, byte active,
 		uint32 pc, int16 x, int16 y, int16 sprite, byte insertAsChild) {
-	uint16 actorIndex = actorAllocate(sceneSlot);
-	Actor *actor = actorGet(actorIndex);
+	uint16 actorIndex = actorAlloc(sceneSlot);
+	Actor *actor = actorGetPtr(actorIndex);
 	if (!actor)
 		return 8;
 
@@ -595,7 +595,7 @@ uint16 ComfyEngine::actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible,
 	actorWriteU8(*actor, kActorDirty, 1);
 
 	if (parentSlot) {
-		uint16 parentIndex = parentSlot < _sceneHandles.size() ? _sceneHandles[parentSlot] : 0;
+		uint16 parentIndex = sceneGetHandle(parentSlot);
 		actorWriteU16(*actor, kActorParent, parentIndex);
 		if (insertAsChild)
 			actorInsertChild(actorIndex, parentIndex);
@@ -669,13 +669,13 @@ void ComfyEngine::actorFreePcChain(Actor &actor) {
 }
 
 void ComfyEngine::actorFreeTree(uint16 actorIndex) {
-	Actor *actor = actorGet(actorIndex);
+	Actor *actor = actorGetPtr(actorIndex);
 	if (!actor)
 		return;
 
 	uint16 child = actorReadU16(*actor, kActorSiblingHead);
 	while (child) {
-		Actor *childActor = actorGet(child);
+		Actor *childActor = actorGetPtr(child);
 		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		actorFreeTree(child);
 		child = next;
@@ -683,7 +683,7 @@ void ComfyEngine::actorFreeTree(uint16 actorIndex) {
 
 	child = actorReadU16(*actor, kActorChildHead);
 	while (child) {
-		Actor *childActor = actorGet(child);
+		Actor *childActor = actorGetPtr(child);
 		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		actorFreeTree(child);
 		child = next;
@@ -691,18 +691,18 @@ void ComfyEngine::actorFreeTree(uint16 actorIndex) {
 
 	uint16 sceneSlot = actorReadU16(*actor, kActorSceneHandle);
 	actorFreePcChain(*actor);
-	actorFree(sceneSlot);
+	actorFreeSlot(sceneSlot);
 }
 
 void ComfyEngine::actorClearDirtyTree(uint16 actorIndex) {
-	Actor *actor = actorGet(actorIndex);
+	Actor *actor = actorGetPtr(actorIndex);
 	if (!actor)
 		return;
 
 	actorWriteU8(*actor, kActorDirty, 0);
 	uint16 child = actorReadU16(*actor, kActorSiblingHead);
 	while (child) {
-		Actor *childActor = actorGet(child);
+		Actor *childActor = actorGetPtr(child);
 		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		actorClearDirtyTree(child);
 		child = next;
@@ -710,7 +710,7 @@ void ComfyEngine::actorClearDirtyTree(uint16 actorIndex) {
 
 	child = actorReadU16(*actor, kActorChildHead);
 	while (child) {
-		Actor *childActor = actorGet(child);
+		Actor *childActor = actorGetPtr(child);
 		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		actorClearDirtyTree(child);
 		child = next;
@@ -723,7 +723,7 @@ void ComfyEngine::actorSetAllVisible() {
 }
 
 bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
-	Actor *actor = actorGet(actorIndex);
+	Actor *actor = actorGetPtr(actorIndex);
 	descendChildren = false;
 	if (!actor)
 		return false;
@@ -830,7 +830,7 @@ bool ComfyEngine::actorTickTree(uint16 actorIndex) {
 	if (_pendingScene)
 		return false;
 
-	Actor *actor = actorGet(actorIndex);
+	Actor *actor = actorGetPtr(actorIndex);
 	if (!actor)
 		return false;
 
@@ -841,30 +841,30 @@ bool ComfyEngine::actorTickTree(uint16 actorIndex) {
 
 	bool descendChildren = true;
 	bool stopBranch = actorRunScript(actorIndex, descendChildren);
-	actor = actorGet(actorIndex);
+	actor = actorGetPtr(actorIndex);
 	if (stopBranch || !descendChildren || !actor)
 		return stopBranch;
 
 	uint16 child = actorReadU16(*actor, kActorSiblingHead);
 	while (child) {
-		Actor *childActor = actorGet(child);
+		Actor *childActor = actorGetPtr(child);
 		uint16 savedNext = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		if (actorTickTree(child))
 			child = savedNext;
 		else {
-			childActor = actorGet(child);
+			childActor = actorGetPtr(child);
 			child = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		}
 	}
 
 	child = actorReadU16(*actor, kActorChildHead);
 	while (child) {
-		Actor *childActor = actorGet(child);
+		Actor *childActor = actorGetPtr(child);
 		uint16 savedNext = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		if (actorTickTree(child))
 			child = savedNext;
 		else {
-			childActor = actorGet(child);
+			childActor = actorGetPtr(child);
 			child = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		}
 	}
@@ -875,7 +875,7 @@ bool ComfyEngine::actorTickTree(uint16 actorIndex) {
 void ComfyEngine::actorDrawList(uint16 actorIndex, int16 x, int16 y) {
 	while (actorIndex) {
 		actorDraw(actorIndex, x, y);
-		Actor *actor = actorGet(actorIndex);
+		Actor *actor = actorGetPtr(actorIndex);
 		actorIndex = actor ? actorReadU16(*actor, kActorNextLink) : 0;
 	}
 }
@@ -931,7 +931,7 @@ void ComfyEngine::actorWriteCachedRect(Actor &actor, VideoRectRecord rect) {
 }
 
 void ComfyEngine::actorInvalidateDrawTree(uint16 actorIndex) {
-	Actor *actor = actorGet(actorIndex);
+	Actor *actor = actorGetPtr(actorIndex);
 	if (!actor)
 		return;
 
@@ -945,7 +945,7 @@ void ComfyEngine::actorInvalidateDrawTree(uint16 actorIndex) {
 	actorWriteCachedRect(*actor, empty);
 	uint16 child = actorReadU16(*actor, kActorSiblingHead);
 	while (child) {
-		Actor *childActor = actorGet(child);
+		Actor *childActor = actorGetPtr(child);
 		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		actorInvalidateDrawTree(child);
 		child = next;
@@ -953,7 +953,7 @@ void ComfyEngine::actorInvalidateDrawTree(uint16 actorIndex) {
 
 	child = actorReadU16(*actor, kActorChildHead);
 	while (child) {
-		Actor *childActor = actorGet(child);
+		Actor *childActor = actorGetPtr(child);
 		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
 		actorInvalidateDrawTree(child);
 		child = next;
@@ -961,7 +961,7 @@ void ComfyEngine::actorInvalidateDrawTree(uint16 actorIndex) {
 }
 
 bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
-	Actor *actor = actorGet(actorIndex);
+	Actor *actor = actorGetPtr(actorIndex);
 	if (!actor)
 		return true;
 
diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
index d39addf6c7c..3ce3353960e 100644
--- a/engines/comfy/anim_file.cpp
+++ b/engines/comfy/anim_file.cpp
@@ -62,7 +62,7 @@ void ComfyEngine::animFileShutdown(bool closeFile) {
 			keyBitSet(_animCurrentFrameKey);
 
 		if (_animCurrentActorSceneHandle < _sceneHandles.size()) {
-			Actor *actor = actorGet(_sceneHandles[_animCurrentActorSceneHandle]);
+			Actor *actor = actorGetPtr(sceneGetHandle(_animCurrentActorSceneHandle));
 			if (actor)
 				actorWriteU32(*actor, kActorSpriteSelector, 0);
 		}
@@ -116,7 +116,7 @@ void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 ac
 	_animVocDeltaA = 0;
 	_animActive = true;
 	if (actorSceneHandle < _sceneHandles.size()) {
-		Actor *actor = actorGet(_sceneHandles[actorSceneHandle]);
+		Actor *actor = actorGetPtr(sceneGetHandle(actorSceneHandle));
 		if (actor)
 			actorWriteU32(*actor, kActorSpriteSelector, 0x00FFFFFF);
 	}
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 4a3341945c3..0295ff4d8cd 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -93,7 +93,7 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Eng
 	_animPantherFormat(false), _animActive(false),
 	_exprStackTop(0), _scriptFault(false),
 	_gameInitialized(false), _videoInitialized(false),
-	_timerInitialized(false), _lptKeyboardInitialized(false), _mainLoopRunning(false) {
+	_timerInitialized(false), _lptKeyboardInitialized(false) {
 	memset(_paletteFadeSource, 0, sizeof(_paletteFadeSource));
 	memset(_paletteTarget, 0, sizeof(_paletteTarget));
 	memset(_paletteDisplay, 0, sizeof(_paletteDisplay));
@@ -124,13 +124,21 @@ Common::String ComfyEngine::getGameId() const {
 
 Common::Error ComfyEngine::run() {
 	setDebugger(new Console());
+	return gameInit();
+}
+
+Common::Error ComfyEngine::gameInit() {
+	if (_gameInitialized)
+		return Common::kNoError;
 
-	Common::Error result = gameInit();
-	if (result.getCode() != Common::kNoError)
-		return result;
+	gameConfigInit();
+	if (!iniReadGameConfig())
+		return Common::kNoGameDataFoundError;
 
+	timerInit();
+	_gameInitialized = true;
 	uint16 currentScene = _language;
-	uint16 chooserScene = currentScene;
+	uint16 chooserScene = 2;
 	if (_multiLanguage && (ConfMan.getBool("force_language_setup") ||
 			!ConfMan.getBool("comfy_language_chosen"))) {
 		if (!iniGetGameDataPath(0x63)) {
@@ -149,8 +157,13 @@ Common::Error ComfyEngine::run() {
 		ConfMan.flushToDisk();
 	}
 
-	if (iniGetGameDataPath(0))
+	if (iniGetGameDataPath(0)) {
 		sceneRun(currentScene, false, true);
+		if (shouldQuit()) {
+			gameShutdown();
+			return Common::kNoError;
+		}
+	}
 
 	while (currentScene && !shouldQuit()) {
 		if (!iniGetGameDataPath(currentScene)) {
@@ -173,25 +186,12 @@ Common::Error ComfyEngine::run() {
 	return Common::kNoError;
 }
 
-Common::Error ComfyEngine::gameInit() {
-	if (_gameInitialized)
-		return Common::kNoError;
-
-	gameConfigInit();
-	if (!iniReadGameConfig())
-		return Common::kNoGameDataFoundError;
-
-	videoInit();
-	timerInit();
-	_gameInitialized = true;
-	return Common::kNoError;
-}
-
 void ComfyEngine::gameShutdown() {
-	if (_lptKeyboardInitialized)
+	if (_lptKeyboardInitialized) {
 		lptKeyboardShutdown();
-
-	assetsUnload(1);
+		midiShutdown();
+		assetsUnload(0);
+	}
 
 	midiPlyrStop();
 
@@ -199,9 +199,8 @@ void ComfyEngine::gameShutdown() {
 		timerShutdown();
 
 	if (_videoInitialized)
-		videoShutdown();
+		videoShutdown(0);
 
-	_mainLoopRunning = false;
 	_gameInitialized = false;
 }
 
@@ -222,22 +221,26 @@ uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
 	memset(&sceneRunBuffer[0], 0, sceneRunBuffer.size());
 	if (!assetsLoad(0x4000, &sceneRunBuffer[0])) {
 		assetsUnload(0);
+		if (_videoInitialized)
+			videoShutdown(0);
+
 		return 0;
 	}
 
 	gameMainLoop(sceneId);
 	uint16 nextScene = 0;
-	if (checkNext && _activeSceneCount > 1 && _midiHandles.size() > 1)
+	if (checkNext && sceneGetActiveCount() > 1 && _midiHandles.size() > 1)
 		nextScene = _midiHandles[1];
 
 	if (nextScene == sceneId || int16(nextScene) <= 0 || int16(nextScene) >= 0x65)
 		nextScene = 0;
 
+	byte restorePalette = !exitFlag && !nextScene;
+
 	midiShutdown();
 	assetsUnload(0);
 	inputQueueReset();
-	if (!exitFlag && nextScene)
-		renderSetDirty();
+	videoShutdown(restorePalette);
 
 	return nextScene;
 }
@@ -289,12 +292,12 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 	keyBitSet(2);
 	lptKeyboardInit();
 
-	uint16 rootIndex = _sceneHandles.size() > 1 ? _sceneHandles[1] : 0;
-	Actor *mainLoopActor = actorGet(rootIndex);
+	uint16 rootIndex = sceneGetHandle(1);
+	Actor *mainLoopActor = actorGetPtr(rootIndex);
 	paletteLoadWithFade(0, 0);
 	paletteVsyncFlip();
 	paletteVsyncFlip();
-	if (_activeSceneCount && _midiHandles.size() > 1)
+	if (sceneGetActiveCount() && _midiHandles.size() > 1)
 		_midiHandles[1] += argument;
 
 	while (keepRunning && !shouldQuit()) {
@@ -383,8 +386,8 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 		}
 	}
 
-	if (_sceneHandles.size() > 1 && _sceneHandles[1])
-		actorFree(1);
+	if (sceneGetHandle(1))
+		actorFreeSlot(1);
 
 	lptKeyboardShutdown();
 	sceneBlockPackRuntimeState();
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 3ec724800b1..2fcc92af5e8 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -30,11 +30,9 @@
 #include "common/hash-str.h"
 #include "common/keyboard.h"
 #include "common/random.h"
-#include "common/serializer.h"
 #include "common/array.h"
 #include "common/util.h"
 #include "engines/engine.h"
-#include "engines/savestate.h"
 #include "graphics/screen.h"
 #include "audio/mixer.h"
 
@@ -417,7 +415,6 @@ private:
 	bool _videoInitialized;
 	bool _timerInitialized;
 	bool _lptKeyboardInitialized;
-	bool _mainLoopRunning;
 
 	Common::Error gameInit();
 	void gameShutdown();
@@ -431,7 +428,7 @@ private:
 	Common::Path pathBuild(const Common::Path &filename, bool useGamePath);
 	Common::SeekableReadStream *pathFOpen(const Common::Path &filename, bool useGamePath);
 	void videoInit();
-	void videoShutdown();
+	void videoShutdown(byte restorePalette);
 	void videoSetResolution();
 	void videoFindBestMode(VideoRectRecord record);
 	void videoPresentFrame();
@@ -511,6 +508,8 @@ private:
 	byte *spriteLoadFromFile(uint16 fileOffset, uint16 index);
 	void sceneBlockPackRuntimeState();
 	void sceneBlockUnpackRuntimeState();
+	uint16 sceneGetHandle(uint16 sceneIndex);
+	uint16 sceneGetActiveCount();
 	bool envXmsToConv(byte *destination, uint16 index);
 	void envConvToXms(byte *source, uint16 index);
 	void sceneGoto(uint16 count);
@@ -532,12 +531,12 @@ private:
 	void actorWriteU16(Actor &actor, uint offset, uint16 value);
 	void actorWriteU8(Actor &actor, uint offset, byte value);
 	Actor *rootActor();
-	Actor *actorGet(uint16 actorIndex);
+	Actor *actorGetPtr(uint16 actorIndex);
 	void actorSetFrame(int16 frame);
 	uint16 actorGetFrame();
 	Actor *actorResolve(uint16 sceneOrActor, uint16 fallbackActor);
-	uint16 actorAllocate(uint16 sceneSlot);
-	void actorFree(uint16 sceneSlot);
+	uint16 actorAlloc(uint16 sceneSlot);
+	void actorFreeSlot(uint16 sceneSlot);
 	void actorInsertChild(uint16 childIndex, uint16 parentIndex);
 	void actorInsertSibling(uint16 actorIndex, uint16 ownerIndex);
 	void actorUnlink(uint16 actorIndex);
@@ -643,12 +642,6 @@ public:
 		return (f == kSupportsReturnToLauncher);
 	};
 
-	bool canLoadGameStateCurrently(Common::U32String *msg = nullptr) override {
-		return false;
-	}
-	bool canSaveGameStateCurrently(Common::U32String *msg = nullptr) override {
-		return false;
-	}
 };
 
 extern ComfyEngine *g_engine;
diff --git a/engines/comfy/expr.cpp b/engines/comfy/expr.cpp
index 688ebf5a4f1..0a276828ec7 100644
--- a/engines/comfy/expr.cpp
+++ b/engines/comfy/expr.cpp
@@ -68,7 +68,7 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 				uint offset = opcode == 0x12 ? kActorXFixed : kActorYFixed;
 				int32 position = actorReadU32(*actor, offset);
 				while (actorReadU16(*actor, kActorParent)) {
-					actor = actorGet(actorReadU16(*actor, kActorParent));
+					actor = actorGetPtr(actorReadU16(*actor, kActorParent));
 					if (!actor)
 						break;
 
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index 76d1bcd258b..a2b6947d71a 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -429,6 +429,8 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	if (!_headerXmsData.empty())
 		memset(&_headerXmsData[0], 0, _headerXmsData.size());
 
+	videoInit();
+
 	_objectCacheEntries.resize(_spriteHeaders.size());
 	_frameCacheEntries.resize(_numFrames + 1);
 	if (!_objectCacheEntries.empty())
diff --git a/engines/comfy/metaengine.cpp b/engines/comfy/metaengine.cpp
index 4046a9302d0..3fa84479f17 100644
--- a/engines/comfy/metaengine.cpp
+++ b/engines/comfy/metaengine.cpp
@@ -60,9 +60,8 @@ Common::Error ComfyMetaEngine::createInstance(OSystem *syst, Engine **engine, co
 	return Common::kNoError;
 }
 
-bool ComfyMetaEngine::hasFeature(MetaEngineFeature f) const {
-	return checkExtendedSaves(f) ||
-		(f == kSupportsLoadingDuringStartup);
+bool ComfyMetaEngine::hasFeature(MetaEngineFeature) const {
+	return false;
 }
 
 Common::KeymapArray ComfyMetaEngine::initKeymaps(const char *target) const {
diff --git a/engines/comfy/midiplyr/midiplyr.cpp b/engines/comfy/midiplyr/midiplyr.cpp
index 2a205ccc528..7fbd49ce8ed 100644
--- a/engines/comfy/midiplyr/midiplyr.cpp
+++ b/engines/comfy/midiplyr/midiplyr.cpp
@@ -829,7 +829,7 @@ void MidiPlyrDriver::comfyboardPollTimer() {
 	if (_driverVersion != kDriverVersion2 || _comfyboardStopReading)
 		return;
 
-	// TODO: Reroute to actual LPT emulated parser...
+	// The original exports this state to the physical Comfyboard through LPT...
 }
 
 } // End of namespace Comfy
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index 524202aa885..acd5a76ffe0 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -25,6 +25,14 @@
 
 namespace Comfy {
 
+uint16 ComfyEngine::sceneGetHandle(uint16 sceneIndex) {
+	return sceneIndex < _sceneHandles.size() ? _sceneHandles[sceneIndex] : 0;
+}
+
+uint16 ComfyEngine::sceneGetActiveCount() {
+	return _activeSceneCount;
+}
+
 void ComfyEngine::sceneBlockPackRuntimeState() {
 	if (_sceneMemoryBlock.empty())
 		return;
@@ -104,11 +112,11 @@ void ComfyEngine::envConvToXms(byte *source, uint16 index) {
 
 bool ComfyEngine::envXmsToConv(byte *destination, uint16 index) {
 	if (!index || _sceneMemoryBlock.empty())
-		return false;
+		return true;
 
 	uint32 offset = uint32(index - 1) * _sceneMemoryBlock.size();
 	if (offset > _environmentData.size() || _sceneMemoryBlock.size() > _environmentData.size() - offset)
-		return false;
+		return true;
 
 	memcpy(destination, &_environmentData[offset], _sceneMemoryBlock.size());
 	sceneBlockUnpackRuntimeState();
@@ -212,7 +220,7 @@ void ComfyEngine::sceneStartWithMusic(uint16 scene) {
 	if (!_musicEnabled)
 		midiStopAll();
 
-	Actor *root = actorGet(0);
+	Actor *root = actorGetPtr(0);
 	if (root) {
 		paletteLoadWithFade(actorReadU16(*root, kActorXFixed), 0);
 		if (actorReadU32(*root, kActorYFixed))
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 06d4367e736..1ab1800a5c9 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -823,7 +823,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			uint16 argument = scriptReadWord(pc);
 			pc += 2;
 			if (kind == 1)
-				condition = argument < _sceneHandles.size() && _sceneHandles[argument];
+				condition = sceneGetHandle(argument) != 0;
 			else if (kind == 2)
 				condition = _inputDeviceMode == 1;
 			else if (kind == 14) {
@@ -838,7 +838,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			}
 		} else if (kind == 1) {
 			uint16 scene = scriptReadWord(pc);
-			condition = scene < _sceneHandles.size() && _sceneHandles[scene];
+			condition = sceneGetHandle(scene) != 0;
 			pc += 2;
 		}
 
@@ -877,7 +877,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 	if (!opcode || opcode > 0x7F || opcode == 0x27 || (opcode >= 0x30 && opcode <= 0x4F) ||
 	    (opcode >= 0x53 && opcode <= 0x6D) || (opcode >= 0x78 && opcode <= 0x7E)) {
-		Actor *root = actorGet(0);
+		Actor *root = actorGetPtr(0);
 		if (root)
 			actorWriteU8(*root, kActorActive, 0);
 
diff --git a/engines/comfy/video.cpp b/engines/comfy/video.cpp
index f38dbcc3677..1cd1ea72ffa 100644
--- a/engines/comfy/video.cpp
+++ b/engines/comfy/video.cpp
@@ -44,7 +44,10 @@ void ComfyEngine::videoInit() {
 	_videoInitialized = true;
 }
 
-void ComfyEngine::videoShutdown() {
+void ComfyEngine::videoShutdown(byte restorePalette) {
+	if (restorePalette)
+		paletteRealize(nullptr);
+
 	colorDatClose();
 	delete[] _presentBuffer;
 	_presentBuffer = nullptr;


Commit: 4fe32750749ef7fef090e46cb8b7466c6a1fe7c2
    https://github.com/scummvm/scummvm/commit/4fe32750749ef7fef090e46cb8b7466c6a1fe7c2
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Add COMFYBOARD driver handling

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/game.cpp
    engines/comfy/input.cpp
    engines/comfy/midiplyr/midiplyr.cpp
    engines/comfy/midiplyr/midiplyr.h


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 0295ff4d8cd..3f2018321d6 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -65,6 +65,8 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Eng
 	_keyboardMapLoaded(false), _keyboardActiveMask(0), _keyboardLatchedMask(0),
 	_keymapperActiveMask(0), _keymapperLatchedMask(0), _toyKeyboardActiveMask(0),
 	_toyKeyboardLatchedMask(0), _toyKeyboardHoldMask(0), _lptPrevScanState(0), _inputDeviceMode(0),
+	_inputDevicePreference(0), _inputPreviousComfyboardState(0), _inputPreviousKeyboardState(0),
+	_inputComfyboardActivityCount(0), _inputKeyboardActivityCount(0),
 	_keyboardUiInitialized(false), _keyboardUiVisible(true),
 	_stringCount(0), _sceneCount(0), _keyBitCount(0), _resourceHandleCount(0), _midiEntryCount(0),
 	_picDataSize(0), _usesAnimFile(false), _sceneOpen(false), _sceneEntryListActive(false),
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 2fcc92af5e8..cec26a72580 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -283,6 +283,11 @@ private:
 	uint32 _toyKeyboardHoldMask;
 	uint32 _lptPrevScanState;
 	uint16 _inputDeviceMode;
+	uint16 _inputDevicePreference;
+	uint32 _inputPreviousComfyboardState;
+	uint32 _inputPreviousKeyboardState;
+	uint16 _inputComfyboardActivityCount;
+	uint16 _inputKeyboardActivityCount;
 	bool _keyboardUiInitialized;
 	bool _keyboardUiVisible;
 	Common::Array<byte> _comfyObjData;
@@ -470,6 +475,7 @@ private:
 	void hostKeyboardSetKeyState(uint16 key, bool pressed);
 	uint16 hostKeyboardVirtualKey(Common::KeyCode key);
 	uint32 lptKeyboardScan();
+	uint16 inputDetectDevice(uint32 comfyboardState, uint32 keyboardState);
 	void lptKeyboardDispatchEvents(uint32 scanState);
 	void setKeyboardContact(uint16 contact, bool pressed, bool keymapper);
 	bool readAssetFile(const Common::Path &filename, Common::Array<byte> &data);
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index a2b6947d71a..ad6431f3f2b 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -152,6 +152,8 @@ bool ComfyEngine::iniReadGameConfig() {
 	if (_inputDeviceMode > 2)
 		_inputDeviceMode = 0;
 
+	_inputDevicePreference = _inputDeviceMode;
+
 	return !_gameDirectory.empty();
 }
 
diff --git a/engines/comfy/input.cpp b/engines/comfy/input.cpp
index b1fafb0f882..935779c217f 100644
--- a/engines/comfy/input.cpp
+++ b/engines/comfy/input.cpp
@@ -212,12 +212,27 @@ uint32 ComfyEngine::lptKeyboardScan() {
 	// iterations after each write, and sampled three bits from the status port. Concatenating those
 	// eight 3-bit samples produced the 24-contact scan word. ScummVM supplies that same word from the
 	// keymapper, KEYBOARD.DAT mappings, and the toy-keyboard UI instead of accessing an I/O port.
-	uint32 keyboardReleased = (_keyboardLatchedMask | _keymapperLatchedMask) & 0x00FFFFFF;
-	uint32 keyboardState = (_keyboardActiveMask | _keymapperActiveMask | keyboardReleased) & 0x00FFFFFF;
+	uint32 keyboardState = (_keyboardActiveMask | _keyboardLatchedMask) & 0x00FFFFFF;
 	uint32 comfyboardState = (_toyKeyboardActiveMask | _toyKeyboardHoldMask |
 		_toyKeyboardLatchedMask) & 0x00FFFFFF;
-	if (_midiPlyrDriver)
+	uint32 comfyboardHostState = (comfyboardState | _keymapperActiveMask | _keymapperLatchedMask) & 0x00FFFFFF;
+	if (_engineVersion == kEngineVersion3 && _midiPlyrDriver) {
+		_midiPlyrDriver->comfyboardSetHostButtons(comfyboardHostState);
 		comfyboardState |= _midiPlyrDriver->comfyboardGetButtons() & 0x00FFFFFF;
+	}
+
+	if (_engineVersion != kEngineVersion3 || _inputDeviceMode != 1)
+		keyboardState |= _keymapperActiveMask | _keymapperLatchedMask;
+
+	if (_engineVersion == kEngineVersion3 && !_inputDeviceMode) {
+		_inputDeviceMode = inputDetectDevice(comfyboardState, keyboardState);
+		if (_inputDeviceMode == 1 && _midiPlyrDriver) {
+			_midiPlyrDriver->comfyboardStopSleepUse();
+		} else if (_inputDeviceMode == 2 && _midiPlyrDriver) {
+			_midiPlyrDriver->comfyboardStopReading();
+			_midiPlyrDriver->comfyboardStopSleepUse();
+		}
+	}
 
 	uint32 scanState;
 	if (_engineVersion == kEngineVersion3 && _inputDeviceMode == 1)
@@ -236,6 +251,58 @@ uint32 ComfyEngine::lptKeyboardScan() {
 	return scanState;
 }
 
+uint16 ComfyEngine::inputDetectDevice(uint32 comfyboardState, uint32 keyboardState) {
+	uint32 previousComfyboardState = _inputPreviousComfyboardState;
+	uint32 previousKeyboardState = _inputPreviousKeyboardState;
+	uint32 filteredComfyboardState = comfyboardState & 0x00FFDF7D;
+	uint32 filteredKeyboardState = keyboardState & 0x00FFDFFD;
+	uint16 activeCount = 0;
+
+	for (uint bit = 0; bit < COMFY_KEYBOARD_CONTACT_COUNT; bit++) {
+		if (filteredComfyboardState & (1 << bit))
+			activeCount++;
+	}
+
+	if (activeCount > 6)
+		filteredComfyboardState = previousComfyboardState;
+
+	activeCount = 0;
+	for (uint bit = 0; bit < COMFY_KEYBOARD_CONTACT_COUNT; bit++) {
+		if (filteredKeyboardState & (1 << bit))
+			activeCount++;
+	}
+
+	if (activeCount > 6)
+		filteredKeyboardState = previousKeyboardState;
+
+	_inputPreviousComfyboardState = filteredComfyboardState;
+	_inputPreviousKeyboardState = filteredKeyboardState;
+	uint32 comfyboardPressed = (filteredComfyboardState ^ previousComfyboardState) & filteredComfyboardState;
+	uint32 keyboardPressed = (filteredKeyboardState ^ previousKeyboardState) & filteredKeyboardState;
+	if (!_inputKeyboardActivityCount && (keyboardPressed & 0x80) && !(comfyboardState & 0x80))
+		return 2;
+
+	keyboardPressed &= ~0x80;
+	if (comfyboardPressed)
+		_inputComfyboardActivityCount++;
+
+	if (keyboardPressed)
+		_inputKeyboardActivityCount++;
+
+	if (_inputDevicePreference == 2)
+		return 2;
+
+	if (_inputDevicePreference <= 1) {
+		if (_inputComfyboardActivityCount > 1)
+			return 1;
+
+		if (_inputKeyboardActivityCount > 1)
+			return 2;
+	}
+
+	return 0;
+}
+
 void ComfyEngine::lptKeyboardDispatchEvents(uint32 scanState) {
 	keyBitCopyRange(8, 0x18, scanState);
 
@@ -282,13 +349,18 @@ void ComfyEngine::lptKeyboardInit() {
 	inputQueueReset();
 	hostKeyboardLoadDatMap();
 	_lptPrevScanState = 0;
+	_inputDeviceMode = _inputDevicePreference;
+	_inputPreviousComfyboardState = 0;
+	_inputPreviousKeyboardState = 0;
+	_inputComfyboardActivityCount = 0;
+	_inputKeyboardActivityCount = 0;
 	_lptKeyboardInitialized = true;
 	_keyboardUiVisible = true;
-	if (_midiPlyrDriver) {
-		if (_engineVersion == kEngineVersion3 && !_inputDeviceMode)
+	if (_engineVersion == kEngineVersion3 && _midiPlyrDriver) {
+		if (!_inputDeviceMode)
 			_midiPlyrDriver->comfyboardStartSleepUse();
 
-		_midiPlyrDriver->comfyboardStartReading(0x006D96DB, 0);
+		_midiPlyrDriver->comfyboardStartReading(0x006D96DB, 0x0378);
 	}
 
 #ifdef USE_IMGUI
@@ -313,7 +385,7 @@ void ComfyEngine::lptKeyboardShutdown() {
 #endif
 
 	_keyboardUiInitialized = false;
-	if (_midiPlyrDriver) {
+	if (_engineVersion == kEngineVersion3 && _midiPlyrDriver) {
 		_midiPlyrDriver->comfyboardStopReading();
 		_midiPlyrDriver->comfyboardStopSleepUse();
 	}
diff --git a/engines/comfy/midiplyr/midiplyr.cpp b/engines/comfy/midiplyr/midiplyr.cpp
index 7fbd49ce8ed..aa00e2ba754 100644
--- a/engines/comfy/midiplyr/midiplyr.cpp
+++ b/engines/comfy/midiplyr/midiplyr.cpp
@@ -50,6 +50,7 @@ void MidiPlyrDriver::resetState() {
 	_comfyboardStopReading = 1;
 	_comfyboardSampleIndex = 0;
 	_comfyboardButtons = 0;
+	_comfyboardHostButtons = 0;
 	_comfyboardSleepUseStopped = 1;
 	_comfyboardPort = 0;
 	_comfyboardXorMask = 0;
@@ -799,11 +800,17 @@ uint32 MidiPlyrDriver::comfyboardGetButtons() const {
 	return _comfyboardButtons;
 }
 
+void MidiPlyrDriver::comfyboardSetHostButtons(uint32 buttons) {
+	Common::StackLock lock(_mutex);
+	_comfyboardHostButtons = buttons & 0x00FFFFFF;
+}
+
 void MidiPlyrDriver::comfyboardStartReading(uint32 xorMask, uint16 port) {
 	Common::StackLock lock(_mutex);
 	_comfyboardPort = port;
 	_comfyboardXorMask = xorMask;
 	_comfyboardButtons = 0;
+	_comfyboardHostButtons = 0;
 	_comfyboardSampleIndex = 0;
 	_comfyboardStopReading = 0;
 }
@@ -813,6 +820,7 @@ void MidiPlyrDriver::comfyboardStopReading() {
 	_comfyboardStopReading = 1;
 	_comfyboardSampleIndex = 0;
 	_comfyboardButtons = 0;
+	_comfyboardHostButtons = 0;
 }
 
 void MidiPlyrDriver::comfyboardStartSleepUse() {
@@ -829,7 +837,34 @@ void MidiPlyrDriver::comfyboardPollTimer() {
 	if (_driverVersion != kDriverVersion2 || _comfyboardStopReading)
 		return;
 
-	// The original exports this state to the physical Comfyboard through LPT...
+	if (!_comfyboardSleepUseStopped && !_comfyboardSampleIndex) {
+		// The original saves the LPT control byte, writes 0x0C to port + 2, and writes 1 to the data port.
+		_comfyboardSavedControl = 0;
+	}
+
+	if (_comfyboardSampleIndex) {
+		uint16 sampleIndex = _comfyboardSampleIndex - 1;
+		uint32 rawButtons = _comfyboardHostButtons ^ _comfyboardXorMask;
+		byte bits = (rawButtons >> ((7 - sampleIndex) * 3)) & 7;
+		_comfyboardSamples[sampleIndex] = ((bits & 4) << 5) | ((bits & 3) << 4);
+	}
+
+	if (_comfyboardSampleIndex >= ARRAYSIZE(_comfyboardSamples)) {
+		_comfyboardSampleIndex = 0;
+		uint32 packedButtons = 0;
+
+		for (uint i = 0; i < ARRAYSIZE(_comfyboardSamples); i++) {
+			uint16 sample = _comfyboardSamples[i];
+			uint16 bits = ((sample & 0x80) >> 5) | ((sample & 0x30) >> 4);
+			packedButtons = (packedButtons << 3) | bits;
+		}
+
+		_comfyboardButtons = packedButtons ^ _comfyboardXorMask;
+		return;
+	}
+
+	// The original writes ((_comfyboardSampleIndex << 1) | 1) to the LPT data port here.
+	_comfyboardSampleIndex++;
 }
 
 } // End of namespace Comfy
diff --git a/engines/comfy/midiplyr/midiplyr.h b/engines/comfy/midiplyr/midiplyr.h
index 3b59f91a064..27ec69b1c19 100644
--- a/engines/comfy/midiplyr/midiplyr.h
+++ b/engines/comfy/midiplyr/midiplyr.h
@@ -77,6 +77,7 @@ public:
 	void vocSrUpdateCounters();
 
 	uint32 comfyboardGetButtons() const;
+	void comfyboardSetHostButtons(uint32 buttons);
 	void comfyboardStartReading(uint32 xorMask, uint16 port);
 	void comfyboardStopReading();
 	void comfyboardStartSleepUse();
@@ -166,6 +167,7 @@ private:
 	byte _comfyboardStopReading;
 	uint16 _comfyboardSampleIndex;
 	uint32 _comfyboardButtons;
+	uint32 _comfyboardHostButtons;
 	byte _comfyboardSleepUseStopped;
 	uint16 _comfyboardPort;
 	uint32 _comfyboardXorMask;


Commit: f374a7b85504ace9d684e1d6ac365e008ed56ac4
    https://github.com/scummvm/scummvm/commit/f374a7b85504ace9d684e1d6ac365e008ed56ac4
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Clean up

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/game.cpp
    engines/comfy/midi.cpp
    engines/comfy/midiplyr/midiplyr.cpp
    engines/comfy/midiplyr/midiplyr.h


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index c02ad57a44c..31567e84bfa 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -239,7 +239,7 @@ void ComfyEngine::spriteCache(int16 spriteId) {
 		WRITE_LE_UINT16(entryData + 2, slotSize);
 		memcpy(entryData + 0x0C, &_comfyObjData[fileOffset], size);
 		_frameSpriteResource.id = spriteId;
-		memset(&_frameSpriteResource.header, 0, sizeof(_frameSpriteResource.header));
+		_frameSpriteResource.header = SpriteObjectHeader();
 		_frameSpriteResource.header.dataSize = size;
 		_frameSpriteResource.header.tiledSize = size;
 		_frameSpriteResource.pixels.resize(size);
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 3f2018321d6..98b1630a8a5 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -51,64 +51,14 @@ static ComfyEngineVersion getEngineVersion(const ADGameDescription *gameDesc) {
 
 ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Engine(syst),
 	_gameDescription(gameDesc), _engineVersion(getEngineVersion(gameDesc)),
-	_language(2), _multiLanguage(true),
-	_randomSource("Comfy"), _screen(nullptr), _framebufPtr(nullptr), _presentBuffer(nullptr),
+	_randomSource("Comfy"),
 	_logicalScreenWidth(!strcmp(gameDesc->gameId, "panther") ? COMFY_PANTHER_SCREEN_WIDTH : COMFY_SCREEN_WIDTH),
-	_logicalScreenHeight(!strcmp(gameDesc->gameId, "panther") ? COMFY_PANTHER_SCREEN_HEIGHT : COMFY_SCREEN_HEIGHT),
-	_resolutionChangeCount(0), _renderDirtyCount(0), _renderInterleaved(false),
-	_colorDatStream(nullptr), _paletteDataPtr(nullptr), _vsyncPending(0), _fadeMax(0), _fadeStep(0),
-	_palettePage(0), _paletteFading(false),
-	_timerCurrent(1), _timer0(1), _timer1(1), _timer2(1),
-	_midiTimeCounter(0), _midiInstanceEventTime(0), _midiEventBaseTime(0),
-	_midiTimeScale(0x400), _midiTimeDelta(0), _midiCounterAdjustment(0), _midiPlyrDriver(nullptr),
-	_keyBits(nullptr), _keyBitsSize(0),
-	_keyboardMapLoaded(false), _keyboardActiveMask(0), _keyboardLatchedMask(0),
-	_keymapperActiveMask(0), _keymapperLatchedMask(0), _toyKeyboardActiveMask(0),
-	_toyKeyboardLatchedMask(0), _toyKeyboardHoldMask(0), _lptPrevScanState(0), _inputDeviceMode(0),
-	_inputDevicePreference(0), _inputPreviousComfyboardState(0), _inputPreviousKeyboardState(0),
-	_inputComfyboardActivityCount(0), _inputKeyboardActivityCount(0),
-	_keyboardUiInitialized(false), _keyboardUiVisible(true),
-	_stringCount(0), _sceneCount(0), _keyBitCount(0), _resourceHandleCount(0), _midiEntryCount(0),
-	_picDataSize(0), _usesAnimFile(false), _sceneOpen(false), _sceneEntryListActive(false),
-	_sceneMidiInstanceOffset(0), _sceneEntryListOffset(0), _sceneActorPcOffset(0), _sceneStringTableOffset(0),
-	_sceneHandlesOffset(0), _sceneActorsOffset(0), _sceneKeyBitsOffset(0), _scenePoolCursor(0),
-	_scenePoolEvictCursor(0), _scenePoolSize(0), _headerXmsObjectTableBase(0),
-	_headerXmsObjectTableBytes(0), _headerXmsPicEntriesBase(0), _headerXmsPicEntriesBytes(0),
-	_headerXmsSoundHeadersBase(0), _headerXmsSoundHeadersBytes(0), _selectorRing(0),
-	_selectorPoolInitialized(false), _activeSceneCount(0), _sceneEntryCount(0), _sceneEntryFrameSize(0),
-	_numObjects(0), _numFrames(0), _numSprites(0), _envNumSprites(0), _midiFileMode(0), _mirrorMode(false),
-	_currentActor(0), _pendingScene(0), _musicEventMask(0), _musicEventFlag(0), _musicEnabled(false),
-	_usesWcomfy99ScriptOps(false), _wcomfy99FeatureWordCount(0), _wcomfy99Sensitivity(0),
-	_wcomfy99RecordHostEnabled(false), _wcomfy99SubsystemWord(0), _wcomfy99MixedHostFirstWord(0),
-	_wcomfy99MixedHostSecondWord(0), _wcomfy99MixedHostThirdWord(0), _wcomfy99MixedHostFourthWord(0),
-	_wcomfy99HostWordA(0), _wcomfy99HostWordB(0), _wcomfy99WaveVolumePercent(0),
-	_wcomfy99WaveLeftPercent(0), _wcomfy99WaveRightPercent(0), _wcomfy99MixerVolumePercent(0),
-	_wcomfy99MixerAltPercent(0), _wcomfy99RangeHostStart(0), _wcomfy99RangeHostEnd(0),
-	_wcomfy99RangeHostCount(0), _actorDestroyedCurrent(false), _lastKey(0xFFFF),
-	_soundEventIndex(0), _soundEventMaximum(0), _soundEventSubIndex(0xFFFF),
-	_soundEventPreviousSubIndex(0xFFFF), _midiInstanceTrackBase(1),
-	_soundTileStride(0), _soundSampleRate(0x2B11), _soundNextCue(0), _soundCompressed(false), _soundPaused(false),
-	_animPosition(0), _animPendingDirtyRectSize(0), _animCurrentIndex(0),
-	_animCurrentActorSceneHandle(0), _animCurrentFrameKey(0), _animVocCounterMode(0),
-	_animVocClockHz(0), _animVocTargetCounter(0), _animVocBaseCounter(0), _animVocDeltaA(0),
-	_animVocCounterStartA(0), _animVocCounterStartB(0), _animIndexLoaded(false),
-	_animPantherFormat(false), _animActive(false),
-	_exprStackTop(0), _scriptFault(false),
-	_gameInitialized(false), _videoInitialized(false),
-	_timerInitialized(false), _lptKeyboardInitialized(false) {
+	_logicalScreenHeight(!strcmp(gameDesc->gameId, "panther") ? COMFY_PANTHER_SCREEN_HEIGHT : COMFY_SCREEN_HEIGHT) {
 	memset(_paletteFadeSource, 0, sizeof(_paletteFadeSource));
 	memset(_paletteTarget, 0, sizeof(_paletteTarget));
 	memset(_paletteDisplay, 0, sizeof(_paletteDisplay));
 	memset(_logicalPalette, 0, sizeof(_logicalPalette));
-	memset(&_inputQueue, 0, sizeof(_inputQueue));
 	memset(_keyboardKeyToBit, 0xFF, sizeof(_keyboardKeyToBit));
-	memset(_vocQueue, 0, sizeof(_vocQueue));
-	memset(&_midiEvents, 0, sizeof(_midiEvents));
-	memset(&_midiTracks, 0, sizeof(_midiTracks));
-	memset(_midiChannels, 0, sizeof(_midiChannels));
-	_frameSpriteResource.id = 0;
-	memset(&_frameSpriteResource.header, 0, sizeof(_frameSpriteResource.header));
-	_frameSpriteResource.loaded = false;
 	memset(_selectorPoolEntries, 0, sizeof(_selectorPoolEntries));
 	memset(_wcomfy99FeatureWords, 0, sizeof(_wcomfy99FeatureWords));
 	memset(_animFrameHeader, 0, sizeof(_animFrameHeader));
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index cec26a72580..6320d098d2b 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -103,6 +103,15 @@ private:
 		uint16 readIndex;
 		uint16 writeIndex;
 		uint16 tailIndex;
+
+		InputQueue() {
+			for (uint i = 0; i < COMFY_INPUT_QUEUE_CAPACITY; i++)
+				words[i] = 0;
+
+			readIndex = 0;
+			writeIndex = 0;
+			tailIndex = 0;
+		}
 	};
 
 	struct SpriteObjectHeader {
@@ -114,6 +123,17 @@ private:
 		int16 hotspotY;
 		byte reserved;
 		uint16 tiledSize;
+
+		SpriteObjectHeader() {
+			fileOffset = 0;
+			dataSize = 0;
+			width = 0;
+			height = 0;
+			hotspotX = 0;
+			hotspotY = 0;
+			reserved = 0;
+			tiledSize = 0;
+		}
 	};
 
 	struct SpriteResource {
@@ -121,6 +141,11 @@ private:
 		SpriteObjectHeader header;
 		Common::Array<byte> pixels;
 		bool loaded;
+
+		SpriteResource() {
+			id = 0;
+			loaded = false;
+		}
 	};
 
 	struct SpriteCacheEntry {
@@ -131,6 +156,13 @@ private:
 	struct ResourceLoadList {
 		uint16 ids[COMFY_RESOURCE_LIST_CAPACITY];
 		uint16 count;
+
+		ResourceLoadList() {
+			for (uint i = 0; i < COMFY_RESOURCE_LIST_CAPACITY; i++)
+				ids[i] = 0;
+
+			count = 0;
+		}
 	};
 
 	struct VocQueueEntry {
@@ -138,11 +170,25 @@ private:
 		uint16 argumentCount;
 		uint16 state;
 		uint16 arguments[COMFY_VOC_ARG_CAPACITY];
+
+		VocQueueEntry() {
+			soundId = 0;
+			argumentCount = 0;
+			state = 0;
+
+			for (uint i = 0; i < COMFY_VOC_ARG_CAPACITY; i++)
+				arguments[i] = 0;
+		}
 	};
 
 	struct MidiQueueEntry {
 		uint16 id;
 		int32 time;
+
+		MidiQueueEntry() {
+			id = 0;
+			time = 0;
+		}
 	};
 
 	struct MidiQueue {
@@ -151,6 +197,13 @@ private:
 		int32 baseTime;
 		uint16 nextIndex;
 		int32 nextTime;
+
+		MidiQueue() {
+			count = 0;
+			baseTime = 0;
+			nextIndex = 0;
+			nextTime = 0;
+		}
 	};
 
 	struct MidiTrackEntry {
@@ -159,6 +212,16 @@ private:
 		byte loadFlag;
 		uint16 frameCount;
 		uint16 frames[COMFY_ANIM_FRAME_CAPACITY];
+
+		MidiTrackEntry() {
+			songId = 0;
+			completionKey = 0;
+			loadFlag = 0;
+			frameCount = 0;
+
+			for (uint i = 0; i < COMFY_ANIM_FRAME_CAPACITY; i++)
+				frames[i] = 0;
+		}
 	};
 
 	struct MidiChannelState {
@@ -178,6 +241,24 @@ private:
 		int16 pitchDefault;
 		uint16 loadedFrameSize;
 		bool playing;
+
+		MidiChannelState() {
+			entryCount = 0;
+			volumeCurrent = 0;
+			volumeTarget = 0;
+			volumeTicksLeft = 0;
+			volumeDefault = 0;
+			rateCurrent = 0;
+			rateTarget = 0;
+			rateTicksLeft = 0;
+			rateDefault = 0;
+			pitchCurrent = 0;
+			pitchTarget = 0;
+			pitchTicksLeft = 0;
+			pitchDefault = 0;
+			loadedFrameSize = 0;
+			playing = false;
+		}
 	};
 
 	struct SoundCue {
@@ -235,76 +316,76 @@ private:
 	Common::Path _introDirectory;
 	Common::Path _gameDataPath;
 	Common::Path _languageDirectories[16];
-	uint16 _language;
-	bool _multiLanguage;
+	uint16 _language = 2;
+	bool _multiLanguage = true;
 	Common::RandomSource _randomSource;
-	Graphics::Screen *_screen;
-	byte *_framebufPtr;
-	byte *_presentBuffer;
+	Graphics::Screen *_screen = nullptr;
+	byte *_framebufPtr = nullptr;
+	byte *_presentBuffer = nullptr;
 	uint16 _logicalScreenWidth;
 	uint16 _logicalScreenHeight;
 	VideoRectRecord _resolutionChanges[COMFY_RESOLUTION_CHANGE_CAPACITY];
-	uint16 _resolutionChangeCount;
-	uint16 _renderDirtyCount;
-	bool _renderInterleaved;
-	Common::SeekableReadStream *_colorDatStream;
+	uint16 _resolutionChangeCount = 0;
+	uint16 _renderDirtyCount = 0;
+	bool _renderInterleaved = false;
+	Common::SeekableReadStream *_colorDatStream = nullptr;
 	byte _paletteFadeSource[COMFY_PALETTE_BYTES];
 	byte _paletteTarget[COMFY_PALETTE_BYTES];
 	byte _paletteDisplay[COMFY_PALETTE_BYTES];
 	byte _logicalPalette[256 * 4];
-	byte *_paletteDataPtr;
-	uint16 _vsyncPending;
-	uint16 _fadeMax;
-	uint16 _fadeStep;
-	byte _palettePage;
-	bool _paletteFading;
-	int16 _timerCurrent;
-	int16 _timer0;
-	int16 _timer1;
-	int16 _timer2;
-	uint32 _midiTimeCounter;
-	uint32 _midiInstanceEventTime;
-	int32 _midiEventBaseTime;
-	int32 _midiTimeScale;
-	int16 _midiTimeDelta;
-	int16 _midiCounterAdjustment;
-	MidiPlyrDriver *_midiPlyrDriver;
-	byte *_keyBits;
-	uint32 _keyBitsSize;
+	byte *_paletteDataPtr = nullptr;
+	uint16 _vsyncPending = 0;
+	uint16 _fadeMax = 0;
+	uint16 _fadeStep = 0;
+	byte _palettePage = 0;
+	bool _paletteFading = false;
+	int16 _timerCurrent = 1;
+	int16 _timer0 = 1;
+	int16 _timer1 = 1;
+	int16 _timer2 = 1;
+	uint32 _midiTimeCounter = 0;
+	uint32 _midiInstanceEventTime = 0;
+	int32 _midiEventBaseTime = 0;
+	int32 _midiTimeScale = 0x400;
+	int16 _midiTimeDelta = 0;
+	int16 _midiCounterAdjustment = 0;
+	MidiPlyrDriver *_midiPlyrDriver = nullptr;
+	byte *_keyBits = nullptr;
+	uint32 _keyBitsSize = 0;
 	InputQueue _inputQueue;
 	byte _keyboardKeyToBit[256];
-	bool _keyboardMapLoaded;
-	uint32 _keyboardActiveMask;
-	uint32 _keyboardLatchedMask;
-	uint32 _keymapperActiveMask;
-	uint32 _keymapperLatchedMask;
-	uint32 _toyKeyboardActiveMask;
-	uint32 _toyKeyboardLatchedMask;
-	uint32 _toyKeyboardHoldMask;
-	uint32 _lptPrevScanState;
-	uint16 _inputDeviceMode;
-	uint16 _inputDevicePreference;
-	uint32 _inputPreviousComfyboardState;
-	uint32 _inputPreviousKeyboardState;
-	uint16 _inputComfyboardActivityCount;
-	uint16 _inputKeyboardActivityCount;
-	bool _keyboardUiInitialized;
-	bool _keyboardUiVisible;
+	bool _keyboardMapLoaded = false;
+	uint32 _keyboardActiveMask = 0;
+	uint32 _keyboardLatchedMask = 0;
+	uint32 _keymapperActiveMask = 0;
+	uint32 _keymapperLatchedMask = 0;
+	uint32 _toyKeyboardActiveMask = 0;
+	uint32 _toyKeyboardLatchedMask = 0;
+	uint32 _toyKeyboardHoldMask = 0;
+	uint32 _lptPrevScanState = 0;
+	uint16 _inputDeviceMode = 0;
+	uint16 _inputDevicePreference = 0;
+	uint32 _inputPreviousComfyboardState = 0;
+	uint32 _inputPreviousKeyboardState = 0;
+	uint16 _inputComfyboardActivityCount = 0;
+	uint16 _inputKeyboardActivityCount = 0;
+	bool _keyboardUiInitialized = false;
+	bool _keyboardUiVisible = true;
 	Common::Array<byte> _comfyObjData;
 	Common::Array<byte> _picFileData;
 	Common::Array<byte> _midiFileData;
 	Common::Array<SpriteObjectHeader> _spriteHeaders;
 	Common::Array<SpriteResource> _spriteResources;
 	SpriteResource _frameSpriteResource;
-	uint16 _stringCount;
-	uint16 _sceneCount;
-	uint16 _keyBitCount;
-	uint16 _resourceHandleCount;
-	uint16 _midiEntryCount;
-	uint32 _picDataSize;
-	bool _usesAnimFile;
-	bool _sceneOpen;
-	bool _sceneEntryListActive;
+	uint16 _stringCount = 0;
+	uint16 _sceneCount = 0;
+	uint16 _keyBitCount = 0;
+	uint16 _resourceHandleCount = 0;
+	uint16 _midiEntryCount = 0;
+	uint32 _picDataSize = 0;
+	bool _usesAnimFile = false;
+	bool _sceneOpen = false;
+	bool _sceneEntryListActive = false;
 	Common::Array<uint16> _stringTable;
 	Common::Array<uint16> _sceneHandles;
 	Common::Array<uint16> _midiHandles;
@@ -318,108 +399,108 @@ private:
 	Common::Array<SpriteCacheEntry> _frameCacheEntries;
 	ResourceLoadList _spriteConversionLoads;
 	uint32 _sceneEntryOffsets[COMFY_SCENE_ENTRY_OFFSET_CAPACITY];
-	uint32 _sceneMidiInstanceOffset;
-	uint32 _sceneEntryListOffset;
-	uint32 _sceneActorPcOffset;
-	uint32 _sceneStringTableOffset;
-	uint32 _sceneHandlesOffset;
-	uint32 _sceneActorsOffset;
-	uint32 _sceneKeyBitsOffset;
-	uint32 _scenePoolCursor;
-	uint32 _scenePoolEvictCursor;
-	uint32 _scenePoolSize;
-	uint32 _headerXmsObjectTableBase;
-	uint32 _headerXmsObjectTableBytes;
-	uint32 _headerXmsPicEntriesBase;
-	uint32 _headerXmsPicEntriesBytes;
-	uint32 _headerXmsSoundHeadersBase;
-	uint32 _headerXmsSoundHeadersBytes;
+	uint32 _sceneMidiInstanceOffset = 0;
+	uint32 _sceneEntryListOffset = 0;
+	uint32 _sceneActorPcOffset = 0;
+	uint32 _sceneStringTableOffset = 0;
+	uint32 _sceneHandlesOffset = 0;
+	uint32 _sceneActorsOffset = 0;
+	uint32 _sceneKeyBitsOffset = 0;
+	uint32 _scenePoolCursor = 0;
+	uint32 _scenePoolEvictCursor = 0;
+	uint32 _scenePoolSize = 0;
+	uint32 _headerXmsObjectTableBase = 0;
+	uint32 _headerXmsObjectTableBytes = 0;
+	uint32 _headerXmsPicEntriesBase = 0;
+	uint32 _headerXmsPicEntriesBytes = 0;
+	uint32 _headerXmsSoundHeadersBase = 0;
+	uint32 _headerXmsSoundHeadersBytes = 0;
 	uint16 _selectorPoolEntries[10];
-	uint16 _selectorRing;
-	bool _selectorPoolInitialized;
-	uint16 _activeSceneCount;
-	uint16 _sceneEntryCount;
-	uint16 _sceneEntryFrameSize;
-	uint16 _numObjects;
-	uint16 _numFrames;
-	uint32 _numSprites;
-	uint32 _envNumSprites;
-	byte _midiFileMode;
-	bool _mirrorMode;
+	uint16 _selectorRing = 0;
+	bool _selectorPoolInitialized = false;
+	uint16 _activeSceneCount = 0;
+	uint16 _sceneEntryCount = 0;
+	uint16 _sceneEntryFrameSize = 0;
+	uint16 _numObjects = 0;
+	uint16 _numFrames = 0;
+	uint32 _numSprites = 0;
+	uint32 _envNumSprites = 0;
+	byte _midiFileMode = 0;
+	bool _mirrorMode = false;
 	uint32 _actorPcTable[COMFY_ACTOR_PC_TABLE_COUNT];
-	uint16 _currentActor;
-	uint16 _pendingScene;
-	uint16 _musicEventMask;
-	byte _musicEventFlag;
-	bool _musicEnabled;
-	bool _usesWcomfy99ScriptOps;
+	uint16 _currentActor = 0;
+	uint16 _pendingScene = 0;
+	uint16 _musicEventMask = 0;
+	byte _musicEventFlag = 0;
+	bool _musicEnabled = false;
+	bool _usesWcomfy99ScriptOps = false;
 	uint16 _wcomfy99FeatureWords[16];
-	byte _wcomfy99FeatureWordCount;
-	uint16 _wcomfy99Sensitivity;
-	bool _wcomfy99RecordHostEnabled;
-	uint16 _wcomfy99SubsystemWord;
-	uint16 _wcomfy99MixedHostFirstWord;
-	uint16 _wcomfy99MixedHostSecondWord;
-	uint16 _wcomfy99MixedHostThirdWord;
-	uint16 _wcomfy99MixedHostFourthWord;
-	uint16 _wcomfy99HostWordA;
-	uint16 _wcomfy99HostWordB;
-	uint16 _wcomfy99WaveVolumePercent;
-	uint16 _wcomfy99WaveLeftPercent;
-	uint16 _wcomfy99WaveRightPercent;
-	uint16 _wcomfy99MixerVolumePercent;
-	uint16 _wcomfy99MixerAltPercent;
-	uint16 _wcomfy99RangeHostStart;
-	uint16 _wcomfy99RangeHostEnd;
-	uint16 _wcomfy99RangeHostCount;
-	bool _actorDestroyedCurrent;
-	uint16 _lastKey;
+	byte _wcomfy99FeatureWordCount = 0;
+	uint16 _wcomfy99Sensitivity = 0;
+	bool _wcomfy99RecordHostEnabled = false;
+	uint16 _wcomfy99SubsystemWord = 0;
+	uint16 _wcomfy99MixedHostFirstWord = 0;
+	uint16 _wcomfy99MixedHostSecondWord = 0;
+	uint16 _wcomfy99MixedHostThirdWord = 0;
+	uint16 _wcomfy99MixedHostFourthWord = 0;
+	uint16 _wcomfy99HostWordA = 0;
+	uint16 _wcomfy99HostWordB = 0;
+	uint16 _wcomfy99WaveVolumePercent = 0;
+	uint16 _wcomfy99WaveLeftPercent = 0;
+	uint16 _wcomfy99WaveRightPercent = 0;
+	uint16 _wcomfy99MixerVolumePercent = 0;
+	uint16 _wcomfy99MixerAltPercent = 0;
+	uint16 _wcomfy99RangeHostStart = 0;
+	uint16 _wcomfy99RangeHostEnd = 0;
+	uint16 _wcomfy99RangeHostCount = 0;
+	bool _actorDestroyedCurrent = false;
+	uint16 _lastKey = 0xFFFF;
 	VocQueueEntry _vocQueue[COMFY_VOC_QUEUE_CAPACITY];
-	uint16 _soundEventIndex;
-	uint16 _soundEventMaximum;
-	uint16 _soundEventSubIndex;
-	uint16 _soundEventPreviousSubIndex;
+	uint16 _soundEventIndex = 0;
+	uint16 _soundEventMaximum = 0;
+	uint16 _soundEventSubIndex = 0xFFFF;
+	uint16 _soundEventPreviousSubIndex = 0xFFFF;
 	MidiQueue _midiEvents;
 	MidiQueue _midiTracks;
 	MidiChannelState _midiChannels[COMFY_MIDI_CHANNEL_COUNT];
-	uint32 _midiInstanceTrackBase;
+	uint32 _midiInstanceTrackBase = 1;
 	Common::Array<byte> _vocFileData;
 	Common::Array<byte> _soundPcm;
 	Common::Array<SoundCue> _soundCues;
 	Audio::SoundHandle _soundHandle;
-	uint16 _soundTileStride;
-	uint32 _soundSampleRate;
-	uint _soundNextCue;
-	bool _soundCompressed;
-	bool _soundPaused;
+	uint16 _soundTileStride = 0;
+	uint32 _soundSampleRate = 0x2B11;
+	uint _soundNextCue = 0;
+	bool _soundCompressed = false;
+	bool _soundPaused = false;
 	Common::Array<byte> _animFileData;
 	Common::Array<uint32> _animIndexTable;
 	Common::Array<byte> _animFrameBuffer;
 	Common::Array<byte> _animFrameStorage;
 	byte _animFrameHeader[COMFY_ANMFILE_HEADER_BYTES];
 	byte _animPendingDirtyRect[16];
-	uint32 _animPosition;
-	uint16 _animPendingDirtyRectSize;
-	uint16 _animCurrentIndex;
-	uint16 _animCurrentActorSceneHandle;
-	uint16 _animCurrentFrameKey;
-	byte _animVocCounterMode;
-	uint16 _animVocClockHz;
-	uint16 _animVocTargetCounter;
-	uint16 _animVocBaseCounter;
-	uint16 _animVocDeltaA;
-	uint32 _animVocCounterStartA;
-	uint32 _animVocCounterStartB;
-	bool _animIndexLoaded;
-	bool _animPantherFormat;
-	bool _animActive;
+	uint32 _animPosition = 0;
+	uint16 _animPendingDirtyRectSize = 0;
+	uint16 _animCurrentIndex = 0;
+	uint16 _animCurrentActorSceneHandle = 0;
+	uint16 _animCurrentFrameKey = 0;
+	byte _animVocCounterMode = 0;
+	uint16 _animVocClockHz = 0;
+	uint16 _animVocTargetCounter = 0;
+	uint16 _animVocBaseCounter = 0;
+	uint16 _animVocDeltaA = 0;
+	uint32 _animVocCounterStartA = 0;
+	uint32 _animVocCounterStartB = 0;
+	bool _animIndexLoaded = false;
+	bool _animPantherFormat = false;
+	bool _animActive = false;
 	uint16 _exprStack[COMFY_EXPR_STACK_CAPACITY];
-	uint16 _exprStackTop;
-	bool _scriptFault;
-	bool _gameInitialized;
-	bool _videoInitialized;
-	bool _timerInitialized;
-	bool _lptKeyboardInitialized;
+	uint16 _exprStackTop = 0;
+	bool _scriptFault = false;
+	bool _gameInitialized = false;
+	bool _videoInitialized = false;
+	bool _timerInitialized = false;
+	bool _lptKeyboardInitialized = false;
 
 	Common::Error gameInit();
 	void gameShutdown();
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index ad6431f3f2b..b8767eca5fc 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -254,8 +254,8 @@ bool ComfyEngine::picFileOpen() {
 	_spriteHeaders.resize(count);
 	_spriteResources.resize(count);
 	for (uint i = 0; i < count; i++) {
-		memset(&_spriteHeaders[i], 0, sizeof(SpriteObjectHeader));
-		memset(&_spriteResources[i].header, 0, sizeof(SpriteObjectHeader));
+		_spriteHeaders[i] = SpriteObjectHeader();
+		_spriteResources[i].header = SpriteObjectHeader();
 		_spriteResources[i].id = i;
 		_spriteResources[i].pixels.clear();
 		_spriteResources[i].loaded = false;
@@ -441,7 +441,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	if (!_frameCacheEntries.empty())
 		memset(&_frameCacheEntries[0], 0xFF, _frameCacheEntries.size() * sizeof(SpriteCacheEntry));
 
-	memset(&_spriteConversionLoads, 0, sizeof(_spriteConversionLoads));
+	_spriteConversionLoads = ResourceLoadList();
 
 	for (uint i = 0; i < _spriteResources.size(); i++)
 		spriteInvalidateHostCache(_spriteResources[i]);
@@ -530,7 +530,8 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	_musicEventMask = 0;
 	_musicEventFlag = 0;
 	_musicEnabled = false;
-	memset(_vocQueue, 0, sizeof(_vocQueue));
+	for (uint i = 0; i < COMFY_VOC_QUEUE_CAPACITY; i++)
+		_vocQueue[i] = VocQueueEntry();
 	_soundEventIndex = 0;
 	_soundEventMaximum = 0;
 	_soundEventSubIndex = 0xFFFF;
@@ -567,7 +568,7 @@ void ComfyEngine::assetsUnload(byte freeAudio) {
 	_picFileData.clear();
 	_midiFileData.clear();
 	selPoolFree();
-	memset(&_spriteConversionLoads, 0, sizeof(_spriteConversionLoads));
+	_spriteConversionLoads = ResourceLoadList();
 	memset(_sceneEntryOffsets, 0, sizeof(_sceneEntryOffsets));
 	memset(_actorPcTable, 0, sizeof(_actorPcTable));
 	_usesWcomfy99ScriptOps = false;
diff --git a/engines/comfy/midi.cpp b/engines/comfy/midi.cpp
index c0e6cde32ca..e4cf247b041 100644
--- a/engines/comfy/midi.cpp
+++ b/engines/comfy/midi.cpp
@@ -174,8 +174,8 @@ void ComfyEngine::midiFindNext(MidiQueue &queue) {
 }
 
 void ComfyEngine::midiInitInstance() {
-	memset(&_midiEvents, 0, sizeof(_midiEvents));
-	memset(&_midiTracks, 0, sizeof(_midiTracks));
+	_midiEvents = MidiQueue();
+	_midiTracks = MidiQueue();
 	_midiEvents.baseTime = 0;
 	_midiTracks.baseTime = 1;
 	_midiInstanceTrackBase = 1;
@@ -184,8 +184,8 @@ void ComfyEngine::midiInitInstance() {
 }
 
 void ComfyEngine::midiInitChannels() {
-	memset(_midiChannels, 0, sizeof(_midiChannels));
 	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
+		_midiChannels[channel] = MidiChannelState();
 		MidiChannelState &state = _midiChannels[channel];
 		state.volumeCurrent = state.volumeTarget = state.volumeDefault = 0x6400;
 		state.rateCurrent = state.rateTarget = state.rateDefault = 0x07D0;
diff --git a/engines/comfy/midiplyr/midiplyr.cpp b/engines/comfy/midiplyr/midiplyr.cpp
index aa00e2ba754..e897d90d643 100644
--- a/engines/comfy/midiplyr/midiplyr.cpp
+++ b/engines/comfy/midiplyr/midiplyr.cpp
@@ -29,8 +29,7 @@
 
 namespace Comfy {
 
-MidiPlyrDriver::MidiPlyrDriver(DriverVersion driverVersion) :
-	_driverVersion(driverVersion), _midiDriver(nullptr), _started(false), _timerInstalled(false) {
+MidiPlyrDriver::MidiPlyrDriver(DriverVersion driverVersion) : _driverVersion(driverVersion) {
 	resetState();
 }
 
@@ -74,36 +73,17 @@ void MidiPlyrDriver::resetState() {
 
 	for (uint i = 0; i < MIDIPLYR_CHANNEL_COUNT; i++) {
 		_deferredCc7Order[i] = 0;
-		_channels[i].inUse = 0;
-		_channels[i].volumePercent = 100;
+		_channels[i] = ChannelSlot();
 	}
 
-	for (uint i = 0; i < MIDIPLYR_NOTE_CAPACITY; i++) {
-		_notes[i].channel = 0;
-		_notes[i].pitch = 0;
-	}
+	for (uint i = 0; i < MIDIPLYR_NOTE_CAPACITY; i++)
+		_notes[i] = Note();
 
 	for (uint i = 0; i < ARRAYSIZE(_comfyboardSamples); i++)
 		_comfyboardSamples[i] = 0;
 
-	for (uint i = 0; i < kTrackCount; i++) {
-		Track &track = _tracks[i];
-		track.state = 0;
-		track.streamBase = nullptr;
-		track.eventDataSize = 0;
-		track.eventCursor = 0;
-		track.rate = 0;
-		track.startTick = 0;
-		track.volume = 0;
-		track.pitch = 0;
-		track.marker = 0;
-		track.midiLoopFlag = 0;
-		track.streamSize = 0;
-		track.streamFault = false;
-
-		for (uint channel = 0; channel < MIDIPLYR_CHANNEL_COUNT; channel++)
-			track.channelState[channel] = MIDIPLYR_FREE_CHANNEL;
-	}
+	for (uint i = 0; i < kTrackCount; i++)
+		_tracks[i] = Track();
 }
 
 uint32 MidiPlyrDriver::midiFindDevice() {
diff --git a/engines/comfy/midiplyr/midiplyr.h b/engines/comfy/midiplyr/midiplyr.h
index 27ec69b1c19..18f1ae23938 100644
--- a/engines/comfy/midiplyr/midiplyr.h
+++ b/engines/comfy/midiplyr/midiplyr.h
@@ -98,16 +98,45 @@ private:
 		byte midiLoopFlag;
 		uint32 streamSize;
 		bool streamFault;
+
+		Track() {
+			state = 0;
+			streamBase = nullptr;
+			eventDataSize = 0;
+			eventCursor = 0;
+
+			for (uint channel = 0; channel < MIDIPLYR_CHANNEL_COUNT; channel++)
+				channelState[channel] = MIDIPLYR_FREE_CHANNEL;
+
+			rate = 0;
+			startTick = 0;
+			volume = 0;
+			pitch = 0;
+			marker = 0;
+			midiLoopFlag = 0;
+			streamSize = 0;
+			streamFault = false;
+		}
 	};
 
 	struct Note {
 		uint16 channel;
 		uint16 pitch;
+
+		Note() {
+			channel = 0;
+			pitch = 0;
+		}
 	};
 
 	struct ChannelSlot {
 		byte inUse;
 		byte volumePercent;
+
+		ChannelSlot() {
+			inUse = 0;
+			volumePercent = 100;
+		}
 	};
 
 	static void timerProc(void *refCon);
@@ -148,48 +177,48 @@ private:
 	void vocSrUpdateCountersInternal();
 
 	DriverVersion _driverVersion;
-	MidiDriver *_midiDriver;
+	MidiDriver *_midiDriver = nullptr;
 	mutable Common::Mutex _mutex;
-	bool _started;
-	bool _timerInstalled;
+	bool _started = false;
+	bool _timerInstalled = false;
 
-	byte _noteCount;
-	uint16 _midiDeviceId;
-	uint32 _midiDeviceHandle;
-	uint16 _deferredCc7QueuedCount;
+	byte _noteCount = 0;
+	uint16 _midiDeviceId = 0;
+	uint32 _midiDeviceHandle = 0;
+	uint16 _deferredCc7QueuedCount = 0;
 	uint16 _deferredCc7[MIDIPLYR_DEFERRED_CC7_COUNT_MAX];
 	uint16 _deferredCc7Order[MIDIPLYR_CHANNEL_COUNT];
-	byte _sendDirectGuard;
-	uint32 _seqCurrentTick;
-	uint16 _vocBlockNo;
-	uint32 _vocUnknown;
-
-	byte _comfyboardStopReading;
-	uint16 _comfyboardSampleIndex;
-	uint32 _comfyboardButtons;
-	uint32 _comfyboardHostButtons;
-	byte _comfyboardSleepUseStopped;
-	uint16 _comfyboardPort;
-	uint32 _comfyboardXorMask;
+	byte _sendDirectGuard = 0;
+	uint32 _seqCurrentTick = 0;
+	uint16 _vocBlockNo = 0;
+	uint32 _vocUnknown = 0;
+
+	byte _comfyboardStopReading = 1;
+	uint16 _comfyboardSampleIndex = 0;
+	uint32 _comfyboardButtons = 0;
+	uint32 _comfyboardHostButtons = 0;
+	byte _comfyboardSleepUseStopped = 1;
+	uint16 _comfyboardPort = 0;
+	uint32 _comfyboardXorMask = 0;
 	byte _comfyboardSamples[8];
-	byte _comfyboardSavedControl;
+	byte _comfyboardSavedControl = 0;
 
 	ChannelSlot _channels[MIDIPLYR_CHANNEL_COUNT];
-	uint16 _timeFracHi;
-	uint16 _timeFracLo;
-	byte _increaseVocCounter;
-	uint32 _tempoAcc;
-	uint32 _timeFracAcc;
+	uint16 _timeFracHi = 0;
+	uint16 _timeFracLo = 0;
+	byte _increaseVocCounter = 0;
+	uint32 _tempoAcc = 0;
+	uint32 _timeFracAcc = 0;
 	Note _notes[MIDIPLYR_NOTE_CAPACITY];
-	uint16 _midiOutResult;
+	uint16 _midiOutResult = 0;
 	Track _tracks[kTrackCount];
-	uint16 _midiFileFormat;
-	uint32 _ticksPerQuarter;
-	uint16 _channelAvailMask;
-	uint16 _drumsChannel;
-	uint16 _midiNoteCountCap;
-	uint16 _vocSnapshotHi;
-	uint16 _vocSnapshotLo;
+	uint16 _midiFileFormat = 0;
+	uint32 _ticksPerQuarter = 0;
+	uint16 _channelAvailMask = 0xFFFF;
+	uint16 _drumsChannel = 9;
+	uint16 _midiNoteCountCap = 0;
+	uint16 _vocSnapshotHi = 0;
+	uint16 _vocSnapshotLo = 0;
 };
 
 } // End of namespace Comfy


Commit: 59c0d1397773e647ffff0fe249b18c4889eb8b2e
    https://github.com/scummvm/scummvm/commit/59c0d1397773e647ffff0fe249b18c4889eb8b2e
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: More refactoring and clean up

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/anim_file.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/game.cpp
    engines/comfy/input.cpp
    engines/comfy/script_vm.cpp
    engines/comfy/video.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index 31567e84bfa..9d3b9ef8983 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -166,6 +166,7 @@ void ComfyEngine::objHdrRead(SpriteObjectHeader &destination, uint16 index) {
 	destination.hotspotY = int16(READ_LE_UINT16(raw + 0x0C));
 	destination.reserved = raw[0x0E];
 	destination.tiledSize = READ_LE_UINT16(raw + 0x0F);
+	_spriteLastHeader = destination;
 }
 
 void ComfyEngine::scenePoolEvict() {
@@ -880,8 +881,152 @@ void ComfyEngine::actorDrawList(uint16 actorIndex, int16 x, int16 y) {
 	}
 }
 
-void ComfyEngine::actorDrawScripted(uint16 actorIndex, uint32 selector, int16 x, int16 y) {
+uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &maskRecord,
+		VideoRectRecord *rects, int16 baseX, int16 baseY) {
+	if (mode == 1) {
+		_keymaskBits = 0;
+		maskRecord.right = 0;
+		maskRecord.bottom = 0;
+	} else {
+		_keymaskBits = uint16(maskRecord.right) | (uint32(uint16(maskRecord.bottom)) << 16);
+	}
+
+	int16 wordsLeft = int16(scriptReadWord(pc) - 1);
+	pc += 2;
+	uint16 bitIndex = 0xFFFF;
+	_keymaskCount = wordsLeft;
+	while (wordsLeft > 0 && !_scriptFault) {
+		bitIndex++;
+		uint16 spriteId = scriptReadWord(pc);
+		uint16 dx = scriptReadWord(pc + 2);
+		uint16 dy = scriptReadWord(pc + 4);
+		pc += 6;
+		wordsLeft -= 3;
+		_keymaskCount = wordsLeft;
+		_keymaskSpriteWord = spriteId;
+		_keymaskArg0 = dx;
+		_keymaskArg1 = dy;
+
+		if (spriteId & 0x8000) {
+			wordsLeft -= 2;
+			_keymaskCount = wordsLeft;
+			uint32 mask = uint32(1) << (bitIndex & 31);
+			if (mode == 1) {
+				uint16 key = scriptReadWord(pc);
+				_keymaskResult = keyBitTest(key) ? 1 : 0;
+				if (_keymaskResult) {
+					_keymaskBits |= mask;
+					maskRecord.right = uint16(_keymaskBits);
+					maskRecord.bottom = uint16(_keymaskBits >> 16);
+				}
+
+				pc += 2;
+				if (_keymaskResult)
+					spriteId &= 0x7FFF;
+				else
+					spriteId = scriptReadWord(pc);
+			} else {
+				_keymaskResult = (_keymaskBits & mask) ? 1 : 0;
+				pc += 2;
+				if (_keymaskResult)
+					spriteId &= 0x7FFF;
+				else
+					spriteId = scriptReadWord(pc);
+			}
+
+			pc += 2;
+			_keymaskSpriteWord = spriteId;
+		}
+
+		VideoRectRecord *rect = bitIndex < COMFY_RESOLUTION_CHANGE_CAPACITY ? &rects[bitIndex] : nullptr;
+		if (rect) {
+			rect->left = 0;
+			rect->top = 0;
+			rect->right = 0;
+			rect->bottom = 0;
+			rect->area = 0;
+		}
+
+		if (!spriteId)
+			continue;
+
+		int16 spriteX = baseX + int16(dx);
+		int16 spriteY = baseY + int16(dy);
+		if (spriteX >= 0x0280 || spriteX <= int16(0xFEC0) ||
+				spriteY >= 0x0190 || spriteY <= int16(0xFF38))
+			continue;
+
+		SpriteResource *sprite = spriteGetPtr(int16(spriteId));
+		if (!sprite)
+			continue;
+
+		int16 left = spriteX - sprite->header.hotspotX;
+		int16 top = spriteY - sprite->header.hotspotY;
+		if (mode == 1)
+			spriteBlitClipped(int16(spriteId), left, top);
+
+		if (rect) {
+			rect->left = left;
+			rect->top = top;
+			rect->right = left + sprite->header.width;
+			rect->bottom = top + sprite->header.height;
+			rect->area = sprite->header.width * sprite->header.height;
+		}
+	}
+
+	_keymaskLastIndex = bitIndex;
+	return bitIndex;
+}
+
+void ComfyEngine::actorEvalFrameSelection(uint16 actorIndex, int16 x, int16 y) {
+	Actor *actor = actorGetPtr(actorIndex);
+	if (!actor)
+		return;
+
+	uint32 selector = actorReadU32(*actor, kActorCachedSprite);
+	VideoRectRecord rect = actorReadCachedRect(*actor);
+	if (selector & 0xFF000000) {
+		uint16 last = scriptEvalKeyMask(selector & 0x00FFFFFF, 0, rect, _keymaskOldRects,
+			rect.left, rect.top);
+		if (last >= COMFY_RESOLUTION_CHANGE_CAPACITY)
+			last = COMFY_RESOLUTION_CHANGE_CAPACITY - 1;
+
+		for (uint i = 0; i <= last; i++) {
+			if (_keymaskOldRects[i].area)
+				videoFindBestMode(_keymaskOldRects[i]);
+		}
+	} else if (rect.area) {
+		videoFindBestMode(rect);
+	}
+
+	actorWriteU32(*actor, kActorCachedSprite, 0);
+	uint16 child = actorReadU16(*actor, kActorSiblingHead);
+	while (child) {
+		actorEvalFrameSelection(child, x, y);
+		Actor *childActor = actorGetPtr(child);
+		child = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
+	}
+
+	child = actorReadU16(*actor, kActorChildHead);
+	while (child) {
+		actorEvalFrameSelection(child, x, y);
+		Actor *childActor = actorGetPtr(child);
+		child = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
+	}
+}
+
+uint16 ComfyEngine::actorDrawScripted(uint16 actorIndex, uint32 selector, int16 x, int16 y) {
 	uint32 pc = selector & 0x00FFFFFF;
+	if (_videoMode == 2) {
+		_keymaskCurrentRecord.left = x;
+		_keymaskCurrentRecord.top = y;
+		_keymaskCurrentRecord.right = 0;
+		_keymaskCurrentRecord.bottom = 0;
+		_keymaskCurrentRecord.area = 0;
+		uint16 last = scriptEvalKeyMask(pc, 1, _keymaskCurrentRecord, _keymaskRects, x, y);
+		return MIN<uint16>(last, COMFY_RESOLUTION_CHANGE_CAPACITY - 1);
+	}
+
 	int16 wordsLeft = int16(scriptReadWord(pc) - 1);
 	pc += 2;
 	while (wordsLeft > 0 && !_scriptFault) {
@@ -910,6 +1055,7 @@ void ComfyEngine::actorDrawScripted(uint16 actorIndex, uint32 selector, int16 x,
 	}
 
 	(void)actorIndex;
+	return 0xFFFF;
 }
 
 ComfyEngine::VideoRectRecord ComfyEngine::actorReadCachedRect(Actor &actor) {
@@ -941,7 +1087,7 @@ void ComfyEngine::actorInvalidateDrawTree(uint16 actorIndex) {
 
 	actorWriteU8(*actor, kActorCachedVisible, 0);
 	actorWriteU32(*actor, kActorCachedSprite, 0);
-	VideoRectRecord empty = {0, 0, 0, 0, 0};
+	VideoRectRecord empty;
 	actorWriteCachedRect(*actor, empty);
 	uint16 child = actorReadU16(*actor, kActorSiblingHead);
 	while (child) {
@@ -974,8 +1120,10 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 	uint32 oldSelector = actorReadU32(*actor, kActorCachedSprite);
 	VideoRectRecord oldRect = actorReadCachedRect(*actor);
 	if (!actorReadU8(*actor, kActorVisible)) {
-		if (oldVisible)
-			actorInvalidateDrawTree(actorIndex);
+		if (_videoMode == 2 && actorReadU8(*actor, kActorVisible) != oldVisible) {
+			actorEvalFrameSelection(actorIndex, drawX, drawY);
+			actorWriteU8(*actor, kActorCachedVisible, actorReadU8(*actor, kActorVisible));
+		}
 
 		return true;
 	}
@@ -983,9 +1131,17 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 	animFrameRecordVocCounter(1);
 	actorDrawList(actorReadU16(*actor, kActorSiblingHead), drawX, drawY);
 	uint32 selector = actorReadU32(*actor, kActorSpriteSelector);
-	VideoRectRecord newRect = {0, 0, 0, 0, 0};
-	if (selector & 0xFF000000) {
-		actorDrawScripted(actorIndex, selector, drawX, drawY);
+	bool oldScripted = (oldSelector & 0xFF000000) != 0;
+	bool newScripted = (selector & 0xFF000000) != 0;
+	VideoRectRecord newRect;
+	uint16 scriptedLastRect = 0xFFFF;
+	bool newRectValid = false;
+	if (newScripted) {
+		scriptedLastRect = actorDrawScripted(actorIndex, selector, drawX, drawY);
+		if (_videoMode == 2 && scriptedLastRect != 0xFFFF) {
+			newRect = _keymaskCurrentRecord;
+			newRectValid = true;
+		}
 	} else if (selector) {
 		SpriteResource *sprite = spriteGetPtr(int16(selector));
 		if (sprite) {
@@ -994,24 +1150,83 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 			newRect.right = newRect.left + sprite->header.width;
 			newRect.bottom = newRect.top + sprite->header.height;
 			newRect.area = sprite->header.width * sprite->header.height;
+			newRectValid = true;
 			spriteBlitClipped(int16(selector), drawX - sprite->header.hotspotX, drawY - sprite->header.hotspotY);
 		}
 	}
 	animFrameRecordVocCounter(2);
 
-	bool rectChanged = oldRect.left != newRect.left || oldRect.top != newRect.top ||
-		oldRect.right != newRect.right || oldRect.bottom != newRect.bottom || oldRect.area != newRect.area;
-	if (oldSelector != selector || oldVisible != actorReadU8(*actor, kActorVisible) || rectChanged) {
-		if (oldRect.area)
-			videoFindBestMode(oldRect);
+	if (_videoMode == 2) {
+		byte newVisible = actorReadU8(*actor, kActorVisible);
+		bool changed = oldSelector != selector || oldVisible != newVisible;
+		if (newRectValid && (oldRect.left != newRect.left || oldRect.top != newRect.top ||
+				oldRect.right != newRect.right || oldRect.bottom != newRect.bottom || oldRect.area != newRect.area))
+			changed = true;
+
+		if (!newRectValid && oldRect.area)
+			changed = true;
+
+		uint16 oldScriptedLastRect = 0xFFFF;
+		if (oldScripted) {
+			VideoRectRecord maskRecord = oldRect;
+			oldScriptedLastRect = scriptEvalKeyMask(oldSelector & 0x00FFFFFF, 0, maskRecord,
+				_keymaskOldRects, oldRect.left, oldRect.top);
+			if (oldScriptedLastRect >= COMFY_RESOLUTION_CHANGE_CAPACITY)
+				oldScriptedLastRect = COMFY_RESOLUTION_CHANGE_CAPACITY - 1;
+		}
+
+		if (changed) {
+			bool comparedScriptRects = false;
+			if (newScripted && oldScripted && oldSelector == selector &&
+					oldRect.left == _keymaskCurrentRecord.left && oldRect.top == _keymaskCurrentRecord.top &&
+					scriptedLastRect != 0xFFFF && oldScriptedLastRect != 0xFFFF) {
+				uint16 last = MAX(scriptedLastRect, oldScriptedLastRect);
+				for (uint i = 0; i <= last; i++) {
+					VideoRectRecord *oldItem = i <= oldScriptedLastRect ? &_keymaskOldRects[i] : nullptr;
+					VideoRectRecord *newItem = i <= scriptedLastRect ? &_keymaskRects[i] : nullptr;
+					bool equal = oldItem && newItem && oldItem->left == newItem->left && oldItem->top == newItem->top &&
+						oldItem->right == newItem->right && oldItem->bottom == newItem->bottom && oldItem->area == newItem->area;
+					if (!equal) {
+						if (oldItem && oldItem->area)
+							videoFindBestMode(*oldItem);
+
+						if (newItem && newItem->area)
+							videoFindBestMode(*newItem);
+					}
+				}
 
-		if (newRect.area)
-			videoFindBestMode(newRect);
+				comparedScriptRects = true;
+			} else if (newScripted) {
+				for (uint i = 0; i <= scriptedLastRect; i++) {
+					if (_keymaskRects[i].area)
+						videoFindBestMode(_keymaskRects[i]);
+				}
+			} else if (newRectValid && newRect.area) {
+				videoFindBestMode(newRect);
+			}
+
+			if (!comparedScriptRects) {
+				if (oldScripted) {
+					for (uint i = 0; i <= oldScriptedLastRect; i++) {
+						if (_keymaskOldRects[i].area)
+							videoFindBestMode(_keymaskOldRects[i]);
+					}
+				} else if (oldRect.area) {
+					videoFindBestMode(oldRect);
+				}
+			}
+		}
+
+		actorWriteU8(*actor, kActorCachedVisible, newVisible);
+		actorWriteU32(*actor, kActorCachedSprite, selector);
+		if (newRectValid) {
+			actorWriteCachedRect(*actor, newRect);
+		} else if (!selector) {
+			VideoRectRecord empty;
+			actorWriteCachedRect(*actor, empty);
+		}
 	}
 
-	actorWriteU8(*actor, kActorCachedVisible, actorReadU8(*actor, kActorVisible));
-	actorWriteU32(*actor, kActorCachedSprite, selector);
-	actorWriteCachedRect(*actor, newRect);
 	actorDrawList(actorReadU16(*actor, kActorChildHead), drawX, drawY);
 	return animFrameShouldDraw(2);
 }
diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
index 3ce3353960e..25ccef08814 100644
--- a/engines/comfy/anim_file.cpp
+++ b/engines/comfy/anim_file.cpp
@@ -61,8 +61,8 @@ void ComfyEngine::animFileShutdown(bool closeFile) {
 		if (_animCurrentFrameKey)
 			keyBitSet(_animCurrentFrameKey);
 
-		if (_animCurrentActorSceneHandle < _sceneHandles.size()) {
-			Actor *actor = actorGetPtr(sceneGetHandle(_animCurrentActorSceneHandle));
+		if (_animCurrentAnimId < _sceneHandles.size()) {
+			Actor *actor = actorGetPtr(sceneGetHandle(_animCurrentAnimId));
 			if (actor)
 				actorWriteU32(*actor, kActorSpriteSelector, 0);
 		}
@@ -70,6 +70,7 @@ void ComfyEngine::animFileShutdown(bool closeFile) {
 
 	_animActive = false;
 	_animCurrentIndex = 0;
+	_animCurrentAnimId = 0;
 	_animCurrentActorSceneHandle = 0;
 	_animCurrentFrameKey = 0;
 	_animVocClockHz = 0;
@@ -107,6 +108,7 @@ void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 ac
 	_animPendingDirtyRectSize = 0;
 	_animPosition = offset + COMFY_ANMFILE_HEADER_BYTES;
 	_animCurrentIndex = animIndex;
+	_animCurrentAnimId = actorSceneHandle;
 	_animCurrentActorSceneHandle = actorSceneHandle;
 	_animCurrentFrameKey = frameKey;
 	_animVocCounterMode = 0;
@@ -395,11 +397,13 @@ void ComfyEngine::animFrameRecordVocCounter(uint16 phase) {
 	if (phase == 1) {
 		_animVocCounterStartA = counter;
 	} else if (phase == 2) {
-		_animVocDeltaA = uint16(counter - _animVocCounterStartA);
+		_animVocCounterEndA = counter;
+		_animVocDeltaA = uint16(_animVocCounterEndA - _animVocCounterStartA);
 	} else if (phase == 3) {
 		_animVocCounterStartB = counter;
 	} else if (phase == 4) {
-		_animVocBaseCounter = uint16(counter - _animVocCounterStartB);
+		_animVocCounterEndB = counter;
+		_animVocBaseCounter = uint16(_animVocCounterEndB - _animVocCounterStartB);
 	}
 }
 
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 98b1630a8a5..d7cf14ed245 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -89,7 +89,7 @@ Common::Error ComfyEngine::gameInit() {
 
 	timerInit();
 	_gameInitialized = true;
-	uint16 currentScene = _language;
+	_currentScene = _language;
 	uint16 chooserScene = 2;
 	if (_multiLanguage && (ConfMan.getBool("force_language_setup") ||
 			!ConfMan.getBool("comfy_language_chosen"))) {
@@ -98,9 +98,9 @@ Common::Error ComfyEngine::gameInit() {
 			return Common::kNoGameDataFoundError;
 		}
 
-		uint16 selectedLanguage = sceneRun(currentScene, true, false);
+		uint16 selectedLanguage = sceneRun(_currentScene, true, false);
 		if (selectedLanguage) {
-			currentScene = selectedLanguage;
+			_currentScene = selectedLanguage;
 			chooserScene = selectedLanguage;
 			iniWriteLanguage(selectedLanguage);
 		}
@@ -110,28 +110,28 @@ Common::Error ComfyEngine::gameInit() {
 	}
 
 	if (iniGetGameDataPath(0)) {
-		sceneRun(currentScene, false, true);
+		sceneRun(_currentScene, false, true);
 		if (shouldQuit()) {
 			gameShutdown();
 			return Common::kNoError;
 		}
 	}
 
-	while (currentScene && !shouldQuit()) {
-		if (!iniGetGameDataPath(currentScene)) {
+	while (_currentScene && !shouldQuit()) {
+		if (!iniGetGameDataPath(_currentScene)) {
 			gameShutdown();
 			return Common::kNoGameDataFoundError;
 		}
 
-		if (currentScene == 0x63) {
-			currentScene = sceneRun(chooserScene, _multiLanguage, false);
+		if (_currentScene == 0x63) {
+			_currentScene = sceneRun(chooserScene, _multiLanguage, false);
 		} else {
-			chooserScene = currentScene;
-			currentScene = sceneRun(currentScene, _multiLanguage, false);
+			chooserScene = _currentScene;
+			_currentScene = sceneRun(_currentScene, _multiLanguage, false);
 		}
 
-		if (currentScene && currentScene != 0x63)
-			iniWriteLanguage(currentScene);
+		if (_currentScene && _currentScene != 0x63)
+			iniWriteLanguage(_currentScene);
 	}
 
 	gameShutdown();
@@ -153,6 +153,10 @@ void ComfyEngine::gameShutdown() {
 	if (_videoInitialized)
 		videoShutdown(0);
 
+	_sceneRunBuffer.clear();
+	_sceneRunPtr = nullptr;
+	_languageSessionRestartRequested = false;
+	_currentScene = 0;
 	_gameInitialized = false;
 }
 
@@ -168,31 +172,63 @@ void ComfyEngine::timerShutdown() {
 }
 
 uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
-	Common::Array<byte> sceneRunBuffer;
-	sceneRunBuffer.resize(0x10010);
-	memset(&sceneRunBuffer[0], 0, sceneRunBuffer.size());
-	if (!assetsLoad(0x4000, &sceneRunBuffer[0])) {
+	byte restorePalette = 1;
+	byte shouldStartNext = 0;
+	uint16 nextScene = 0;
+	_lptKeyboardInitialized = true;
+
+	if (_sceneRunBuffer.empty()) {
+		_sceneRunBuffer.resize(0x10010);
+		memset(&_sceneRunBuffer[0], 0, _sceneRunBuffer.size());
+	}
+
+	_sceneRunPtr = _sceneRunBuffer.data();
+
+	if (!assetsLoad(0x4000, _sceneRunPtr)) {
 		assetsUnload(0);
+		if (_engineVersion != kEngineVersion3) {
+			_sceneRunBuffer.clear();
+			_sceneRunPtr = nullptr;
+		}
+
 		if (_videoInitialized)
 			videoShutdown(0);
 
+		_lptKeyboardInitialized = false;
 		return 0;
 	}
 
 	gameMainLoop(sceneId);
-	uint16 nextScene = 0;
-	if (checkNext && sceneGetActiveCount() > 1 && _midiHandles.size() > 1)
-		nextScene = _midiHandles[1];
+	if (_engineVersion == kEngineVersion3 && _languageSessionRestartRequested) {
+		nextScene = sceneId;
+		_languageSessionRestartRequested = false;
+	} else if (checkNext) {
+		if (sceneGetActiveCount() > 1 && _midiHandles.size() > 1)
+			nextScene = _midiHandles[1];
+
+		if (int16(nextScene) > 0 && int16(nextScene) < 0x65 && nextScene != sceneId)
+			shouldStartNext = 1;
+
+		if (_engineVersion == kEngineVersion3)
+			shouldStartNext = 1;
+	}
 
-	if (nextScene == sceneId || int16(nextScene) <= 0 || int16(nextScene) >= 0x65)
-		nextScene = 0;
+	if (exitFlag || shouldStartNext)
+		restorePalette = 0;
 
-	byte restorePalette = !exitFlag && !nextScene;
+	if (_engineVersion == kEngineVersion3)
+		soundShutdown();
 
 	midiShutdown();
 	assetsUnload(0);
 	inputQueueReset();
+	if (_engineVersion != kEngineVersion3) {
+		_sceneRunBuffer.clear();
+		_sceneRunPtr = nullptr;
+	}
+
 	videoShutdown(restorePalette);
+	_lptKeyboardInitialized = false;
 
 	return nextScene;
 }
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 6320d098d2b..7173122b680 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -96,6 +96,14 @@ private:
 		int16 right;
 		int16 bottom;
 		uint16 area;
+
+		VideoRectRecord() {
+			left = 0;
+			top = 0;
+			right = 0;
+			bottom = 0;
+			area = 0;
+		}
 	};
 
 	struct InputQueue {
@@ -315,6 +323,7 @@ private:
 	Common::Path _gameDirectory;
 	Common::Path _introDirectory;
 	Common::Path _gameDataPath;
+	bool _hasDataPath = false;
 	Common::Path _languageDirectories[16];
 	uint16 _language = 2;
 	bool _multiLanguage = true;
@@ -324,6 +333,14 @@ private:
 	byte *_presentBuffer = nullptr;
 	uint16 _logicalScreenWidth;
 	uint16 _logicalScreenHeight;
+	uint16 _videoMode = 2;
+	int16 _videoScale = 1;
+	uint16 _screenWidth = 0;
+	uint16 _screenHeight = 0;
+	uint16 _renderWidth = 0;
+	uint16 _renderHeight = 0;
+	int16 _viewOffsetX = 0;
+	int16 _viewOffsetY = 0;
 	VideoRectRecord _resolutionChanges[COMFY_RESOLUTION_CHANGE_CAPACITY];
 	uint16 _resolutionChangeCount = 0;
 	uint16 _renderDirtyCount = 0;
@@ -363,6 +380,7 @@ private:
 	uint32 _toyKeyboardLatchedMask = 0;
 	uint32 _toyKeyboardHoldMask = 0;
 	uint32 _lptPrevScanState = 0;
+	uint16 _lptPortBase = 0x0378;
 	uint16 _inputDeviceMode = 0;
 	uint16 _inputDevicePreference = 0;
 	uint32 _inputPreviousComfyboardState = 0;
@@ -384,6 +402,11 @@ private:
 	uint16 _midiEntryCount = 0;
 	uint32 _picDataSize = 0;
 	bool _usesAnimFile = false;
+	bool _picFileDatOpen = false;
+	bool _comfyObjOpen = false;
+	bool _xmsEnvAllocated = false;
+	bool _soundLoaded = false;
+	bool _picFileMapped = false;
 	bool _sceneOpen = false;
 	bool _sceneEntryListActive = false;
 	Common::Array<uint16> _stringTable;
@@ -391,6 +414,8 @@ private:
 	Common::Array<uint16> _midiHandles;
 	Common::Array<Actor> _actors;
 	Common::Array<byte> _sceneMemoryBlock;
+	Common::Array<byte> _sceneRunBuffer;
+	byte *_sceneRunPtr = nullptr;
 	Common::Array<byte> _scenePoolData;
 	Common::Array<byte> _environmentData;
 	Common::Array<byte> _headerXmsData;
@@ -398,6 +423,17 @@ private:
 	Common::Array<SpriteCacheEntry> _objectCacheEntries;
 	Common::Array<SpriteCacheEntry> _frameCacheEntries;
 	ResourceLoadList _spriteConversionLoads;
+	SpriteObjectHeader _spriteLastHeader;
+	uint32 _keymaskBits = 0;
+	uint16 _keymaskLastIndex = 0xFFFF;
+	uint16 _keymaskCount = 0;
+	uint16 _keymaskSpriteWord = 0;
+	uint16 _keymaskArg0 = 0;
+	uint16 _keymaskArg1 = 0;
+	uint16 _keymaskResult = 0;
+	VideoRectRecord _keymaskCurrentRecord;
+	VideoRectRecord _keymaskRects[COMFY_RESOLUTION_CHANGE_CAPACITY];
+	VideoRectRecord _keymaskOldRects[COMFY_RESOLUTION_CHANGE_CAPACITY];
 	uint32 _sceneEntryOffsets[COMFY_SCENE_ENTRY_OFFSET_CAPACITY];
 	uint32 _sceneMidiInstanceOffset = 0;
 	uint32 _sceneEntryListOffset = 0;
@@ -429,11 +465,13 @@ private:
 	bool _mirrorMode = false;
 	uint32 _actorPcTable[COMFY_ACTOR_PC_TABLE_COUNT];
 	uint16 _currentActor = 0;
+	uint16 _currentScene = 0;
 	uint16 _pendingScene = 0;
 	uint16 _musicEventMask = 0;
 	byte _musicEventFlag = 0;
 	bool _musicEnabled = false;
 	bool _usesWcomfy99ScriptOps = false;
+	bool _languageSessionRestartRequested = false;
 	uint16 _wcomfy99FeatureWords[16];
 	byte _wcomfy99FeatureWordCount = 0;
 	uint16 _wcomfy99Sensitivity = 0;
@@ -482,6 +520,7 @@ private:
 	uint32 _animPosition = 0;
 	uint16 _animPendingDirtyRectSize = 0;
 	uint16 _animCurrentIndex = 0;
+	uint16 _animCurrentAnimId = 0;
 	uint16 _animCurrentActorSceneHandle = 0;
 	uint16 _animCurrentFrameKey = 0;
 	byte _animVocCounterMode = 0;
@@ -490,7 +529,9 @@ private:
 	uint16 _animVocBaseCounter = 0;
 	uint16 _animVocDeltaA = 0;
 	uint32 _animVocCounterStartA = 0;
+	uint32 _animVocCounterEndA = 0;
 	uint32 _animVocCounterStartB = 0;
+	uint32 _animVocCounterEndB = 0;
 	bool _animIndexLoaded = false;
 	bool _animPantherFormat = false;
 	bool _animActive = false;
@@ -639,7 +680,10 @@ private:
 	bool actorTickTree(uint16 actorIndex);
 	bool actorDraw(uint16 actorIndex, int16 x, int16 y);
 	void actorDrawList(uint16 actorIndex, int16 x, int16 y);
-	void actorDrawScripted(uint16 actorIndex, uint32 selector, int16 x, int16 y);
+	uint16 scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &maskRecord,
+		VideoRectRecord *rects, int16 baseX, int16 baseY);
+	void actorEvalFrameSelection(uint16 actorIndex, int16 x, int16 y);
+	uint16 actorDrawScripted(uint16 actorIndex, uint32 selector, int16 x, int16 y);
 	VideoRectRecord actorReadCachedRect(Actor &actor);
 	void actorWriteCachedRect(Actor &actor, VideoRectRecord rect);
 	void actorInvalidateDrawTree(uint16 actorIndex);
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index b8767eca5fc..e80f515cf07 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -194,10 +194,11 @@ Common::Path ComfyEngine::getLanguageDirectory(uint16 language) {
 
 void ComfyEngine::pathSetGameDataDir(const Common::Path &path) {
 	_gameDataPath = path;
+	_hasDataPath = !_gameDataPath.empty();
 }
 
 Common::Path ComfyEngine::pathBuild(const Common::Path &filename, bool useGamePath) {
-	if (useGamePath && !_gameDataPath.empty())
+	if (useGamePath && _hasDataPath)
 		return _gameDataPath.join(filename);
 
 	return filename;
@@ -239,6 +240,7 @@ bool ComfyEngine::comfyObjOpen() {
 	_resourceHandleCount = assetsReadLe16At(_comfyObjData, 0x12);
 	_usesAnimFile = (_resourceHandleCount & 0x8000) != 0;
 	_resourceHandleCount &= 0x7FFF;
+	_comfyObjOpen = true;
 	return true;
 }
 
@@ -261,6 +263,7 @@ bool ComfyEngine::picFileOpen() {
 		_spriteResources[i].loaded = false;
 	}
 
+	_picFileDatOpen = true;
 	return true;
 }
 
@@ -407,6 +410,8 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	if (!soundInit()) {
 		return false;
 	}
+	_soundLoaded = true;
+	_picFileMapped = true;
 
 	_numFrames = _picDataSize / COMFY_TILE_SIZE + (_picDataSize % COMFY_TILE_SIZE ? 2 : 1);
 	_numObjects = _spriteHeaders.size();
@@ -418,6 +423,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	_environmentData.resize(environmentBytes);
 	if (environmentBytes)
 		memset(&_environmentData[0], 0, environmentBytes);
+	_xmsEnvAllocated = !_environmentData.empty();
 
 	uint32 midiHeaderBytes = assetsAlignEven32(uint32(_midiEntryCount) * 6);
 	uint16 soundTileStride = 0;
@@ -558,8 +564,7 @@ void ComfyEngine::assetsUnload(byte freeAudio) {
 	_objectCacheEntries.clear();
 	_frameCacheEntries.clear();
 	keyBitFree();
-	if (!_vocFileData.empty())
-		soundShutdown();
+	soundShutdown();
 
 	if (_sceneOpen)
 		sceneShutdown();
@@ -600,6 +605,11 @@ void ComfyEngine::assetsUnload(byte freeAudio) {
 	_resourceHandleCount = 0;
 	_midiEntryCount = 0;
 	_picDataSize = 0;
+	_picFileDatOpen = false;
+	_comfyObjOpen = false;
+	_xmsEnvAllocated = false;
+	_soundLoaded = false;
+	_picFileMapped = false;
 	_numFrames = 0;
 	_numObjects = 0;
 	_numSprites = 0;
diff --git a/engines/comfy/input.cpp b/engines/comfy/input.cpp
index 935779c217f..6d33d09c657 100644
--- a/engines/comfy/input.cpp
+++ b/engines/comfy/input.cpp
@@ -343,9 +343,6 @@ void ComfyEngine::lptKeyboardDispatchEvents(uint32 scanState) {
 }
 
 void ComfyEngine::lptKeyboardInit() {
-	if (_lptKeyboardInitialized)
-		return;
-
 	inputQueueReset();
 	hostKeyboardLoadDatMap();
 	_lptPrevScanState = 0;
@@ -354,13 +351,12 @@ void ComfyEngine::lptKeyboardInit() {
 	_inputPreviousKeyboardState = 0;
 	_inputComfyboardActivityCount = 0;
 	_inputKeyboardActivityCount = 0;
-	_lptKeyboardInitialized = true;
 	_keyboardUiVisible = true;
 	if (_engineVersion == kEngineVersion3 && _midiPlyrDriver) {
 		if (!_inputDeviceMode)
 			_midiPlyrDriver->comfyboardStartSleepUse();
 
-		_midiPlyrDriver->comfyboardStartReading(0x006D96DB, 0x0378);
+		_midiPlyrDriver->comfyboardStartReading(0x006D96DB, _lptPortBase);
 	}
 
 #ifdef USE_IMGUI
@@ -396,7 +392,6 @@ void ComfyEngine::lptKeyboardShutdown() {
 	_toyKeyboardActiveMask = 0;
 	_toyKeyboardLatchedMask = 0;
 	_toyKeyboardHoldMask = 0;
-	_lptKeyboardInitialized = false;
 }
 
 } // End of namespace Comfy
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 1ab1800a5c9..7064c2e4bda 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -606,10 +606,14 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 					keyBitSet(value);
 				else
 					keyBitClear(value);
-			} else if (subop == 6 && value < _stringTable.size()) {
+			} else if (subop == 6) {
 				byte last = key.empty() ? 0 : key.lastChar();
-				_stringTable[value] = Common::isSpace(last) ? 0x81 : Common::isDigit(last) ? 0x12 :
-					(Common::isAlpha(last) ? (Common::isUpper(last) ? 0x04 : 0x08) : 0x40);
+				if (value < _stringTable.size())
+					_stringTable[value] = Common::isSpace(last) ? 0x81 : Common::isDigit(last) ? 0x12 :
+						(Common::isAlpha(last) ? (Common::isUpper(last) ? 0x04 : 0x08) : 0x40);
+
+				pathSetGameDataDir(Common::Path(key));
+				_languageSessionRestartRequested = true;
 			}
 		} else if (opcode == 0x35) {
 			byte subop = scriptReadByte(pc++);
diff --git a/engines/comfy/video.cpp b/engines/comfy/video.cpp
index 1cd1ea72ffa..4699729b064 100644
--- a/engines/comfy/video.cpp
+++ b/engines/comfy/video.cpp
@@ -33,6 +33,14 @@ void ComfyEngine::videoInit() {
 	if (_videoInitialized)
 		return;
 
+	_videoMode = 2;
+	_videoScale = 1;
+	_screenWidth = _logicalScreenWidth;
+	_screenHeight = _logicalScreenHeight;
+	_renderWidth = _screenWidth;
+	_renderHeight = _screenHeight;
+	_viewOffsetX = 0;
+	_viewOffsetY = 0;
 	initGraphics(_logicalScreenWidth, _logicalScreenHeight);
 	_screen = new Graphics::Screen(_logicalScreenWidth, _logicalScreenHeight);
 	_framebufPtr = new byte[framebufferBytes()]();


Commit: 7e49c132682c01360e7719d315366176842a4e3f
    https://github.com/scummvm/scummvm/commit/7e49c132682c01360e7719d315366176842a4e3f
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Fix things along the code after audit

Changed paths:
  R engines/comfy/entry.cpp
    engines/comfy/actor.cpp
    engines/comfy/anim_file.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/expr.cpp
    engines/comfy/game.cpp
    engines/comfy/input.cpp
    engines/comfy/midi.cpp
    engines/comfy/module.mk
    engines/comfy/palette.cpp
    engines/comfy/scene.cpp
    engines/comfy/script_vm.cpp
    engines/comfy/sound.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index 9d3b9ef8983..d9994a4741e 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -27,12 +27,23 @@ namespace Comfy {
 
 bool ComfyEngine::spriteDecompressTile(SpriteResource &sprite, const byte *source, uint32 sourceSize) {
 	uint32 outputSize = sprite.header.tiledSize;
+	_spriteDecompressLastSize = 0;
+	_spriteDecompressLastComplete = false;
 	if (!source || !sourceSize || !sprite.header.width || !sprite.header.height || !outputSize)
 		return false;
 
+	// The original temporarily writes a zero sentinel at source[dataSize].
+	Common::Array<byte> sourceWithSentinel;
+	sourceWithSentinel.resize(sourceSize + 1);
+	memcpy(&sourceWithSentinel[0], source, sourceSize);
+	sourceWithSentinel[sourceSize] = 0;
+	source = &sourceWithSentinel[0];
+	uint32 sourceEnd = sourceSize + 1;
+
 	sprite.pixels.resize(outputSize);
 	uint32 sourcePos = 0;
 	uint32 outputPos = 0;
+	uint16 totalOutput = 0;
 	uint16 skipCount = 0;
 	uint16 fillCount = 0;
 	uint16 literalCount = 0;
@@ -41,7 +52,7 @@ bool ComfyEngine::spriteDecompressTile(SpriteResource &sprite, const byte *sourc
 
 	for (uint row = 0; row < sprite.header.height; row++) {
 		if (outputPos + 2 > outputSize)
-			return false;
+			break;
 
 		uint32 rowStart = outputPos;
 		outputPos += 2;
@@ -51,21 +62,15 @@ bool ComfyEngine::spriteDecompressTile(SpriteResource &sprite, const byte *sourc
 
 		while (pixelsLeft) {
 			if (!skipCount && !fillCount && !literalCount) {
-				if (sourcePos >= sourceSize)
-					return false;
-
-				byte op = source[sourcePos++];
+				byte op = sourcePos < sourceEnd ? source[sourcePos++] : 0;
 				if (op & 0x40) {
 					skipCount = op - 0x40;
-					while (sourcePos < sourceSize && (source[sourcePos] & 0x40))
+					while (sourcePos < sourceEnd && (source[sourcePos] & 0x40))
 						skipCount += source[sourcePos++] - 0x40;
 				} else if (op & 0x80) {
 					fillCount = op - 0x80;
-					if (sourcePos >= sourceSize)
-						return false;
-
-					fillValue = source[sourcePos++];
-					while (sourcePos < sourceSize && (source[sourcePos] & 0xC0) == 0xC0)
+					fillValue = sourcePos < sourceEnd ? source[sourcePos++] : 0;
+					while (sourcePos < sourceEnd && (source[sourcePos] & 0xC0) == 0xC0)
 						fillCount += source[sourcePos++] - 0xC0;
 				} else {
 					literalCount = op;
@@ -86,12 +91,15 @@ bool ComfyEngine::spriteDecompressTile(SpriteResource &sprite, const byte *sourc
 
 				uint16 count = MIN<uint16>(pixelsLeft, literalCount);
 				count = MIN<uint16>(count, 0x3F - literalPacketLength);
-				if (outputPos + count > outputSize || (!literalFromFill && sourcePos + count > sourceSize))
-					return false;
+				if (outputPos + count > outputSize)
+					count = outputSize - outputPos;
 
-				if (literalFromFill)
+				if (literalFromFill) {
 					memset(&sprite.pixels[outputPos], fillValue, count);
-				else {
+				} else {
+					if (count > sourceEnd - sourcePos)
+						count = sourceEnd - sourcePos;
+
 					memcpy(&sprite.pixels[outputPos], source + sourcePos, count);
 					sourcePos += count;
 				}
@@ -131,10 +139,16 @@ bool ComfyEngine::spriteDecompressTile(SpriteResource &sprite, const byte *sourc
 			}
 		}
 
-		WRITE_LE_UINT16(&sprite.pixels[rowStart], outputPos - rowStart);
+		uint16 rowSize = outputPos - rowStart;
+		WRITE_LE_UINT16(&sprite.pixels[rowStart], rowSize);
+		totalOutput += rowSize;
+		if (totalOutput > outputSize)
+			break;
 	}
 
-	return outputPos == outputSize;
+	_spriteDecompressLastSize = totalOutput;
+	_spriteDecompressLastComplete = totalOutput == outputSize;
+	return _spriteDecompressLastComplete;
 }
 
 void ComfyEngine::spriteInvalidateHostCache(SpriteResource &sprite) {
@@ -147,11 +161,10 @@ void ComfyEngine::objHdrReadFromXms(byte *destination, uint32 base, uint16 size,
 		return;
 
 	uint32 offset = base + uint32(size) * row;
-	if (offset >= _headerXmsData.size())
-		return;
+	if (offset > _headerXmsData.size() || size > _headerXmsData.size() - offset)
+		error("Headers move (XMS->memory)");
 
-	uint16 copySize = MIN<uint32>(size, _headerXmsData.size() - offset);
-	memcpy(destination, &_headerXmsData[offset], copySize);
+	memcpy(destination, &_headerXmsData[offset], size);
 }
 
 void ComfyEngine::objHdrRead(SpriteObjectHeader &destination, uint16 index) {
@@ -176,12 +189,15 @@ void ComfyEngine::scenePoolEvict() {
 	byte *entry = &_scenePoolData[_scenePoolEvictCursor];
 	int16 id = int16(READ_LE_UINT16(entry));
 	uint16 slotSize = READ_LE_UINT16(entry + 2);
-	if (id > 0 && uint16(id) < _spriteResources.size()) {
-		spriteInvalidateHostCache(_spriteResources[id]);
-		_objectCacheEntries[id].slotSize = 0xFFFF;
-	} else if (id < 0) {
+	if (id > 0) {
+		if (uint16(id) < _spriteResources.size())
+			spriteInvalidateHostCache(_spriteResources[id]);
+
+		if (uint16(id) < _objectCacheEntries.size())
+			_objectCacheEntries[id].slotSize = 0xFFFF;
+	} else {
 		uint16 frameId = uint16(-id);
-		if (_frameSpriteResource.id == id)
+		if (_frameSpriteResource.id == frameId)
 			spriteInvalidateHostCache(_frameSpriteResource);
 
 		if (frameId < _frameCacheEntries.size())
@@ -222,6 +238,8 @@ void ComfyEngine::spriteCache(int16 spriteId) {
 	if (!spriteId)
 		return;
 
+	soundUnprepareHeader();
+
 	if (spriteId < 0) {
 		uint16 frameId = uint16(-spriteId);
 		uint32 fileOffset = uint32(frameId - 1) * COMFY_TILE_SIZE;
@@ -239,7 +257,7 @@ void ComfyEngine::spriteCache(int16 spriteId) {
 		WRITE_LE_UINT16(entryData, uint16(spriteId));
 		WRITE_LE_UINT16(entryData + 2, slotSize);
 		memcpy(entryData + 0x0C, &_comfyObjData[fileOffset], size);
-		_frameSpriteResource.id = spriteId;
+		_frameSpriteResource.id = frameId;
 		_frameSpriteResource.header = SpriteObjectHeader();
 		_frameSpriteResource.header.dataSize = size;
 		_frameSpriteResource.header.tiledSize = size;
@@ -279,9 +297,8 @@ void ComfyEngine::spriteCache(int16 spriteId) {
 	if (header.width == _logicalScreenWidth && header.height == _logicalScreenHeight) {
 		sprite.pixels.resize(header.dataSize);
 		memcpy(&sprite.pixels[0], source, header.dataSize);
-	} else if (!spriteDecompressTile(sprite, source, header.dataSize)) {
-		sprite.pixels.clear();
-		return;
+	} else {
+		spriteDecompressTile(sprite, source, header.dataSize);
 	}
 
 	uint16 payloadSize = sprite.pixels.size() + (sprite.pixels.size() & 1);
@@ -308,6 +325,38 @@ void ComfyEngine::spriteCache(int16 spriteId) {
 	sprite.loaded = true;
 }
 
+ComfyEngine::SpriteResource *ComfyEngine::spriteLookup(uint16 spriteId, int16 x, int16 y) {
+	if (spriteId >= _spriteResources.size())
+		return nullptr;
+
+	SpriteResource &sprite = _spriteResources[spriteId];
+	SpriteCacheEntry *entry = spriteId < _objectCacheEntries.size() ? &_objectCacheEntries[spriteId] : nullptr;
+	if (entry && entry->slotSize == 0xFFFF) {
+		SpriteObjectHeader header;
+		objHdrRead(header, spriteId);
+		sprite.header = header;
+	}
+
+	int16 left = x - sprite.header.hotspotX;
+	int16 top = y - sprite.header.hotspotY;
+	int16 right = left + int16(sprite.header.width) - 1;
+	int16 bottom = top + int16(sprite.header.height) - 1;
+	bool fullscreen = sprite.header.width == _logicalScreenWidth && sprite.header.height == _logicalScreenHeight;
+	bool offscreen = left > int16(_logicalScreenWidth - 1) || right < 0 ||
+		top > int16(_logicalScreenHeight - 1) || bottom < 0;
+
+	if (entry && entry->slotSize == 0xFFFF && !fullscreen && offscreen) {
+		_objFileOffset = _spriteLastHeader.fileOffset;
+		_objFileStride = _spriteLastHeader.tiledSize;
+		return nullptr;
+	}
+
+	if ((entry && entry->slotSize == 0xFFFF) || (!entry && !sprite.loaded))
+		spriteCache(int16(spriteId));
+
+	return &sprite;
+}
+
 ComfyEngine::SpriteResource *ComfyEngine::spriteGetPtr(int16 spriteId) {
 	if (spriteId > 0) {
 		if (uint16(spriteId) >= _spriteResources.size())
@@ -324,10 +373,10 @@ ComfyEngine::SpriteResource *ComfyEngine::spriteGetPtr(int16 spriteId) {
 
 	uint16 frameId = uint16(-spriteId);
 	if (frameId >= _frameCacheEntries.size() || _frameCacheEntries[frameId].slotSize == 0xFFFF ||
-			!_frameSpriteResource.loaded || _frameSpriteResource.id != spriteId)
+			!_frameSpriteResource.loaded || _frameSpriteResource.id != frameId)
 		spriteCache(spriteId);
 
-	return _frameSpriteResource.loaded && _frameSpriteResource.id == spriteId ? &_frameSpriteResource : nullptr;
+	return _frameSpriteResource.loaded && _frameSpriteResource.id == frameId ? &_frameSpriteResource : nullptr;
 }
 
 void ComfyEngine::spriteBlitRle(const byte *source, uint32 sourceSize) {
@@ -391,9 +440,8 @@ void ComfyEngine::spriteBlitClipped(int16 spriteId, int16 x, int16 y) {
 
 				byte value = sprite.pixels[packetPos++];
 				for (uint i = 0; i < count; i++, drawX++) {
-					int16 screenX = _mirrorMode ? int16(_logicalScreenWidth - 1 - drawX) : drawX;
-					if (screenX >= 0 && screenX < int16(_logicalScreenWidth) && drawY >= 0 && drawY < int16(_logicalScreenHeight))
-						_framebufPtr[drawY * _logicalScreenWidth + screenX] = value;
+					if (drawX >= 0 && drawX < int16(_logicalScreenWidth) && drawY >= 0 && drawY < int16(_logicalScreenHeight))
+						_framebufPtr[drawY * _logicalScreenWidth + drawX] = value;
 				}
 			} else if (op & 0x40) {
 				drawX += count;
@@ -403,9 +451,8 @@ void ComfyEngine::spriteBlitClipped(int16 spriteId, int16 x, int16 y) {
 
 				for (uint i = 0; i < count; i++, drawX++) {
 					byte value = sprite.pixels[packetPos++];
-					int16 screenX = _mirrorMode ? int16(_logicalScreenWidth - 1 - drawX) : drawX;
-					if (screenX >= 0 && screenX < int16(_logicalScreenWidth) && drawY >= 0 && drawY < int16(_logicalScreenHeight))
-						_framebufPtr[drawY * _logicalScreenWidth + screenX] = value;
+					if (drawX >= 0 && drawX < int16(_logicalScreenWidth) && drawY >= 0 && drawY < int16(_logicalScreenHeight))
+						_framebufPtr[drawY * _logicalScreenWidth + drawX] = value;
 				}
 			}
 		}
@@ -417,28 +464,22 @@ void ComfyEngine::spriteBlitClipped(int16 spriteId, int16 x, int16 y) {
 }
 
 uint32 ComfyEngine::actorReadU32(Actor &actor, uint offset) {
-	if (offset + 4 > COMFY_ACTOR_SIZE) {
-		_scriptFault = true;
+	if (offset + 4 > COMFY_ACTOR_SIZE)
 		return 0;
-	}
 
 	return READ_LE_UINT32(actor.raw + offset);
 }
 
 uint16 ComfyEngine::actorReadU16(Actor &actor, uint offset) {
-	if (offset + 2 > COMFY_ACTOR_SIZE) {
-		_scriptFault = true;
+	if (offset + 2 > COMFY_ACTOR_SIZE)
 		return 0;
-	}
 
 	return READ_LE_UINT16(actor.raw + offset);
 }
 
 byte ComfyEngine::actorReadU8(Actor &actor, uint offset) {
-	if (offset >= COMFY_ACTOR_SIZE) {
-		_scriptFault = true;
+	if (offset >= COMFY_ACTOR_SIZE)
 		return 0;
-	}
 
 	return actor.raw[offset];
 }
@@ -446,22 +487,16 @@ byte ComfyEngine::actorReadU8(Actor &actor, uint offset) {
 void ComfyEngine::actorWriteU32(Actor &actor, uint offset, uint32 value) {
 	if (offset + 4 <= COMFY_ACTOR_SIZE)
 		WRITE_LE_UINT32(actor.raw + offset, value);
-	else
-		_scriptFault = true;
 }
 
 void ComfyEngine::actorWriteU16(Actor &actor, uint offset, uint16 value) {
 	if (offset + 2 <= COMFY_ACTOR_SIZE)
 		WRITE_LE_UINT16(actor.raw + offset, value);
-	else
-		_scriptFault = true;
 }
 
 void ComfyEngine::actorWriteU8(Actor &actor, uint offset, byte value) {
 	if (offset < COMFY_ACTOR_SIZE)
 		actor.raw[offset] = value;
-	else
-		_scriptFault = true;
 }
 
 ComfyEngine::Actor *ComfyEngine::actorGetPtr(uint16 actorIndex) {
@@ -589,11 +624,25 @@ uint16 ComfyEngine::actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible,
 	actorWriteU8(*actor, kActorVisible, visible);
 	actorWriteU8(*actor, kActorActive, active);
 	actorWriteU32(*actor, kActorCurrentPc, pc);
+	actorWriteU32(*actor, kActorCallPc, 0);
 	actorWriteU32(*actor, kActorResetPc, pc);
 	actorWriteU32(*actor, kActorXFixed, uint32(int32(x) * 0x1000));
 	actorWriteU32(*actor, kActorYFixed, uint32(int32(y) * 0x1000));
 	actorWriteU32(*actor, kActorSpriteSelector, uint32(int32(sprite)));
+	actorWriteU16(*actor, kActorChildTail, 0);
+	actorWriteU16(*actor, kActorChildHead, 0);
+	actorWriteU16(*actor, kActorSiblingHead, 0);
+	actorWriteU16(*actor, kActorMoveTicks, 0);
+	actorWriteU16(*actor, kActorTriggerKey, 0);
+	actorWriteU16(*actor, kActorWaitTarget, 0);
+	actorWriteU16(*actor, kActorWaitAccum, 0);
 	actorWriteU8(*actor, kActorDirty, 1);
+	if (_videoMode == 2) {
+		VideoRectRecord empty;
+		actorWriteCachedRect(*actor, empty);
+		actorWriteU32(*actor, kActorCachedSprite, 0);
+		actorWriteU8(*actor, kActorCachedVisible, 0);
+	}
 
 	if (parentSlot) {
 		uint16 parentIndex = sceneGetHandle(parentSlot);
@@ -602,6 +651,10 @@ uint16 ComfyEngine::actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible,
 			actorInsertChild(actorIndex, parentIndex);
 		else
 			actorInsertSibling(actorIndex, parentIndex);
+	} else {
+		actorWriteU16(*actor, kActorParent, 0);
+		actorWriteU16(*actor, kActorNextLink, 0);
+		actorWriteU16(*actor, kActorPrevLink, 0);
 	}
 
 	return 1;
@@ -612,11 +665,6 @@ void ComfyEngine::actorSetPc(Actor &actor, uint32 pc) {
 	uint32 packed = pc;
 	if (previous) {
 		byte entry = _actorPcTable[0] >> 24;
-		if (!entry || entry >= COMFY_ACTOR_PC_TABLE_COUNT) {
-			_scriptFault = true;
-			return;
-		}
-
 		_actorPcTable[0] = _actorPcTable[entry];
 		_actorPcTable[entry] = previous;
 		if (_sceneActorPcOffset + sizeof(_actorPcTable) <= _sceneMemoryBlock.size()) {
@@ -624,7 +672,7 @@ void ComfyEngine::actorSetPc(Actor &actor, uint32 pc) {
 			WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneActorPcOffset + entry * 4], _actorPcTable[entry]);
 		}
 
-		packed = (uint32(entry) << 24) | (pc & 0x00FFFFFF);
+		packed = (uint32(entry) << 24) + pc;
 	}
 
 	actorWriteU32(actor, kActorCallPc, packed);
@@ -633,7 +681,7 @@ void ComfyEngine::actorSetPc(Actor &actor, uint32 pc) {
 uint32 ComfyEngine::actorPopPc(Actor &actor) {
 	uint32 packed = actorReadU32(actor, kActorCallPc);
 	byte entry = packed >> 24;
-	if (entry && entry < COMFY_ACTOR_PC_TABLE_COUNT) {
+	if (entry) {
 		actorWriteU32(actor, kActorCallPc, _actorPcTable[entry]);
 		_actorPcTable[entry] = _actorPcTable[0];
 		_actorPcTable[0] = uint32(entry) << 24;
@@ -651,7 +699,7 @@ uint32 ComfyEngine::actorPopPc(Actor &actor) {
 void ComfyEngine::actorFreePcChain(Actor &actor) {
 	byte first = actorReadU32(actor, kActorCallPc) >> 24;
 	byte entry = first;
-	while (entry && entry < COMFY_ACTOR_PC_TABLE_COUNT) {
+	while (entry) {
 		byte next = _actorPcTable[entry] >> 24;
 		if (!next) {
 			_actorPcTable[entry] = _actorPcTable[0];
@@ -669,16 +717,23 @@ void ComfyEngine::actorFreePcChain(Actor &actor) {
 	actorWriteU32(actor, kActorCallPc, 0);
 }
 
-void ComfyEngine::actorFreeTree(uint16 actorIndex) {
+void ComfyEngine::actorFreeTreePc(uint16 actorIndex) {
 	Actor *actor = actorGetPtr(actorIndex);
 	if (!actor)
 		return;
 
+	if (_videoMode == 2) {
+		VideoRectRecord rect = actorReadCachedRect(*actor);
+		videoFindBestMode(rect);
+	}
+
+	actorFreePcChain(*actor);
+
 	uint16 child = actorReadU16(*actor, kActorSiblingHead);
 	while (child) {
 		Actor *childActor = actorGetPtr(child);
 		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
-		actorFreeTree(child);
+		actorFreeTreePc(child);
 		child = next;
 	}
 
@@ -686,12 +741,14 @@ void ComfyEngine::actorFreeTree(uint16 actorIndex) {
 	while (child) {
 		Actor *childActor = actorGetPtr(child);
 		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
-		actorFreeTree(child);
+		actorFreeTreePc(child);
 		child = next;
 	}
 
+	if (_usesAnimFile && actorReadU32(*actor, kActorSpriteSelector) == 0x00FFFFFF)
+		animFrameShutdown(true);
+
 	uint16 sceneSlot = actorReadU16(*actor, kActorSceneHandle);
-	actorFreePcChain(*actor);
 	actorFreeSlot(sceneSlot);
 }
 
@@ -753,6 +810,19 @@ bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
 		actorWriteU32(*actor, kActorCurrentPc, actorReadU32(*actor, kActorTriggerPc));
 	}
 
+	bool timerWaitYield = false;
+	int16 waitTarget = actorReadU16(*actor, kActorWaitTarget);
+	if (waitTarget) {
+		if (waitTarget > _timerCurrent) {
+			actorWriteU16(*actor, kActorWaitTarget, waitTarget - _timerCurrent);
+			timerWaitYield = true;
+		} else {
+			int16 elapsed = _timerCurrent - waitTarget;
+			actorWriteU16(*actor, kActorWaitAccum, actorReadU16(*actor, kActorWaitAccum) + elapsed);
+			actorWriteU16(*actor, kActorWaitTarget, 0);
+		}
+	}
+
 	int16 moveTicks = actorReadU16(*actor, kActorMoveTicks);
 	if (moveTicks) {
 		int16 stepTicks = int16(uint16(_timerCurrent + _timer0 + _timer1 + _timer2 + 2)) / 4;
@@ -791,35 +861,29 @@ bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
 			keyBitSet(actorReadU16(*actor, kActorCompletionKey));
 	}
 
-	int16 waitTarget = actorReadU16(*actor, kActorWaitTarget);
-	if (waitTarget) {
-		if (waitTarget > _timerCurrent) {
-			actorWriteU16(*actor, kActorWaitTarget, waitTarget - _timerCurrent);
-			if (_stringTable.size() > 3) {
-				actorWriteU16(*actor, kActorStringRef, _stringTable[2]);
-				actorWriteU16(*actor, kActorStringRef + 2, _stringTable[3]);
-			}
-
-			descendChildren = true;
-			return false;
+	if (timerWaitYield) {
+		if (_stringTable.size() > 3) {
+			actorWriteU16(*actor, kActorStringRef, _stringTable[2]);
+			actorWriteU16(*actor, kActorStringRef + 2, _stringTable[3]);
 		}
 
-		int16 elapsed = _timerCurrent - waitTarget;
-		actorWriteU16(*actor, kActorWaitAccum, actorReadU16(*actor, kActorWaitAccum) + elapsed);
-		actorWriteU16(*actor, kActorWaitTarget, 0);
+		descendChildren = true;
+		return false;
 	}
 
 	uint32 pc = actorReadU32(*actor, kActorCurrentPc);
 	for (;;) {
 		ScriptDispatchStatus status = scriptStep(*actor, pc);
-		if (status == kScriptContinue) {
-			actorWriteU32(*actor, kActorCurrentPc, pc);
+		if (status == kScriptContinue)
 			continue;
-		}
 
-		if (status == kScriptYield && _stringTable.size() > 3) {
-			actorWriteU16(*actor, kActorStringRef, _stringTable[2]);
-			actorWriteU16(*actor, kActorStringRef + 2, _stringTable[3]);
+		if (status == kScriptYield) {
+			if (_stringTable.size() > 3) {
+				actorWriteU16(*actor, kActorStringRef, _stringTable[2]);
+				actorWriteU16(*actor, kActorStringRef + 2, _stringTable[3]);
+			}
+
+			actorWriteU32(*actor, kActorCurrentPc, pc);
 		}
 
 		descendChildren = status == kScriptYield && !_actorDestroyedCurrent;
@@ -950,18 +1014,18 @@ uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &m
 		if (!spriteId)
 			continue;
 
-		int16 spriteX = baseX + int16(dx);
-		int16 spriteY = baseY + int16(dy);
-		if (spriteX >= 0x0280 || spriteX <= int16(0xFEC0) ||
-				spriteY >= 0x0190 || spriteY <= int16(0xFF38))
+		_keymaskX = baseX + int16(dx);
+		_keymaskY = baseY + int16(dy);
+		if (_keymaskX >= 0x0280 || _keymaskX <= int16(0xFEC0) ||
+				_keymaskY >= 0x0190 || _keymaskY <= int16(0xFF38))
 			continue;
 
 		SpriteResource *sprite = spriteGetPtr(int16(spriteId));
 		if (!sprite)
 			continue;
 
-		int16 left = spriteX - sprite->header.hotspotX;
-		int16 top = spriteY - sprite->header.hotspotY;
+		int16 left = _keymaskX - sprite->header.hotspotX;
+		int16 top = _keymaskY - sprite->header.hotspotY;
 		if (mode == 1)
 			spriteBlitClipped(int16(spriteId), left, top);
 
@@ -986,16 +1050,16 @@ void ComfyEngine::actorEvalFrameSelection(uint16 actorIndex, int16 x, int16 y) {
 	uint32 selector = actorReadU32(*actor, kActorCachedSprite);
 	VideoRectRecord rect = actorReadCachedRect(*actor);
 	if (selector & 0xFF000000) {
-		uint16 last = scriptEvalKeyMask(selector & 0x00FFFFFF, 0, rect, _keymaskOldRects,
+		uint16 last = scriptEvalKeyMask(selector & 0x00FFFFFF, 0, rect, _keymaskInvalidationRects,
 			rect.left, rect.top);
-		if (last >= COMFY_RESOLUTION_CHANGE_CAPACITY)
+		if (last != 0xFFFF && last >= COMFY_RESOLUTION_CHANGE_CAPACITY)
 			last = COMFY_RESOLUTION_CHANGE_CAPACITY - 1;
 
-		for (uint i = 0; i <= last; i++) {
-			if (_keymaskOldRects[i].area)
-				videoFindBestMode(_keymaskOldRects[i]);
+		if (last != 0xFFFF) {
+			for (uint i = 0; i <= last; i++)
+				videoFindBestMode(_keymaskInvalidationRects[i]);
 		}
-	} else if (rect.area) {
+	} else {
 		videoFindBestMode(rect);
 	}
 
@@ -1015,49 +1079,6 @@ void ComfyEngine::actorEvalFrameSelection(uint16 actorIndex, int16 x, int16 y) {
 	}
 }
 
-uint16 ComfyEngine::actorDrawScripted(uint16 actorIndex, uint32 selector, int16 x, int16 y) {
-	uint32 pc = selector & 0x00FFFFFF;
-	if (_videoMode == 2) {
-		_keymaskCurrentRecord.left = x;
-		_keymaskCurrentRecord.top = y;
-		_keymaskCurrentRecord.right = 0;
-		_keymaskCurrentRecord.bottom = 0;
-		_keymaskCurrentRecord.area = 0;
-		uint16 last = scriptEvalKeyMask(pc, 1, _keymaskCurrentRecord, _keymaskRects, x, y);
-		return MIN<uint16>(last, COMFY_RESOLUTION_CHANGE_CAPACITY - 1);
-	}
-
-	int16 wordsLeft = int16(scriptReadWord(pc) - 1);
-	pc += 2;
-	while (wordsLeft > 0 && !_scriptFault) {
-		uint16 spriteId = scriptReadWord(pc);
-		int16 dx = scriptReadWord(pc + 2);
-		int16 dy = scriptReadWord(pc + 4);
-		pc += 6;
-		wordsLeft -= 3;
-		if (spriteId & 0x8000) {
-			wordsLeft -= 2;
-			uint16 key = scriptReadWord(pc);
-			pc += 2;
-			if (keyBitTest(key))
-				spriteId &= 0x7FFF;
-			else
-				spriteId = scriptReadWord(pc);
-
-			pc += 2;
-		}
-
-		if (spriteId) {
-			SpriteResource *sprite = spriteGetPtr(int16(spriteId));
-			if (sprite)
-				spriteBlitClipped(int16(spriteId), x + dx - sprite->header.hotspotX, y + dy - sprite->header.hotspotY);
-		}
-	}
-
-	(void)actorIndex;
-	return 0xFFFF;
-}
-
 ComfyEngine::VideoRectRecord ComfyEngine::actorReadCachedRect(Actor &actor) {
 	VideoRectRecord rect;
 	rect.left = actorReadU16(actor, kActorCachedRect);
@@ -1076,36 +1097,6 @@ void ComfyEngine::actorWriteCachedRect(Actor &actor, VideoRectRecord rect) {
 	actorWriteU16(actor, kActorCachedRect + 8, rect.area);
 }
 
-void ComfyEngine::actorInvalidateDrawTree(uint16 actorIndex) {
-	Actor *actor = actorGetPtr(actorIndex);
-	if (!actor)
-		return;
-
-	VideoRectRecord rect = actorReadCachedRect(*actor);
-	if (rect.area)
-		videoFindBestMode(rect);
-
-	actorWriteU8(*actor, kActorCachedVisible, 0);
-	actorWriteU32(*actor, kActorCachedSprite, 0);
-	VideoRectRecord empty;
-	actorWriteCachedRect(*actor, empty);
-	uint16 child = actorReadU16(*actor, kActorSiblingHead);
-	while (child) {
-		Actor *childActor = actorGetPtr(child);
-		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
-		actorInvalidateDrawTree(child);
-		child = next;
-	}
-
-	child = actorReadU16(*actor, kActorChildHead);
-	while (child) {
-		Actor *childActor = actorGetPtr(child);
-		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
-		actorInvalidateDrawTree(child);
-		child = next;
-	}
-}
-
 bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 	Actor *actor = actorGetPtr(actorIndex);
 	if (!actor)
@@ -1135,22 +1126,68 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 	bool newScripted = (selector & 0xFF000000) != 0;
 	VideoRectRecord newRect;
 	uint16 scriptedLastRect = 0xFFFF;
-	bool newRectValid = false;
 	if (newScripted) {
-		scriptedLastRect = actorDrawScripted(actorIndex, selector, drawX, drawY);
+		uint32 pc = selector & 0x00FFFFFF;
+		if (_videoMode == 2) {
+			_keymaskCurrentRecord.left = drawX;
+			_keymaskCurrentRecord.top = drawY;
+			_keymaskCurrentRecord.right = 0;
+			_keymaskCurrentRecord.bottom = 0;
+			_keymaskCurrentRecord.area = 0;
+			scriptedLastRect = scriptEvalKeyMask(pc, 1, _keymaskCurrentRecord, _keymaskRects, drawX, drawY);
+			if (scriptedLastRect != 0xFFFF && scriptedLastRect >= COMFY_RESOLUTION_CHANGE_CAPACITY)
+				scriptedLastRect = COMFY_RESOLUTION_CHANGE_CAPACITY - 1;
+		} else {
+			int16 wordsLeft = int16(scriptReadWord(pc) - 1);
+			pc += 2;
+			while (wordsLeft > 0 && !_scriptFault) {
+				uint16 spriteId = scriptReadWord(pc);
+				int16 dx = scriptReadWord(pc + 2);
+				int16 dy = scriptReadWord(pc + 4);
+				pc += 6;
+				wordsLeft -= 3;
+				if (spriteId & 0x8000) {
+					wordsLeft -= 2;
+					uint16 key = scriptReadWord(pc);
+					pc += 2;
+					if (keyBitTest(key))
+						spriteId &= 0x7FFF;
+					else
+						spriteId = scriptReadWord(pc);
+
+					pc += 2;
+				}
+
+				if (spriteId) {
+					SpriteResource *sprite = spriteGetPtr(int16(spriteId));
+					if (sprite)
+						spriteBlitClipped(int16(spriteId), drawX + dx - sprite->header.hotspotX,
+							drawY + dy - sprite->header.hotspotY);
+				}
+			}
+		}
+
 		if (_videoMode == 2 && scriptedLastRect != 0xFFFF) {
 			newRect = _keymaskCurrentRecord;
-			newRectValid = true;
 		}
+	} else if (selector == 0x00FFFFFF) {
+		uint16 frameWidth = 0;
+		uint16 frameHeight = 0;
+		animFrameGetDimensions(frameWidth, frameHeight);
+		newRect.left = drawX;
+		newRect.top = drawY;
+		newRect.right = drawX + frameWidth;
+		newRect.bottom = drawY + frameHeight;
+		newRect.area = frameWidth * frameHeight;
+		animFrameBlitAt(drawX, drawY);
 	} else if (selector) {
-		SpriteResource *sprite = spriteGetPtr(int16(selector));
+		SpriteResource *sprite = spriteLookup(uint16(selector), drawX, drawY);
 		if (sprite) {
 			newRect.left = drawX - sprite->header.hotspotX;
 			newRect.top = drawY - sprite->header.hotspotY;
 			newRect.right = newRect.left + sprite->header.width;
 			newRect.bottom = newRect.top + sprite->header.height;
 			newRect.area = sprite->header.width * sprite->header.height;
-			newRectValid = true;
 			spriteBlitClipped(int16(selector), drawX - sprite->header.hotspotX, drawY - sprite->header.hotspotY);
 		}
 	}
@@ -1159,11 +1196,8 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 	if (_videoMode == 2) {
 		byte newVisible = actorReadU8(*actor, kActorVisible);
 		bool changed = oldSelector != selector || oldVisible != newVisible;
-		if (newRectValid && (oldRect.left != newRect.left || oldRect.top != newRect.top ||
-				oldRect.right != newRect.right || oldRect.bottom != newRect.bottom || oldRect.area != newRect.area))
-			changed = true;
-
-		if (!newRectValid && oldRect.area)
+		if (oldRect.left != newRect.left || oldRect.top != newRect.top ||
+				oldRect.right != newRect.right || oldRect.bottom != newRect.bottom || oldRect.area != newRect.area)
 			changed = true;
 
 		uint16 oldScriptedLastRect = 0xFFFF;
@@ -1171,7 +1205,7 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 			VideoRectRecord maskRecord = oldRect;
 			oldScriptedLastRect = scriptEvalKeyMask(oldSelector & 0x00FFFFFF, 0, maskRecord,
 				_keymaskOldRects, oldRect.left, oldRect.top);
-			if (oldScriptedLastRect >= COMFY_RESOLUTION_CHANGE_CAPACITY)
+			if (oldScriptedLastRect != 0xFFFF && oldScriptedLastRect >= COMFY_RESOLUTION_CHANGE_CAPACITY)
 				oldScriptedLastRect = COMFY_RESOLUTION_CHANGE_CAPACITY - 1;
 		}
 
@@ -1187,31 +1221,27 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 					bool equal = oldItem && newItem && oldItem->left == newItem->left && oldItem->top == newItem->top &&
 						oldItem->right == newItem->right && oldItem->bottom == newItem->bottom && oldItem->area == newItem->area;
 					if (!equal) {
-						if (oldItem && oldItem->area)
+						if (oldItem)
 							videoFindBestMode(*oldItem);
 
-						if (newItem && newItem->area)
+						if (newItem)
 							videoFindBestMode(*newItem);
 					}
 				}
 
 				comparedScriptRects = true;
-			} else if (newScripted) {
-				for (uint i = 0; i <= scriptedLastRect; i++) {
-					if (_keymaskRects[i].area)
-						videoFindBestMode(_keymaskRects[i]);
-				}
-			} else if (newRectValid && newRect.area) {
+			} else if (newScripted && scriptedLastRect != 0xFFFF) {
+				for (uint i = 0; i <= scriptedLastRect; i++)
+					videoFindBestMode(_keymaskRects[i]);
+			} else if (!newScripted) {
 				videoFindBestMode(newRect);
 			}
 
 			if (!comparedScriptRects) {
-				if (oldScripted) {
-					for (uint i = 0; i <= oldScriptedLastRect; i++) {
-						if (_keymaskOldRects[i].area)
-							videoFindBestMode(_keymaskOldRects[i]);
-					}
-				} else if (oldRect.area) {
+				if (oldScripted && oldScriptedLastRect != 0xFFFF) {
+					for (uint i = 0; i <= oldScriptedLastRect; i++)
+						videoFindBestMode(_keymaskOldRects[i]);
+				} else if (!oldScripted) {
 					videoFindBestMode(oldRect);
 				}
 			}
@@ -1219,12 +1249,7 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 
 		actorWriteU8(*actor, kActorCachedVisible, newVisible);
 		actorWriteU32(*actor, kActorCachedSprite, selector);
-		if (newRectValid) {
-			actorWriteCachedRect(*actor, newRect);
-		} else if (!selector) {
-			VideoRectRecord empty;
-			actorWriteCachedRect(*actor, empty);
-		}
+		actorWriteCachedRect(*actor, newRect);
 	}
 
 	actorDrawList(actorReadU16(*actor, kActorChildHead), drawX, drawY);
diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
index 25ccef08814..ac3b325ac9b 100644
--- a/engines/comfy/anim_file.cpp
+++ b/engines/comfy/anim_file.cpp
@@ -33,8 +33,45 @@ enum AnimFileCommand {
 	kAnimCommandFrame = 0x5246
 };
 
+bool ComfyEngine::animFrameIsActive() {
+	return _animActive;
+}
+
+bool ComfyEngine::animFrameIsReady() {
+	return _animActive && _animFrameReady;
+}
+
+void ComfyEngine::animFrameReadStorage(byte *destination, uint32 offset, uint16 size) {
+	if (offset > _animFrameStorage.size() || size > _animFrameStorage.size() - offset)
+		error("Invalid animation storage read");
+
+	if (size)
+		memcpy(destination, &_animFrameStorage[offset], size);
+}
+
+void ComfyEngine::animFilePushStorageChunk(uint32 fileOffset, uint32 storageOffset, uint16 size) {
+	for (int i = 5; i > 0; i--) {
+		_animStorageChunkFileOffsets[i] = _animStorageChunkFileOffsets[i - 1];
+		_animStorageChunkOffsets[i] = _animStorageChunkOffsets[i - 1];
+		_animStorageChunkSizes[i] = _animStorageChunkSizes[i - 1];
+	}
+
+	_animStorageChunkFileOffsets[0] = fileOffset;
+	_animStorageChunkOffsets[0] = storageOffset;
+	_animStorageChunkSizes[0] = size;
+}
+
+void ComfyEngine::animFrameSetVocCounter(uint32 counter) {
+	if (!_midiPlyrDriver)
+		return;
+
+	// The original uses a wave callback counter when the ANM header requests it.
+	// ScummVM uses the MidiPlyr timer as the common host-side VOC clock.
+	_midiPlyrDriver->setIncreaseVocCounter(1);
+	_midiPlyrDriver->setVocCounter(counter);
+}
+
 bool ComfyEngine::animFileOpen() {
-	animFileShutdown(true);
 	if (!readAssetFile(Common::Path("ANMFILE.DAT"), _animFileData) ||
 			_animFileData.size() < COMFY_ANMFILE_HEADER_BYTES)
 		return false;
@@ -53,70 +90,80 @@ bool ComfyEngine::animFileOpen() {
 
 	_animPantherFormat = magic == COMFY_ANMFILE_PANTHER_MAGIC;
 	_animIndexLoaded = true;
+	_animActive = false;
+	_animUsesWaveVocCounter = false;
 	return true;
 }
 
-void ComfyEngine::animFileShutdown(bool closeFile) {
+void ComfyEngine::animFrameShutdown(bool freeBuffers) {
 	if (_animActive) {
+		if (_stringTable.size() > 14)
+			_stringTable[14] = 0;
+
 		if (_animCurrentFrameKey)
 			keyBitSet(_animCurrentFrameKey);
 
-		if (_animCurrentAnimId < _sceneHandles.size()) {
-			Actor *actor = actorGetPtr(sceneGetHandle(_animCurrentAnimId));
+		_animCurrentFrameKey = 0;
+		_animFrameStorage.clear();
+		_animActive = false;
+	}
+
+	if (freeBuffers) {
+		_animFrameBuffer.clear();
+		if (_animCurrentActorSceneHandle < _sceneHandles.size()) {
+			Actor *actor = actorGetPtr(sceneGetHandle(_animCurrentActorSceneHandle));
 			if (actor)
 				actorWriteU32(*actor, kActorSpriteSelector, 0);
 		}
-	}
 
-	_animActive = false;
-	_animCurrentIndex = 0;
-	_animCurrentAnimId = 0;
-	_animCurrentActorSceneHandle = 0;
-	_animCurrentFrameKey = 0;
-	_animVocClockHz = 0;
-	_animVocTargetCounter = 0;
-	if (closeFile) {
-		_animFileData.clear();
-		_animIndexTable.clear();
-		_animFrameBuffer.clear();
-		_animFrameStorage.clear();
-		_animPosition = 0;
-		_animIndexLoaded = false;
-		_animPantherFormat = false;
+		_animCurrentActorSceneHandle = 0;
 	}
 }
 
+void ComfyEngine::animFileShutdown() {
+	animFrameShutdown(true);
+	_animFileData.clear();
+	_animIndexTable.clear();
+	_animIndexLoaded = false;
+}
+
 void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 actorSceneHandle) {
-	if (!_animIndexLoaded || _animActive || animIndex >= _animIndexTable.size()) {
-		_animActive = false;
+	if (!_animIndexLoaded || _animActive || animIndex >= _animIndexTable.size())
 		return;
-	}
+
+	animFrameShutdown(true);
 
 	uint32 offset = _animIndexTable[animIndex];
 	if (offset > _animFileData.size() || COMFY_ANMFILE_HEADER_BYTES > _animFileData.size() - offset)
-		return;
+		error("ANMFILE.DAT is truncated while loading animation %u", uint(animIndex));
 
 	memcpy(_animFrameHeader, &_animFileData[offset], sizeof(_animFrameHeader));
-	uint16 expectedMagic = _animPantherFormat ? COMFY_ANMFRAME_PANTHER_MAGIC : COMFY_ANMFRAME_MAGIC;
-	if (READ_LE_UINT16(_animFrameHeader) != expectedMagic)
-		return;
+	uint16 magic = READ_LE_UINT16(_animFrameHeader);
+	if (magic != COMFY_ANMFRAME_MAGIC && magic != COMFY_ANMFRAME_PANTHER_MAGIC)
+		error("Invalid frame header in ANMFILE.DAT for animation %u", uint(animIndex));
 
-	_animFrameBuffer.resize(_animPantherFormat ? framebufferBytes() : COMFY_ANMFRAME_BYTES);
+	_animFrameBuffer.resize(COMFY_ANMFRAME_BYTES);
 	memset(&_animFrameBuffer[0], 0xFF, _animFrameBuffer.size());
 	_animFrameStorage.clear();
-	memset(_animPendingDirtyRect, 0, sizeof(_animPendingDirtyRect));
-	_animPendingDirtyRectSize = 0;
+	memset(_animStorageChunkFileOffsets, 0, sizeof(_animStorageChunkFileOffsets));
+	memset(_animStorageChunkOffsets, 0, sizeof(_animStorageChunkOffsets));
+	memset(_animStorageChunkSizes, 0, sizeof(_animStorageChunkSizes));
+	memset(_animFrameCommandData, 0, sizeof(_animFrameCommandData));
+	_animFrameCommandDataSize = 0;
+	_animFrameCommandArgument = 0;
+	_animFrameCommandFlag = false;
 	_animPosition = offset + COMFY_ANMFILE_HEADER_BYTES;
 	_animCurrentIndex = animIndex;
-	_animCurrentAnimId = actorSceneHandle;
 	_animCurrentActorSceneHandle = actorSceneHandle;
 	_animCurrentFrameKey = frameKey;
-	_animVocCounterMode = 0;
+	_animUsesWaveVocCounter = READ_LE_UINT32(_animFrameHeader + 4) != 0;
 	_animVocClockHz = READ_LE_UINT16(_animFrameHeader + 8);
 	_animVocTargetCounter = 0xFFFF;
-	_animVocBaseCounter = 0;
+	_animVocDeltaB = 0;
 	_animVocDeltaA = 0;
 	_animActive = true;
+	_animFrameReady = false;
+
 	if (actorSceneHandle < _sceneHandles.size()) {
 		Actor *actor = actorGetPtr(sceneGetHandle(actorSceneHandle));
 		if (actor)
@@ -131,71 +178,63 @@ uint32 ComfyEngine::animDecompressRle(const byte *source, uint32 sourceSize, byt
 	uint32 destinationPosition = 0;
 	while (sourcePosition < sourceSize) {
 		byte control = source[sourcePosition++];
-		if (!control) {
-			do {
-				if (sourcePosition + 1 >= sourceSize || destinationPosition >= destinationSize)
-					return destinationPosition;
-
-				sourcePosition++;
-				destination[destinationPosition++] = source[sourcePosition++];
-				if (sourcePosition >= sourceSize)
-					return destinationPosition;
+		if (control == 0) {
+			if (sourcePosition + 1 >= sourceSize)
+				return destinationPosition;
 
-				control = source[sourcePosition++];
-			} while (!control);
+			uint32 count = source[sourcePosition++];
+			byte value = source[sourcePosition++];
+			count = MIN<uint32>(count, destinationSize - destinationPosition);
+			memset(destination + destinationPosition, value, count);
+			destinationPosition += count;
+			continue;
 		}
 
-		for (;;) {
-			if (control == 0x80) {
-				if (sourcePosition + 1 >= sourceSize)
-					return destinationPosition;
-
-				uint16 word = READ_LE_UINT16(source + sourcePosition);
-				sourcePosition += 2;
-				if (!word)
-					return destinationPosition;
-
-				if (int16(word) > 0) {
-					destinationPosition = MIN<uint32>(destinationPosition + word, destinationSize);
-					break;
-				}
+		if (control == 0x80) {
+			if (sourcePosition + 1 >= sourceSize)
+				return destinationPosition;
 
-				uint16 count = word - 0x8000;
-				if ((count & 0x4000) == 0) {
-					count = MIN<uint32>(count, sourceSize - sourcePosition);
-					count = MIN<uint32>(count, destinationSize - destinationPosition);
-					memcpy(destination + destinationPosition, source + sourcePosition, count);
-					sourcePosition += count;
-					destinationPosition += count;
-					break;
-				}
+			uint16 word = READ_LE_UINT16(source + sourcePosition);
+			sourcePosition += 2;
+			if (word == 0)
+				return destinationPosition;
 
-				count -= 0x4000;
-				if (sourcePosition >= sourceSize)
-					return destinationPosition;
+			if (int16(word) > 0) {
+				destinationPosition = MIN<uint32>(destinationPosition + word, destinationSize);
+				continue;
+			}
 
+			uint32 count = word - 0x8000;
+			if ((count & 0x4000) == 0) {
+				count = MIN<uint32>(count, sourceSize - sourcePosition);
 				count = MIN<uint32>(count, destinationSize - destinationPosition);
-				memset(destination + destinationPosition, source[sourcePosition++], count);
+				memcpy(destination + destinationPosition, source + sourcePosition, count);
+				sourcePosition += count;
 				destinationPosition += count;
-				break;
-			}
-
-			if (control & 0x80) {
-				destinationPosition = MIN<uint32>(destinationPosition + control - 0x80, destinationSize);
-				break;
+				continue;
 			}
 
-			if (sourcePosition >= sourceSize || destinationPosition >= destinationSize)
-				return destinationPosition;
-
-			destination[destinationPosition++] = source[sourcePosition++];
+			count -= 0x4000;
 			if (sourcePosition >= sourceSize)
 				return destinationPosition;
 
-			control = source[sourcePosition++];
-			if (!control)
-				break;
+			byte value = source[sourcePosition++];
+			count = MIN<uint32>(count, destinationSize - destinationPosition);
+			memset(destination + destinationPosition, value, count);
+			destinationPosition += count;
+			continue;
+		}
+
+		if (control & 0x80) {
+			destinationPosition = MIN<uint32>(destinationPosition + control - 0x80, destinationSize);
+			continue;
 		}
+
+		uint32 count = MIN<uint32>(control, sourceSize - sourcePosition);
+		count = MIN<uint32>(count, destinationSize - destinationPosition);
+		memcpy(destination + destinationPosition, source + sourcePosition, count);
+		sourcePosition += count;
+		destinationPosition += count;
 	}
 
 	return destinationPosition;
@@ -219,7 +258,7 @@ uint32 ComfyEngine::animDecodePanther(const byte *source, uint32 sourceSize) {
 			uint16 runCount = READ_LE_UINT16(source + sourcePosition);
 			sourcePosition += 2;
 			if (runCount & 0x4000) {
-				destinationPosition += uint32(uint16(0 - runCount)) * _logicalScreenWidth;
+				destinationPosition += uint32(uint16(0 - runCount)) * COMFY_SCREEN_WIDTH;
 				continue;
 			}
 
@@ -254,7 +293,7 @@ uint32 ComfyEngine::animDecodePanther(const byte *source, uint32 sourceSize) {
 				runCount--;
 			}
 
-			destinationPosition = rowStart + _logicalScreenWidth;
+			destinationPosition = rowStart + COMFY_SCREEN_WIDTH;
 			rows--;
 		}
 
@@ -294,39 +333,47 @@ uint32 ComfyEngine::animDecodePanther(const byte *source, uint32 sourceSize) {
 			remaining -= count;
 		}
 
-		if (width < _logicalScreenWidth)
-			destinationPosition += _logicalScreenWidth - width;
+		if (width < COMFY_SCREEN_WIDTH)
+			destinationPosition += COMFY_SCREEN_WIDTH - width;
 	}
 
 	return written;
 }
 
 void ComfyEngine::animFileTickCommands() {
-	if (!_usesAnimFile || !_animActive || _animVocCounterMode)
+	if (!_usesAnimFile)
 		return;
 
-	_animVocTargetCounter++;
-	if (_animVocTargetCounter == 1 && _midiPlyrDriver) {
-		_midiPlyrDriver->setVocCounter(0);
-		_midiPlyrDriver->setIncreaseVocCounter(1);
+	if (!_animActive) {
+		if (_stringTable.size() > 14)
+			_stringTable[14] = 0;
+
+		return;
 	}
 
+	if (_animFrameReady)
+		return;
+
+	_animVocTargetCounter++;
+	if (_animVocTargetCounter == 1)
+		animFrameSetVocCounter(0);
+
+	if (_stringTable.size() > 14)
+		_stringTable[14] = _animVocTargetCounter + 1;
+
 	bool ended = false;
 	bool frameReady = false;
 	while (!ended && !frameReady) {
 		uint32 headerSize = _animPantherFormat ? 8 : 4;
-		if (_animPosition > _animFileData.size() || headerSize > _animFileData.size() - _animPosition) {
-			animFileShutdown(false);
-			return;
-		}
+		if (_animPosition > _animFileData.size() || headerSize > _animFileData.size() - _animPosition)
+			error("ANMFILE.DAT is truncated while reading an animation command");
 
 		byte *header = &_animFileData[_animPosition];
 		uint16 command = READ_LE_UINT16(header);
-		uint32 commandSize = _animPantherFormat ? READ_LE_UINT32(header + 2) : READ_LE_UINT16(header + 2);
-		if (commandSize < headerSize || commandSize > _animFileData.size() - _animPosition) {
-			animFileShutdown(false);
-			return;
-		}
+		uint32 rawCommandSize = _animPantherFormat ? READ_LE_UINT32(header + 2) : READ_LE_UINT16(header + 2);
+		uint32 commandSize = _animPantherFormat ? rawCommandSize & 0xFFFF : rawCommandSize;
+		if (commandSize < headerSize || commandSize > _animFileData.size() - _animPosition)
+			error("Invalid animation command size in ANMFILE.DAT");
 
 		uint32 payloadSize = commandSize - headerSize;
 		byte *payload = header + headerSize;
@@ -335,62 +382,76 @@ void ComfyEngine::animFileTickCommands() {
 			ended = true;
 		} else if (command == kAnimCommandStoreFrameBytes) {
 			uint32 oldSize = _animFrameStorage.size();
+			uint32 frameStart = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
+			animFilePushStorageChunk(uint32(payload - &_animFileData[frameStart]), oldSize, uint16(payloadSize));
 			_animFrameStorage.resize(oldSize + payloadSize);
 			if (payloadSize)
 				memcpy(&_animFrameStorage[oldSize], payload, payloadSize);
 		} else if (command == kAnimCommandDirtyRect) {
-			_animPendingDirtyRectSize = payloadSize;
-			memset(_animPendingDirtyRect, 0, sizeof(_animPendingDirtyRect));
-			memcpy(_animPendingDirtyRect, payload, MIN<uint32>(payloadSize, sizeof(_animPendingDirtyRect)));
+			_animFrameCommandDataSize = payloadSize;
+			_animFrameCommandFlag = _animPantherFormat && (rawCommandSize & 0x80000000) != 0;
+			_animFrameCommandArgument = _animPantherFormat ? (rawCommandSize >> 16) & 0x7FF : payloadSize;
+			memset(_animFrameCommandData, 0, sizeof(_animFrameCommandData));
+			memcpy(_animFrameCommandData, payload, MIN<uint32>(payloadSize, sizeof(_animFrameCommandData)));
 		} else if (command == kAnimCommandFrame) {
-			if (payloadSize) {
+			if (commandSize > 8) {
 				if (_animPantherFormat)
 					animDecodePanther(payload, payloadSize);
 				else
 					animDecompressRle(payload, payloadSize, &_animFrameBuffer[0], _animFrameBuffer.size());
 			}
 
-			if (_framebufPtr && !_animFrameBuffer.empty()) {
-				memcpy(_framebufPtr, &_animFrameBuffer[0], MIN<uint32>(framebufferBytes(), _animFrameBuffer.size()));
-				renderSetDirty();
-			}
-
 			frameReady = true;
 		} else {
-			animFileShutdown(false);
-			return;
+			error("Unknown animation command 0x%04X in ANMFILE.DAT", command);
 		}
 	}
 
 	if (ended)
-		animFileShutdown(false);
+		animFrameShutdown(false);
 }
 
-bool ComfyEngine::animFrameShouldWaitForVoc() {
-	return _animActive && !_animVocCounterMode && _animVocTargetCounter && _animVocClockHz && _midiPlyrDriver;
+bool ComfyEngine::animFrameIsPending() {
+	return _animActive && !_animFrameReady && _animVocTargetCounter != 0;
 }
 
 int16 ComfyEngine::animFrameVocCounterDelta() {
-	if (!animFrameShouldWaitForVoc())
+	if (!_midiPlyrDriver)
+		return 0;
+
+	uint32 counter = _midiPlyrDriver->getVocCounter();
+	if (counter == 0)
 		return 0;
 
+	if (_animVocClockHz == 0)
+		error("Invalid VOC clock frequency in ANMFILE.DAT");
+
 	int32 expected = (int32(int16(_animVocTargetCounter)) * 100) / int16(_animVocClockHz);
-	return int16(uint16(_midiPlyrDriver->getVocCounter()) - uint16(expected));
+	return int16(uint16(counter) - uint16(expected));
 }
 
 bool ComfyEngine::animFrameShouldDraw(uint16 phase) {
-	if (!animFrameShouldWaitForVoc())
+	if (!animFrameIsPending())
 		return true;
 
 	int16 baseStep = 100 / int16(_animVocClockHz);
 	int16 threshold = phase == 1 ? baseStep / 2 : baseStep;
 	int16 delta = animFrameVocCounterDelta();
-	int16 adjustedDelta = int16((phase == 1 ? int16(delta + _animVocDeltaA) : delta) + _animVocBaseCounter);
-	return adjustedDelta <= threshold;
+	int16 adjustedDelta = int16((phase == 1 ? int16(delta + _animVocDeltaA) : delta) + _animVocDeltaB);
+	bool shouldDraw = adjustedDelta <= threshold;
+	if (!shouldDraw) {
+		if (int16(_animVocDeltaA) > 0)
+			_animVocDeltaA--;
+
+		if (int16(_animVocDeltaB) > 0)
+			_animVocDeltaB--;
+	}
+
+	return shouldDraw;
 }
 
 void ComfyEngine::animFrameRecordVocCounter(uint16 phase) {
-	if (!animFrameShouldWaitForVoc())
+	if (!animFrameIsPending() || !_midiPlyrDriver)
 		return;
 
 	uint32 counter = _midiPlyrDriver->getVocCounter();
@@ -403,25 +464,235 @@ void ComfyEngine::animFrameRecordVocCounter(uint16 phase) {
 		_animVocCounterStartB = counter;
 	} else if (phase == 4) {
 		_animVocCounterEndB = counter;
-		_animVocBaseCounter = uint16(_animVocCounterEndB - _animVocCounterStartB);
+		_animVocDeltaB = uint16(_animVocCounterEndB - _animVocCounterStartB);
 	}
 }
 
 void ComfyEngine::animFrameWaitForVocCounter() {
-	if (!animFrameShouldWaitForVoc())
+	if (!animFrameIsPending())
 		return;
 
-	for (uint guard = 0; guard < 1000; guard++) {
-		if (animFrameVocCounterDelta() >= -int16(_animVocBaseCounter))
-			break;
-
-		soundAdvanceTick();
+	while (animFrameVocCounterDelta() < -int16(_animVocDeltaB + 3)) {
 		processEvents();
 		if (shouldQuit())
 			break;
+	}
+}
+
+void ComfyEngine::animFrameSetReady(bool ready) {
+	if (!_animActive || ready == _animFrameReady)
+		return;
+
+	if (_midiPlyrDriver)
+		_midiPlyrDriver->setIncreaseVocCounter(!ready);
+
+	_animFrameReady = ready;
+}
+
+bool ComfyEngine::animFrameBlitAt(int16 x, int16 y) {
+	if (_animFrameBuffer.empty() || !_framebufPtr)
+		return false;
+
+	uint16 rectCount = MIN<uint16>(_animFrameCommandDataSize / 4,
+		sizeof(_animFrameCommandData) / 4);
+	for (uint i = 0; i < rectCount; i++) {
+		uint16 start = READ_LE_UINT16(_animFrameCommandData + i * 4);
+		uint16 end = READ_LE_UINT16(_animFrameCommandData + i * 4 + 2);
+		int16 left = x + (start % (COMFY_SCREEN_WIDTH / 4)) * 4;
+		int16 top = y + (start / (COMFY_SCREEN_WIDTH / 4)) * 4;
+		int16 right = x + ((end % (COMFY_SCREEN_WIDTH / 4)) + 1) * 4;
+		int16 bottom = y + ((end / (COMFY_SCREEN_WIDTH / 4)) + 1) * 4;
+
+		int16 clippedLeft = MAX<int16>(left, 0);
+		int16 clippedTop = MAX<int16>(top, 0);
+		int16 clippedRight = MIN<int16>(right, _logicalScreenWidth);
+		int16 clippedBottom = MIN<int16>(bottom, _logicalScreenHeight);
+		if (clippedLeft >= clippedRight || clippedTop >= clippedBottom)
+			continue;
+
+		for (int16 row = clippedTop; row < clippedBottom; row++) {
+			uint32 sourceOffset = uint32(row - y) * COMFY_SCREEN_WIDTH + clippedLeft - x;
+			uint32 destinationOffset = uint32(row) * _logicalScreenWidth + clippedLeft;
+			uint32 width = clippedRight - clippedLeft;
+			if (sourceOffset >= _animFrameBuffer.size())
+				break;
+
+			width = MIN<uint32>(width, _animFrameBuffer.size() - sourceOffset);
+			memcpy(_framebufPtr + destinationOffset, &_animFrameBuffer[sourceOffset], width);
+		}
+	}
+
+	renderSetDirty();
+	return true;
+}
+
+void ComfyEngine::animFrameInvalidateRects(int16, int16, byte) {
+	if (_animFrameBuffer.empty())
+		return;
+
+	// The original feeds these rectangles to its partial-update compositor.
+	// ScummVM presents the engine framebuffer as one dirty surface.
+	renderSetDirty();
+}
+
+bool ComfyEngine::animFrameGetDimensions(uint16 &width, uint16 &height) {
+	if (!_animIndexLoaded || _animCurrentActorSceneHandle == 0)
+		return false;
+
+	if (_animPantherFormat) {
+		width = READ_LE_UINT16(_animFrameHeader + 10);
+		height = READ_LE_UINT16(_animFrameHeader + 12);
+	} else {
+		width = COMFY_SCREEN_WIDTH;
+		height = COMFY_SCREEN_HEIGHT;
+	}
+
+	return true;
+}
+
+void ComfyEngine::animFrameClear() {
+	if (!_animFrameBuffer.empty())
+		memset(&_animFrameBuffer[0], 0xFF, COMFY_ANMFRAME_BYTES);
+}
+
+void ComfyEngine::animFilePackState(byte *state) {
+	memset(state, 0, COMFY_ANM_STATE_BYTES);
+	memcpy(state, _animFrameHeader, sizeof(_animFrameHeader));
+	WRITE_LE_UINT16(state + 0x10, _animCurrentIndex);
+	WRITE_LE_UINT16(state + 0x12, _animVocTargetCounter);
+	state[0x14] = _animActive;
+	state[0x15] = !_animFrameBuffer.empty();
+	state[0x16] = _animFrameReady;
+	WRITE_LE_UINT16(state + 0x17, _animCurrentFrameKey);
+	state[0x19] = _animUsesWaveVocCounter;
+	WRITE_LE_UINT16(state + 0x1A, _animCurrentActorSceneHandle);
+	WRITE_LE_UINT16(state + 0x1C, _animVocDeltaA);
+	WRITE_LE_UINT16(state + 0x1E, _animVocDeltaB);
+	WRITE_LE_UINT32(state + 0x20, _midiPlyrDriver ? _midiPlyrDriver->getVocCounter() : 0);
+	WRITE_LE_UINT32(state + 0x24, _animFrameStorage.size());
+
+	uint32 streamPosition = 0;
+	if (_animCurrentIndex < _animIndexTable.size()) {
+		uint32 frameStart = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
+		if (_animPosition >= frameStart)
+			streamPosition = _animPosition - frameStart;
+	}
 
-		_system->delayMillis(1);
+	WRITE_LE_UINT32(state + 0x28, streamPosition);
+	for (uint i = 0; i < 6; i++) {
+		byte *chunk = state + 0x2C + i * 0x0A;
+		WRITE_LE_UINT32(chunk, _animStorageChunkFileOffsets[i]);
+		WRITE_LE_UINT32(chunk + 4, _animStorageChunkOffsets[i]);
+		WRITE_LE_UINT16(chunk + 8, _animStorageChunkSizes[i]);
 	}
 }
 
+void ComfyEngine::animFileRestoreStreamPosition(const byte *state) {
+	if (_animCurrentIndex >= _animIndexTable.size())
+		return;
+
+	uint32 frameStart = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
+	uint32 streamPosition = READ_LE_UINT32(state + 0x28);
+	if (frameStart > _animFileData.size() || streamPosition > _animFileData.size() - frameStart)
+		error("Invalid restored stream position in ANMFILE.DAT");
+
+	_animPosition = frameStart + streamPosition;
+}
+
+void ComfyEngine::animFileRebuildStorage(uint32 targetSize) {
+	_animFrameStorage.clear();
+	memset(_animFrameCommandData, 0, sizeof(_animFrameCommandData));
+	_animFrameCommandDataSize = 0;
+	_animFrameCommandArgument = 0;
+	_animFrameCommandFlag = false;
+	memset(_animStorageChunkFileOffsets, 0, sizeof(_animStorageChunkFileOffsets));
+	memset(_animStorageChunkOffsets, 0, sizeof(_animStorageChunkOffsets));
+	memset(_animStorageChunkSizes, 0, sizeof(_animStorageChunkSizes));
+	if (_animCurrentIndex >= _animIndexTable.size())
+		return;
+
+	uint32 position = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
+	while (position < _animPosition && position < _animFileData.size()) {
+		uint32 headerSize = _animPantherFormat ? 8 : 4;
+		if (headerSize > _animFileData.size() - position)
+			error("ANMFILE.DAT is truncated while rebuilding animation storage");
+
+		byte *header = &_animFileData[position];
+		uint16 command = READ_LE_UINT16(header);
+		uint32 rawCommandSize = _animPantherFormat ? READ_LE_UINT32(header + 2) : READ_LE_UINT16(header + 2);
+		uint32 commandSize = _animPantherFormat ? rawCommandSize & 0xFFFF : rawCommandSize;
+		if (commandSize < headerSize || commandSize > _animFileData.size() - position)
+			error("Invalid command while rebuilding animation storage");
+
+		uint32 payloadSize = commandSize - headerSize;
+		byte *payload = header + headerSize;
+		if (command == kAnimCommandStoreFrameBytes && _animFrameStorage.size() < targetSize) {
+			uint32 copySize = MIN<uint32>(payloadSize, targetSize - _animFrameStorage.size());
+			uint32 oldSize = _animFrameStorage.size();
+			uint32 frameStart = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
+			animFilePushStorageChunk(uint32(payload - &_animFileData[frameStart]), oldSize, uint16(copySize));
+			_animFrameStorage.resize(oldSize + copySize);
+			if (copySize)
+				memcpy(&_animFrameStorage[oldSize], payload, copySize);
+		} else if (command == kAnimCommandDirtyRect) {
+			_animFrameCommandDataSize = payloadSize;
+			_animFrameCommandFlag = _animPantherFormat && (rawCommandSize & 0x80000000) != 0;
+			_animFrameCommandArgument = _animPantherFormat ? (rawCommandSize >> 16) & 0x7FF : payloadSize;
+			memset(_animFrameCommandData, 0, sizeof(_animFrameCommandData));
+			memcpy(_animFrameCommandData, payload, MIN<uint32>(payloadSize, sizeof(_animFrameCommandData)));
+		}
+
+		position += commandSize;
+	}
+}
+
+void ComfyEngine::animFileUnpackState(const byte *state) {
+	animFrameShutdown(true);
+	memcpy(_animFrameHeader, state, sizeof(_animFrameHeader));
+	_animCurrentIndex = READ_LE_UINT16(state + 0x10);
+	_animVocTargetCounter = READ_LE_UINT16(state + 0x12);
+	_animActive = state[0x14] != 0;
+	_animFrameReady = state[0x16] != 0;
+	_animCurrentFrameKey = READ_LE_UINT16(state + 0x17);
+	_animUsesWaveVocCounter = state[0x19] != 0;
+	_animCurrentActorSceneHandle = READ_LE_UINT16(state + 0x1A);
+	_animVocDeltaA = READ_LE_UINT16(state + 0x1C);
+	_animVocDeltaB = READ_LE_UINT16(state + 0x1E);
+	for (uint i = 0; i < 6; i++) {
+		_animStorageChunkFileOffsets[i] = READ_LE_UINT32(state + 0x2C + i * 0x0A);
+		_animStorageChunkOffsets[i] = READ_LE_UINT32(state + 0x30 + i * 0x0A);
+		_animStorageChunkSizes[i] = READ_LE_UINT16(state + 0x34 + i * 0x0A);
+	}
+
+	if (_animCurrentActorSceneHandle == 0)
+		return;
+
+	if (_animCurrentActorSceneHandle < _sceneHandles.size()) {
+		Actor *actor = actorGetPtr(sceneGetHandle(_animCurrentActorSceneHandle));
+		if (actor)
+			actorWriteU32(*actor, kActorSpriteSelector, 0x00FFFFFF);
+	}
+
+	_animFrameBuffer.resize(COMFY_ANMFRAME_BYTES);
+	animFrameClear();
+	if (!_animActive)
+		return;
+
+	animFileRestoreStreamPosition(state);
+	animFileRebuildStorage(READ_LE_UINT32(state + 0x24));
+	animFrameSetVocCounter(READ_LE_UINT32(state + 0x20));
+}
+
+void ComfyEngine::animFrameInvalidateActorRect() {
+	if (_animCurrentActorSceneHandle >= _sceneHandles.size())
+		return;
+
+	Actor *actor = actorGetPtr(sceneGetHandle(_animCurrentActorSceneHandle));
+	if (!actor)
+		return;
+
+	actorWriteU16(*actor, kActorCachedRect, 0x270F);
+	actorWriteU16(*actor, kActorCachedRect + 4, 0x270F);
+}
+
 } // End of namespace Comfy
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index d7cf14ed245..1b32a6160ee 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -43,7 +43,7 @@ static ComfyEngineVersion getEngineVersion(const ADGameDescription *gameDesc) {
 	}
 
 	if (!strcmp(gameDesc->gameId, "boo") || !strcmp(gameDesc->gameId, "first") ||
-			!strcmp(gameDesc->gameId, "panther"))
+			!strcmp(gameDesc->gameId, "match"))
 		return kEngineVersion2;
 
 	return kEngineVersion3;
@@ -60,14 +60,20 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Eng
 	memset(_logicalPalette, 0, sizeof(_logicalPalette));
 	memset(_keyboardKeyToBit, 0xFF, sizeof(_keyboardKeyToBit));
 	memset(_selectorPoolEntries, 0, sizeof(_selectorPoolEntries));
+	memset(_sceneEntryVolumes, 0, sizeof(_sceneEntryVolumes));
+	memset(_sceneEntryCompletionKeys, 0, sizeof(_sceneEntryCompletionKeys));
 	memset(_wcomfy99FeatureWords, 0, sizeof(_wcomfy99FeatureWords));
 	memset(_animFrameHeader, 0, sizeof(_animFrameHeader));
-	memset(_animPendingDirtyRect, 0, sizeof(_animPendingDirtyRect));
+	memset(_animFrameCommandData, 0, sizeof(_animFrameCommandData));
+	memset(_animStorageChunkFileOffsets, 0, sizeof(_animStorageChunkFileOffsets));
+	memset(_animStorageChunkOffsets, 0, sizeof(_animStorageChunkOffsets));
+	memset(_animStorageChunkSizes, 0, sizeof(_animStorageChunkSizes));
 	g_engine = this;
 }
 
 ComfyEngine::~ComfyEngine() {
 	gameShutdown();
+	g_engine = nullptr;
 }
 
 Common::String ComfyEngine::getGameId() const {
@@ -109,7 +115,7 @@ Common::Error ComfyEngine::gameInit() {
 		ConfMan.flushToDisk();
 	}
 
-	if (iniGetGameDataPath(0)) {
+	if (!_hasDataPath && iniGetGameDataPath(0)) {
 		sceneRun(_currentScene, false, true);
 		if (shouldQuit()) {
 			gameShutdown();
@@ -176,6 +182,7 @@ uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
 	byte shouldStartNext = 0;
 	uint16 nextScene = 0;
 	_lptKeyboardInitialized = true;
+	hostKeyboardLoadDatMap();
 
 	if (_sceneRunBuffer.empty()) {
 		_sceneRunBuffer.resize(0x10010);
@@ -204,7 +211,7 @@ uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
 		_languageSessionRestartRequested = false;
 	} else if (checkNext) {
 		if (sceneGetActiveCount() > 1 && _midiHandles.size() > 1)
-			nextScene = _midiHandles[1];
+			nextScene = midiGetHandle(1);
 
 		if (int16(nextScene) > 0 && int16(nextScene) < 0x65 && nextScene != sceneId)
 			shouldStartNext = 1;
@@ -217,7 +224,7 @@ uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
 		restorePalette = 0;
 
 	if (_engineVersion == kEngineVersion3)
-		soundShutdown();
+		animFileShutdown();
 
 	midiShutdown();
 	assetsUnload(0);
@@ -267,17 +274,105 @@ void ComfyEngine::processEvents() {
 		case Common::EVENT_KEYUP:
 			hostKeyboardSetKeyState(hostKeyboardVirtualKey(event.kbd.keycode), false);
 			break;
+		case Common::EVENT_MOUSEMOVE:
+			if (_engineVersion == kEngineVersion3) {
+				_mouseX = CLIP<int16>(int32(event.mouse.x) * 320 / _logicalScreenWidth, 0, 319);
+				_mouseY = CLIP<int16>(int32(event.mouse.y) * 200 / _logicalScreenHeight, 0, 199);
+			}
+			break;
+		case Common::EVENT_LBUTTONDOWN:
+			if (_engineVersion == kEngineVersion3) {
+				_mouseLeftButton = true;
+				_mouseLeftButtonEdge = false;
+			}
+			break;
+		case Common::EVENT_LBUTTONUP:
+			if (_engineVersion == kEngineVersion3)
+				_mouseLeftButtonEdge = true;
+			break;
+		case Common::EVENT_RBUTTONDOWN:
+			if (_engineVersion == kEngineVersion3) {
+				_mouseRightButton = true;
+				_mouseRightButtonEdge = false;
+			}
+			break;
+		case Common::EVENT_RBUTTONUP:
+			if (_engineVersion == kEngineVersion3)
+				_mouseRightButtonEdge = true;
+			break;
 		default:
 			break;
 		}
 	}
 }
 
+void ComfyEngine::mouseSetActor(Actor *actor) {
+	_mouseActorSceneHandle = actor ? actorReadU16(*actor, kActorSceneHandle) : 0;
+}
+
+ComfyEngine::Actor *ComfyEngine::mouseGetActor() {
+	if (!_mouseActorSceneHandle)
+		return nullptr;
+
+	uint16 actorIndex = sceneGetHandle(_mouseActorSceneHandle);
+	if (!actorIndex) {
+		_mouseActorSceneHandle = 0;
+		return nullptr;
+	}
+
+	return actorGetPtr(actorIndex);
+}
+
+void ComfyEngine::mouseClearButtonEdges() {
+	if (_mouseLeftButtonEdge) {
+		_mouseLeftButtonEdge = false;
+		_mouseLeftButton = false;
+	}
+
+	if (_mouseRightButtonEdge) {
+		_mouseRightButtonEdge = false;
+		_mouseRightButton = false;
+	}
+}
+
+void ComfyEngine::mouseUpdateCursor() {
+	_mouseFlags |= 0x10;
+	_mouseActor = mouseGetActor();
+	if (!_mouseActor) {
+		_mouseCursorSprite = nullptr;
+		_mouseFlags &= ~0x10;
+		return;
+	}
+
+	uint32 selector = actorReadU32(*_mouseActor, kActorSpriteSelector);
+	if (!selector) {
+		_mouseCursorSprite = nullptr;
+		_mouseFlags &= ~0x10;
+		return;
+	}
+
+	_mouseCursorSprite = spriteGetPtr(int16(selector));
+	if (_mouseCursorSprite)
+		_mouseCursorSpriteId = uint16(_mouseCursorSprite->id);
+
+	if (!actorReadU8(*_mouseActor, kActorVisible) && !(_mouseFlags & 8))
+		_mouseFlags |= 8;
+
+	_mouseFlags &= ~0x10;
+}
+
 void ComfyEngine::gameMainLoop(uint16 argument) {
 	byte keepRunning = 1;
 	uint16 lastKey = 0xFFFF;
+	if (_engineVersion == kEngineVersion3)
+		midiInitInstance();
+
 	actorInit(1, 0, 1, 1, 0x14, 0, 0, 0, 1);
+	if (_engineVersion == kEngineVersion3)
+		mouseSetActor(nullptr);
+
 	keyBitSet(2);
+	inputQueueReset();
 	lptKeyboardInit();
 
 	uint16 rootIndex = sceneGetHandle(1);
@@ -286,7 +381,7 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 	paletteVsyncFlip();
 	paletteVsyncFlip();
 	if (sceneGetActiveCount() && _midiHandles.size() > 1)
-		_midiHandles[1] += argument;
+		midiHandleAddTo(1, argument);
 
 	while (keepRunning && !shouldQuit()) {
 		_pendingScene = 0;
@@ -304,6 +399,10 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 		lptKeyboardScanAndProcess();
 		lptKeyToFlags(lastKey);
 		actorTickTree(rootIndex);
+		if (_engineVersion == kEngineVersion3) {
+			mouseClearButtonEdges();
+			mouseUpdateCursor();
+		}
 
 		uint16 frame = actorGetFrame();
 		if (frame) {
@@ -329,6 +428,9 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 			renderSetDirty();
 		}
 
+		if (_engineVersion == kEngineVersion3)
+			_waveOutputActive = true;
+
 		lastKey = 0xFFFF;
 		if (inputQueueHasItems())
 			lastKey = lptReadKeyOrNext();
@@ -397,6 +499,56 @@ void ComfyEngine::sceneTickEvent() {
 	if (_soundEventIndex == _soundEventMaximum)
 		return;
 
+	if (_engineVersion == kEngineVersion3) {
+		VocQueueEntry1999 &entry = _vocQueue1999[_soundEventIndex];
+		bool started = false;
+		if (entry.state == 0xFFFF && (entry.soundId != 0xFFFF || !animFrameIsReady())) {
+			entry.state = 0;
+			_soundEventSubIndex = 0xFFFF;
+			soundPlayEntry(entry.soundId);
+			keyBitSet(1);
+			keyBitSet(4);
+			keyBitClear(2);
+			keyBitClear(3);
+			started = true;
+		}
+
+		if (!started && _soundEventSubIndex != 0xFFFF &&
+				_soundEventSubIndex != _soundEventPreviousSubIndex) {
+			if (!_soundEventSubIndex) {
+				if (entry.argumentCount)
+					keyBitSet(entry.arguments[0]);
+
+				_soundEventIndex++;
+				if (_soundEventIndex == COMFY_VOC_QUEUE_CAPACITY)
+					_soundEventIndex = 0;
+
+				if (_soundEventIndex == _soundEventMaximum) {
+					keyBitClear(1);
+					keyBitClear(4);
+					keyBitSet(3);
+					keyBitSet(2);
+				}
+			} else if (_soundEventSubIndex == 1) {
+				keyBitSet(3);
+				keyBitClear(4);
+			} else if (_soundEventSubIndex == 2) {
+				keyBitSet(4);
+				keyBitClear(3);
+			} else if (_soundEventSubIndex - 2 < entry.argumentCount) {
+				if (entry.clearArgumentKeys) {
+					for (uint i = 0; i < entry.argumentCount; i++)
+						keyBitClear(entry.arguments[i]);
+				}
+
+				keyBitSet(entry.arguments[_soundEventSubIndex - 2]);
+			}
+		}
+
+		_soundEventPreviousSubIndex = _soundEventSubIndex;
+		return;
+	}
+
 	VocQueueEntry &entry = _vocQueue[_soundEventIndex % COMFY_VOC_QUEUE_CAPACITY];
 	if (entry.state == 0xFFFF) {
 		entry.state = 0;
@@ -436,15 +588,21 @@ void ComfyEngine::midiPollChannels(uint16 ticks) {
 	if (!_midiPlyrDriver)
 		return;
 
+	if (_sceneEntryListActive) {
+		midiPollSceneEntries();
+		return;
+	}
+
 	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
 		MidiChannelState &state = _midiChannels[channel];
 		if (!state.entryCount)
 			continue;
 
-		if (state.playing && !_midiPlyrDriver->musicIsSongPlaying(channel))
-			state.playing = false;
+		uint16 marker = _midiPlyrDriver->musicGetClearMarker(channel);
+		if (marker)
+			midiFireClearMarker(channel, marker);
 
-		if (!state.playing)
+		if (!_midiPlyrDriver->musicIsSongPlaying(channel))
 			midiFinishChannel(channel);
 
 		int16 volume = midiApproachTarget(state.volumeCurrent, state.volumeTarget, state.volumeTicksLeft, ticks);
@@ -465,10 +623,31 @@ void ComfyEngine::midiPollChannels(uint16 ticks) {
 	}
 }
 
-void ComfyEngine::vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc) {
+bool ComfyEngine::vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc) {
 	uint16 next = (_soundEventMaximum + 1) % COMFY_VOC_QUEUE_CAPACITY;
 	if (next == _soundEventIndex)
-		return;
+		return false;
+
+	if (_engineVersion == kEngineVersion3) {
+		VocQueueEntry1999 &entry = _vocQueue1999[_soundEventMaximum];
+		entry.clearArgumentKeys = (argumentCount & 0x80) != 0;
+		argumentCount &= 0x3F;
+		entry.soundId = soundId;
+		entry.argumentCount = MIN<uint16>(argumentCount, COMFY_VOC_ARG_CAPACITY_1999);
+		entry.state = 0xFFFF;
+		for (uint i = 0; i < COMFY_VOC_ARG_CAPACITY_1999; i++)
+			entry.arguments[i] = 0;
+
+		for (uint i = 0; i < entry.argumentCount; i++)
+			entry.arguments[i] = scriptReadWord(pc + i * 2);
+
+		_soundEventMaximum = next;
+		keyBitSet(1);
+		keyBitSet(4);
+		keyBitClear(2);
+		keyBitClear(3);
+		return true;
+	}
 
 	VocQueueEntry &entry = _vocQueue[_soundEventMaximum % COMFY_VOC_QUEUE_CAPACITY];
 	entry.soundId = soundId;
@@ -483,10 +662,33 @@ void ComfyEngine::vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc)
 	keyBitSet(4);
 	keyBitClear(2);
 	keyBitClear(3);
+	return true;
 }
 
 void ComfyEngine::vocQueuePlayAll() {
 	_mixer->stopHandle(_soundHandle);
+	_soundCues.clear();
+	if (_engineVersion == kEngineVersion3) {
+		uint16 slot = _soundEventIndex;
+		while (slot != _soundEventMaximum) {
+			VocQueueEntry1999 &entry = _vocQueue1999[slot];
+			for (uint i = 0; i < entry.argumentCount; i++)
+				keyBitSet(entry.arguments[i]);
+
+			slot++;
+			if (slot == COMFY_VOC_QUEUE_CAPACITY)
+				slot = 0;
+		}
+
+		_soundEventMaximum = _soundEventIndex;
+		_soundPcm.clear();
+		keyBitClear(1);
+		keyBitClear(4);
+		keyBitSet(3);
+		keyBitSet(2);
+		return;
+	}
+
 	uint16 slot = _soundEventIndex;
 	while (slot != _soundEventMaximum) {
 		VocQueueEntry &entry = _vocQueue[slot];
@@ -500,8 +702,8 @@ void ComfyEngine::vocQueuePlayAll() {
 	_soundPcm.clear();
 	keyBitClear(1);
 	keyBitClear(4);
-	keyBitSet(2);
 	keyBitSet(3);
+	keyBitSet(2);
 }
 
 bool ComfyEngine::vocQueueIsIdle() {
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 7173122b680..bcba95f9666 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -57,12 +57,19 @@
 #define COMFY_RESOURCE_LIST_CAPACITY 32
 #define COMFY_SCENE_ENTRY_OFFSET_CAPACITY 16
 #define COMFY_SCENE_MIDI_INSTANCE_BYTES 0x18C
+#define COMFY_SCENE_MIDI_VERSION_BYTES_CLASSIC 0x167
+#define COMFY_SCENE_VOC_STATE_BYTES_V3 0x24D
+#define COMFY_SCENE_STATE_BYTES_V3 0x17F
+#define COMFY_ACTOR_SIZE_V3 0x57
 #define COMFY_SCENE_ACTOR_PC_BYTES 0x320
 #define COMFY_SCENE_FRAME_BYTES 0x4E20
+#define COMFY_SCENE_FRAME_BYTES_V3 0x7530
 #define COMFY_VOC_ARG_CAPACITY 10
 #define COMFY_VOC_QUEUE_CAPACITY 16
+#define COMFY_VOC_ARG_CAPACITY_1999 12
 #define COMFY_MIDI_QUEUE_CAPACITY 32
 #define COMFY_MIDI_CHANNEL_COUNT 2
+#define COMFY_SCENE_MUSIC_CHANNEL_COUNT 6
 #define COMFY_MIDI_TRACK_ENTRY_CAPACITY 5
 #define COMFY_ANIM_FRAME_CAPACITY 10
 #define COMFY_ANMFILE_HEADER_BYTES 16
@@ -71,6 +78,8 @@
 #define COMFY_ANMFRAME_MAGIC 0x4E41
 #define COMFY_ANMFRAME_PANTHER_MAGIC 0x4C46
 #define COMFY_ANMFRAME_BYTES 0xFA00
+#define COMFY_ANMFRAME_COMMAND_DATA_BYTES 0x78
+#define COMFY_ANM_STATE_BYTES 0x68
 
 namespace Comfy {
 
@@ -189,6 +198,24 @@ private:
 		}
 	};
 
+	struct VocQueueEntry1999 {
+		uint16 soundId;
+		uint16 argumentCount;
+		uint16 state;
+		uint16 arguments[COMFY_VOC_ARG_CAPACITY_1999];
+		bool clearArgumentKeys;
+
+		VocQueueEntry1999() {
+			soundId = 0;
+			argumentCount = 0;
+			state = 0;
+			clearArgumentKeys = false;
+
+			for (uint i = 0; i < COMFY_VOC_ARG_CAPACITY_1999; i++)
+				arguments[i] = 0;
+		}
+	};
+
 	struct MidiQueueEntry {
 		uint16 id;
 		int32 time;
@@ -248,7 +275,6 @@ private:
 		int16 pitchTicksLeft;
 		int16 pitchDefault;
 		uint16 loadedFrameSize;
-		bool playing;
 
 		MidiChannelState() {
 			entryCount = 0;
@@ -265,7 +291,6 @@ private:
 			pitchTicksLeft = 0;
 			pitchDefault = 0;
 			loadedFrameSize = 0;
-			playing = false;
 		}
 	};
 
@@ -383,10 +408,18 @@ private:
 	uint16 _lptPortBase = 0x0378;
 	uint16 _inputDeviceMode = 0;
 	uint16 _inputDevicePreference = 0;
+	uint16 _inputInitialDeviceMode = 0;
 	uint32 _inputPreviousComfyboardState = 0;
 	uint32 _inputPreviousKeyboardState = 0;
 	uint16 _inputComfyboardActivityCount = 0;
 	uint16 _inputKeyboardActivityCount = 0;
+	bool _inputKeyboardBit7Held = false;
+	bool _inputKeyboardResetRequested = false;
+	bool _inputKeyboardSyntheticBit7 = false;
+	bool _inputComfyboardSuppressBit1 = false;
+	uint16 _inputKeyboardPulseTicks = 0;
+	bool _inputKeyboardPulseLatched = false;
+	uint32 _inputKeyboardPulseTime = 0;
 	bool _keyboardUiInitialized = false;
 	bool _keyboardUiVisible = true;
 	Common::Array<byte> _comfyObjData;
@@ -424,6 +457,10 @@ private:
 	Common::Array<SpriteCacheEntry> _frameCacheEntries;
 	ResourceLoadList _spriteConversionLoads;
 	SpriteObjectHeader _spriteLastHeader;
+	uint16 _spriteDecompressLastSize = 0;
+	bool _spriteDecompressLastComplete = false;
+	uint32 _objFileOffset = 0;
+	uint16 _objFileStride = 0;
 	uint32 _keymaskBits = 0;
 	uint16 _keymaskLastIndex = 0xFFFF;
 	uint16 _keymaskCount = 0;
@@ -431,10 +468,15 @@ private:
 	uint16 _keymaskArg0 = 0;
 	uint16 _keymaskArg1 = 0;
 	uint16 _keymaskResult = 0;
+	int16 _keymaskX = 0;
+	int16 _keymaskY = 0;
 	VideoRectRecord _keymaskCurrentRecord;
 	VideoRectRecord _keymaskRects[COMFY_RESOLUTION_CHANGE_CAPACITY];
 	VideoRectRecord _keymaskOldRects[COMFY_RESOLUTION_CHANGE_CAPACITY];
+	VideoRectRecord _keymaskInvalidationRects[COMFY_RESOLUTION_CHANGE_CAPACITY];
 	uint32 _sceneEntryOffsets[COMFY_SCENE_ENTRY_OFFSET_CAPACITY];
+	uint16 _sceneEntryVolumes[COMFY_SCENE_MUSIC_CHANNEL_COUNT];
+	uint16 _sceneEntryCompletionKeys[COMFY_SCENE_MUSIC_CHANNEL_COUNT];
 	uint32 _sceneMidiInstanceOffset = 0;
 	uint32 _sceneEntryListOffset = 0;
 	uint32 _sceneActorPcOffset = 0;
@@ -442,13 +484,14 @@ private:
 	uint32 _sceneHandlesOffset = 0;
 	uint32 _sceneActorsOffset = 0;
 	uint32 _sceneKeyBitsOffset = 0;
+	uint32 _sceneAnimStateOffset = 0;
 	uint32 _scenePoolCursor = 0;
 	uint32 _scenePoolEvictCursor = 0;
 	uint32 _scenePoolSize = 0;
 	uint32 _headerXmsObjectTableBase = 0;
 	uint32 _headerXmsObjectTableBytes = 0;
-	uint32 _headerXmsPicEntriesBase = 0;
-	uint32 _headerXmsPicEntriesBytes = 0;
+	uint32 _headerXmsMidiEntriesBase = 0;
+	uint32 _headerXmsMidiEntriesBytes = 0;
 	uint32 _headerXmsSoundHeadersBase = 0;
 	uint32 _headerXmsSoundHeadersBytes = 0;
 	uint16 _selectorPoolEntries[10];
@@ -472,8 +515,30 @@ private:
 	bool _musicEnabled = false;
 	bool _usesWcomfy99ScriptOps = false;
 	bool _languageSessionRestartRequested = false;
+	int16 _mouseX = 0;
+	int16 _mouseY = 0;
+	bool _mouseLeftButton = false;
+	bool _mouseRightButton = false;
+	bool _mouseLeftButtonEdge = false;
+	bool _mouseRightButtonEdge = false;
+	uint16 _mouseActorSceneHandle = 0;
+	Actor *_mouseActor = nullptr;
+	SpriteResource *_mouseCursorSprite = nullptr;
+	uint16 _mouseCursorSpriteId = 0;
+	uint16 _mouseFlags = 0;
+	bool _waveOutputActive = false;
+	byte _wcomfy99VocState0 = 0;
+	byte _wcomfy99VocState1 = 0;
+	byte _wcomfy99VocState2 = 0;
+	byte _wcomfy99VocState3 = 0;
+	byte _wcomfy99VocState6 = 0;
+	bool _wcomfy99HostMediaValueAvailable = false;
+	uint16 _wcomfy99HostMediaValue = 0;
+	uint16 _wcomfy99HostMediaProgress = 0;
 	uint16 _wcomfy99FeatureWords[16];
 	byte _wcomfy99FeatureWordCount = 0;
+	uint16 _wcomfy99Stub32FirstWord = 0;
+	uint16 _wcomfy99Stub32SecondWord = 0;
 	uint16 _wcomfy99Sensitivity = 0;
 	bool _wcomfy99RecordHostEnabled = false;
 	uint16 _wcomfy99SubsystemWord = 0;
@@ -494,6 +559,7 @@ private:
 	bool _actorDestroyedCurrent = false;
 	uint16 _lastKey = 0xFFFF;
 	VocQueueEntry _vocQueue[COMFY_VOC_QUEUE_CAPACITY];
+	VocQueueEntry1999 _vocQueue1999[COMFY_VOC_QUEUE_CAPACITY];
 	uint16 _soundEventIndex = 0;
 	uint16 _soundEventMaximum = 0;
 	uint16 _soundEventSubIndex = 0xFFFF;
@@ -506,7 +572,7 @@ private:
 	Common::Array<byte> _soundPcm;
 	Common::Array<SoundCue> _soundCues;
 	Audio::SoundHandle _soundHandle;
-	uint16 _soundTileStride = 0;
+	uint16 _soundEntryCount = 0;
 	uint32 _soundSampleRate = 0x2B11;
 	uint _soundNextCue = 0;
 	bool _soundCompressed = false;
@@ -515,18 +581,21 @@ private:
 	Common::Array<uint32> _animIndexTable;
 	Common::Array<byte> _animFrameBuffer;
 	Common::Array<byte> _animFrameStorage;
+	uint32 _animStorageChunkFileOffsets[6];
+	uint32 _animStorageChunkOffsets[6];
+	uint16 _animStorageChunkSizes[6];
 	byte _animFrameHeader[COMFY_ANMFILE_HEADER_BYTES];
-	byte _animPendingDirtyRect[16];
+	byte _animFrameCommandData[COMFY_ANMFRAME_COMMAND_DATA_BYTES];
 	uint32 _animPosition = 0;
-	uint16 _animPendingDirtyRectSize = 0;
+	uint16 _animFrameCommandDataSize = 0;
+	uint16 _animFrameCommandArgument = 0;
+	bool _animFrameCommandFlag = false;
 	uint16 _animCurrentIndex = 0;
-	uint16 _animCurrentAnimId = 0;
 	uint16 _animCurrentActorSceneHandle = 0;
 	uint16 _animCurrentFrameKey = 0;
-	byte _animVocCounterMode = 0;
 	uint16 _animVocClockHz = 0;
 	uint16 _animVocTargetCounter = 0;
-	uint16 _animVocBaseCounter = 0;
+	uint16 _animVocDeltaB = 0;
 	uint16 _animVocDeltaA = 0;
 	uint32 _animVocCounterStartA = 0;
 	uint32 _animVocCounterEndA = 0;
@@ -535,6 +604,8 @@ private:
 	bool _animIndexLoaded = false;
 	bool _animPantherFormat = false;
 	bool _animActive = false;
+	bool _animFrameReady = false;
+	bool _animUsesWaveVocCounter = false;
 	uint16 _exprStack[COMFY_EXPR_STACK_CAPACITY];
 	uint16 _exprStackTop = 0;
 	bool _scriptFault = false;
@@ -575,6 +646,11 @@ private:
 	void paletteConvertRgbToLogical(byte *source, byte *destination);
 	void paletteRealize(byte *rawPalette);
 	uint16 midiTick();
+	void midiHandleAddTo(uint16 handleIndex, int16 delta);
+	void midiHandleCopy(uint16 destination, uint16 source);
+	void midiHandleSet(uint16 handleIndex, uint16 value);
+	uint16 midiGetHandle(uint16 handleIndex);
+	uint16 midiGetVersion();
 	void midiSetTimeScale(int16 delta);
 	int16 midiGetCounterAdjustment();
 	bool midiPlyrStart();
@@ -616,10 +692,11 @@ private:
 	bool comfyObjOpen();
 	bool picFileOpen();
 	bool midiFileOpen();
-	void objFileReadEntries(byte *destination);
+	void midiFileReadEntries(byte *destination);
 	byte *soundReadTiledData();
-	void soundGetTileParams(uint16 *tileStride, uint16 *fieldCount);
+	void soundGetTileParams(uint16 *entryCount, uint16 *entrySize);
 	void spriteCache(int16 spriteId);
+	SpriteResource *spriteLookup(uint16 spriteId, int16 x, int16 y);
 	void spriteInvalidateHostCache(SpriteResource &sprite);
 	void objHdrReadFromXms(byte *destination, uint32 base, uint16 size, uint16 row);
 	void objHdrRead(SpriteObjectHeader &destination, uint16 index);
@@ -671,7 +748,7 @@ private:
 	void actorSetPc(Actor &actor, uint32 pc);
 	uint32 actorPopPc(Actor &actor);
 	void actorFreePcChain(Actor &actor);
-	void actorFreeTree(uint16 actorIndex);
+	void actorFreeTreePc(uint16 actorIndex);
 	void actorClearDirtyTree(uint16 actorIndex);
 	void actorSetAllVisible();
 	uint16 actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible, byte active,
@@ -683,10 +760,8 @@ private:
 	uint16 scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &maskRecord,
 		VideoRectRecord *rects, int16 baseX, int16 baseY);
 	void actorEvalFrameSelection(uint16 actorIndex, int16 x, int16 y);
-	uint16 actorDrawScripted(uint16 actorIndex, uint32 selector, int16 x, int16 y);
 	VideoRectRecord actorReadCachedRect(Actor &actor);
 	void actorWriteCachedRect(Actor &actor, VideoRectRecord rect);
-	void actorInvalidateDrawTree(uint16 actorIndex);
 	void timerInit();
 	void timerShutdown();
 	void lptKeyboardInit();
@@ -694,40 +769,64 @@ private:
 	void gameMainLoop(uint16 argument);
 	uint16 sceneRun(uint16 sceneId, bool checkNext, bool exitFlag);
 	void processEvents();
+	void mouseSetActor(Actor *actor);
+	Actor *mouseGetActor();
+	void mouseClearButtonEdges();
+	void mouseUpdateCursor();
 
 	uint16 timerTick();
 	void midiTrackTickAndRemove();
 	void animFileTickCommands();
 	bool animFileOpen();
-	void animFileShutdown(bool closeFile);
+	void animFrameShutdown(bool freeBuffers);
+	void animFileShutdown();
 	void animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 actorSceneHandle);
 	uint32 animDecompressRle(const byte *source, uint32 sourceSize, byte *destination, uint32 destinationSize);
 	uint32 animDecodePanther(const byte *source, uint32 sourceSize);
-	bool animFrameShouldWaitForVoc();
+	bool animFrameIsPending();
 	bool animFrameShouldDraw(uint16 phase);
 	int16 animFrameVocCounterDelta();
 	void animFrameRecordVocCounter(uint16 phase);
 	void animFrameWaitForVocCounter();
+	void animFrameSetReady(bool ready);
+	bool animFrameBlitAt(int16 x, int16 y);
+	void animFrameInvalidateRects(int16 x, int16 y, byte mode);
+	bool animFrameGetDimensions(uint16 &width, uint16 &height);
+	void animFrameClear();
+	void animFilePackState(byte *state);
+	void animFileRestoreStreamPosition(const byte *state);
+	void animFileRebuildStorage(uint32 targetSize);
+	void animFileUnpackState(const byte *state);
+	void animFrameInvalidateActorRect();
+	bool animFrameIsActive();
+	bool animFrameIsReady();
+	void animFrameReadStorage(byte *destination, uint32 offset, uint16 size);
+	void animFilePushStorageChunk(uint32 fileOffset, uint32 storageOffset, uint16 size);
+	void animFrameSetVocCounter(uint32 counter);
 	void sceneTickEvent();
 	void sceneStartWithMusic(uint16 scene);
 	void midiPollChannels(uint16 ticks);
+	void midiInitInstanceAt();
 	void midiInitInstance();
 	void midiInitChannels();
 	void midiSyncAndScan();
 	void midiFindNext(MidiQueue &queue);
 	void midiQueueAdd(MidiQueue &queue, uint16 id, int16 delta);
-	void midiQueueRemove(MidiQueue &queue, uint16 id);
+	bool midiQueueRemove(MidiQueue &queue, uint16 id);
 	void midiAddEvent(uint16 id, int16 delta);
 	void midiAddTrack(uint16 id, int16 delta);
 	void midiRemoveTrack(uint16 id);
 	void midiAddTrackEntry(uint16 channel, uint16 songId, uint16 completionKey, byte loadFlag,
 		uint16 frameCount, uint16 *frames);
 	void midiClearChannel(uint16 channel);
+	void midiFireClearMarker(uint16 channel, int16 marker);
+	void midiPollSceneEntries();
 	void midiResumeAll();
 	void midiStopChannel(uint16 channel);
 	void midiStopAll();
 	void midiStopSong(uint16 channel);
 	void midiPlaySongAtFrame(uint16 channel, uint16 frame);
+	void sceneEntrySetVolume(uint16 channel, uint16 volume);
 	void midiFinishChannel(uint16 channel);
 	void midiStopAndFireKeys(uint16 channel);
 	void midiStopAndRemove(uint16 channel);
@@ -736,12 +835,13 @@ private:
 	void musicSetEnabled(byte value);
 	void paletteFadeStep(uint16 ticks);
 	void lptKeyboardScanAndProcess();
-	void vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc);
+	bool vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc);
 	void vocQueuePlayAll();
 	bool vocQueueIsIdle();
 	bool soundInit();
 	void soundShutdown();
 	void soundHdrReadFromXms(byte *destination, uint16 index, uint16 size);
+	void soundUnprepareHeader();
 	bool soundDecodeEntry(uint16 index);
 	bool soundDecodeCompressedEntry(uint32 dataOffset, uint32 dataSize);
 	bool soundLoadEntry(uint16 index);
diff --git a/engines/comfy/entry.cpp b/engines/comfy/entry.cpp
deleted file mode 100644
index 409cdeb90bd..00000000000
--- a/engines/comfy/entry.cpp
+++ /dev/null
@@ -1,25 +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/>.
- *
- */
-
-namespace Comfy {
-
-
-} // End of namespace Comfy
diff --git a/engines/comfy/expr.cpp b/engines/comfy/expr.cpp
index 0a276828ec7..6571ec9b5c8 100644
--- a/engines/comfy/expr.cpp
+++ b/engines/comfy/expr.cpp
@@ -94,6 +94,47 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 			continue;
 		}
 
+		if (_engineVersion == kEngineVersion3 && opcode >= 0x17 && opcode <= 0x21) {
+			uint16 value = 0;
+			bool pushValue = true;
+			if (opcode == 0x17)
+				value = _mouseX;
+			else if (opcode == 0x18)
+				value = _mouseY;
+			else if (opcode == 0x19)
+				value = _wcomfy99VocState0;
+			else if (opcode == 0x1A)
+				value = _wcomfy99HostMediaValueAvailable ? _wcomfy99HostMediaValue : 0;
+			else if (opcode == 0x1B)
+				pushValue = false;
+			else if (opcode == 0x1C)
+				value = _wcomfy99VocState2;
+			else if (opcode == 0x1D)
+				value = _wcomfy99VocState3;
+			else if (opcode == 0x1E) {
+				if (_exprStackTop) {
+					uint16 dimension = _exprStack[_exprStackTop - 1];
+					if (dimension == 0x6E)
+						_exprStack[_exprStackTop - 1] = 320;
+					else if (dimension == 0x6F)
+						_exprStack[_exprStackTop - 1] = 200;
+					else
+						_exprStack[_exprStackTop - 1] = 0;
+				}
+
+				pushValue = false;
+			} else if (opcode == 0x1F || opcode == 0x20) {
+				value = _wcomfy99HostMediaProgress;
+			} else if (opcode == 0x21) {
+				value = _wcomfy99VocState6;
+			}
+
+			if (pushValue && _exprStackTop < COMFY_EXPR_STACK_CAPACITY)
+				_exprStack[_exprStackTop++] = value;
+
+			continue;
+		}
+
 		if (opcode == 0x0C) {
 			if (_exprStackTop < 2) {
 				_exprStackTop = 0;
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index e80f515cf07..72cc61bb764 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -115,15 +115,19 @@ void ComfyEngine::findLanguageDirectories() {
 		_languageDirectories[i] = Common::Path();
 
 	Common::FSNode root(ConfMan.getPath("path"));
-	Common::FSList gameDirectories;
-	if (!root.getChildren(gameDirectories, Common::FSNode::kListDirectoriesOnly))
-		return;
-
 	Common::FSNode gameDirectory;
-	for (Common::FSList::iterator it = gameDirectories.begin(); it != gameDirectories.end(); it++) {
-		if (it->getName().equalsIgnoreCase(_gameDirectory.toString())) {
-			gameDirectory = *it;
-			break;
+	if (root.getName().equalsIgnoreCase(_gameDirectory.toString())) {
+		gameDirectory = root;
+	} else {
+		Common::FSList gameDirectories;
+		if (!root.getChildren(gameDirectories, Common::FSNode::kListDirectoriesOnly))
+			return;
+
+		for (Common::FSList::iterator it = gameDirectories.begin(); it != gameDirectories.end(); it++) {
+			if (it->getName().equalsIgnoreCase(_gameDirectory.toString())) {
+				gameDirectory = *it;
+				break;
+			}
 		}
 	}
 
@@ -147,12 +151,22 @@ void ComfyEngine::findLanguageDirectories() {
 
 bool ComfyEngine::iniReadGameConfig() {
 	_language = ConfMan.getInt("comfy_language");
+	if (getLanguageDirectory(_language).empty()) {
+		for (uint language = 1; language < ARRAYSIZE(_languageDirectories); language++) {
+			if (!_languageDirectories[language].empty()) {
+				_language = language;
+				break;
+			}
+		}
+	}
+
 	_renderInterleaved = ConfMan.getBool("comfy_screen_update_interleaved");
 	_inputDeviceMode = ConfMan.getInt("comfy_input_device");
-	if (_inputDeviceMode > 2)
+	if (_inputDeviceMode > 4)
 		_inputDeviceMode = 0;
 
 	_inputDevicePreference = _inputDeviceMode;
+	_wcomfy99Sensitivity = ConfMan.hasKey("SENSITIVITY") ? ConfMan.getInt("SENSITIVITY") : 0;
 
 	return !_gameDirectory.empty();
 }
@@ -245,7 +259,7 @@ bool ComfyEngine::comfyObjOpen() {
 }
 
 bool ComfyEngine::picFileOpen() {
-	if (!readAssetFile(Common::Path("PICFILE.DAT"), _picFileData) || _picFileData.size() < 2)
+	if (!readAssetFile(Common::Path("PICFILE.DAT"), _picFileData) || _picFileData.size() < 4)
 		return false;
 
 	uint16 count = assetsReadLe16At(_picFileData, 0);
@@ -304,7 +318,7 @@ int32 ComfyEngine::assetsXmsCopy(byte *destination, uint32 destinationSize, uint
 	return 0;
 }
 
-void ComfyEngine::objFileReadEntries(byte *destination) {
+void ComfyEngine::midiFileReadEntries(byte *destination) {
 	if (!destination || _midiFileData.size() <= 4)
 		return;
 
@@ -316,12 +330,12 @@ byte *ComfyEngine::soundReadTiledData() {
 	return _vocFileData.size() > 4 ? &_vocFileData[4] : nullptr;
 }
 
-void ComfyEngine::soundGetTileParams(uint16 *tileStride, uint16 *fieldCount) {
-	if (tileStride)
-		*tileStride = _soundTileStride;
+void ComfyEngine::soundGetTileParams(uint16 *entryCount, uint16 *entrySize) {
+	if (entryCount)
+		*entryCount = _soundEntryCount;
 
-	if (fieldCount)
-		*fieldCount = 8;
+	if (entrySize)
+		*entrySize = 8;
 }
 
 bool ComfyEngine::selPoolInit() {
@@ -365,18 +379,27 @@ bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16
 	if (0xC7 < ARRAYSIZE(_actorPcTable))
 		_actorPcTable[0xC7] = 0;
 
-	uint32 midiVersionBytes = 0x167;
 	uint32 stringBytes = _stringTable.size() * sizeof(uint16);
 	uint32 handleBytes = _sceneHandles.size() * sizeof(uint16);
-	uint32 actorBytes = _actors.size() * sizeof(Actor);
+	uint32 actorBytes = _actors.size() * (_engineVersion == kEngineVersion3 ? COMFY_ACTOR_SIZE_V3 : COMFY_ACTOR_SIZE);
 	uint32 keyBytes = (uint32(keyBitCount) + 1) / 8 + 1;
 	_sceneMidiInstanceOffset = 0;
-	_sceneEntryListOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES;
-	_sceneActorPcOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES + midiVersionBytes;
-	_sceneStringTableOffset = _sceneActorPcOffset + COMFY_SCENE_ACTOR_PC_BYTES;
+	if (_engineVersion == kEngineVersion3) {
+		_sceneEntryListOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES + COMFY_SCENE_VOC_STATE_BYTES_V3 +
+				COMFY_ANM_STATE_BYTES;
+		_sceneActorPcOffset = _sceneEntryListOffset + COMFY_SCENE_STATE_BYTES_V3;
+		_sceneStringTableOffset = _sceneActorPcOffset + COMFY_SCENE_ACTOR_PC_BYTES;
+	} else {
+		_sceneEntryListOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES;
+		_sceneActorPcOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES + midiGetVersion();
+		_sceneStringTableOffset = _sceneActorPcOffset + COMFY_SCENE_ACTOR_PC_BYTES;
+	}
+
 	_sceneHandlesOffset = _sceneStringTableOffset + stringBytes;
 	_sceneActorsOffset = _sceneHandlesOffset + handleBytes;
 	_sceneKeyBitsOffset = _sceneActorsOffset + actorBytes;
+	_sceneAnimStateOffset = _engineVersion == kEngineVersion3 ?
+			COMFY_SCENE_MIDI_INSTANCE_BYTES + COMFY_SCENE_VOC_STATE_BYTES_V3 : _sceneKeyBitsOffset + keyBytes;
 	uint32 sceneBytes = assetsAlignEven32(_sceneKeyBitsOffset + keyBytes);
 	_sceneMemoryBlock.resize(sceneBytes);
 	memset(&_sceneMemoryBlock[0], 0, sceneBytes);
@@ -385,6 +408,15 @@ bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16
 	_envNumSprites = numSprites;
 	_activeSceneCount = handleCount;
 
+	if (_engineVersion == kEngineVersion3) {
+		midiInitInstanceAt();
+		if (!soundInit())
+			return false;
+
+		if (_usesAnimFile && !animFileOpen())
+			return false;
+	}
+
 	if (!sceneOpen(_sceneEntryListOffset))
 		return false;
 
@@ -407,10 +439,9 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 		return false;
 	}
 
-	if (!soundInit()) {
+	if (_engineVersion != kEngineVersion3 && !soundInit())
 		return false;
-	}
-	_soundLoaded = true;
+
 	_picFileMapped = true;
 
 	_numFrames = _picDataSize / COMFY_TILE_SIZE + (_picDataSize % COMFY_TILE_SIZE ? 2 : 1);
@@ -419,6 +450,8 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	if (!sceneLoadAndInit(_sceneCount, 0x78, _keyBitCount, _resourceHandleCount, numSprites))
 		return false;
 
+	_soundLoaded = true;
+
 	uint32 environmentBytes = ((_envNumSprites * 5 + 0x3FF) / 0x400) * 0x400;
 	_environmentData.resize(environmentBytes);
 	if (environmentBytes)
@@ -426,10 +459,10 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	_xmsEnvAllocated = !_environmentData.empty();
 
 	uint32 midiHeaderBytes = assetsAlignEven32(uint32(_midiEntryCount) * 6);
-	uint16 soundTileStride = 0;
-	uint16 soundFieldCount = 0;
-	soundGetTileParams(&soundTileStride, &soundFieldCount);
-	uint32 soundHeaderBytes = assetsAlignEven32(uint32(soundTileStride) * soundFieldCount);
+	uint16 soundEntryCount = 0;
+	uint16 soundEntrySize = 0;
+	soundGetTileParams(&soundEntryCount, &soundEntrySize);
+	uint32 soundHeaderBytes = assetsAlignEven32(uint32(soundEntryCount) * soundEntrySize);
 	uint32 objectTableBytes = assetsAlignEven32(uint32(_numObjects) * 0x11);
 	uint32 headerTotalBytes = midiHeaderBytes + soundHeaderBytes + objectTableBytes;
 	uint16 headerPages = (headerTotalBytes + 0x400) / 0x400;
@@ -452,10 +485,15 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	for (uint i = 0; i < _spriteResources.size(); i++)
 		spriteInvalidateHostCache(_spriteResources[i]);
 
-	if (_usesAnimFile && !animFileOpen())
+	if (_engineVersion != kEngineVersion3 && _usesAnimFile && !animFileOpen())
 		return false;
 
-	uint32 xmsLimit = 0x0800 << 10;
+	if (_usesAnimFile) {
+		_animFrameBuffer.resize(COMFY_ANMFRAME_BYTES);
+		memset(&_animFrameBuffer[0], 0, _animFrameBuffer.size());
+	}
+
+	uint32 xmsLimit = _engineVersion == kEngineVersion3 ? 0x7D000 : 0x0800 << 10;
 	_scenePoolSize = xmsLimit > budget ? xmsLimit - budget : 0;
 	_scenePoolSize &= 0xFFFFFFFE;
 	_scenePoolData.resize(_scenePoolSize);
@@ -464,7 +502,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 
 	_scenePoolCursor = 0;
 	_scenePoolEvictCursor = 0;
-	if (_scenePoolSize >= 2)
+	if (_engineVersion != kEngineVersion3 && _scenePoolSize >= 2)
 		WRITE_LE_UINT16(&_scenePoolData[0], 0x8000);
 
 	uint32 xmsOffset = 0;
@@ -483,11 +521,11 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 		remaining -= chunk;
 	}
 
-	_headerXmsPicEntriesBase = xmsOffset;
-	_headerXmsPicEntriesBytes = midiHeaderBytes;
+	_headerXmsMidiEntriesBase = xmsOffset;
+	_headerXmsMidiEntriesBytes = midiHeaderBytes;
 	if (midiHeaderBytes && scenePtr) {
 		memset(scenePtr, 0, midiHeaderBytes);
-		objFileReadEntries(scenePtr);
+		midiFileReadEntries(scenePtr);
 
 		if (assetsXmsCopy(&_headerXmsData[0], _headerXmsData.size(), xmsOffset,
 				scenePtr, midiHeaderBytes, 0, midiHeaderBytes) < 0)
@@ -513,90 +551,73 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	_sceneEntryFrameSize = 0;
 	Common::ScopedPtr<Common::SeekableReadStream> message(pathFOpen(Common::Path("MESSAGE"), true));
 	_usesWcomfy99ScriptOps = bool(message);
-	_wcomfy99FeatureWordCount = 0;
-	_wcomfy99Sensitivity = ConfMan.hasKey("SENSITIVITY") ? ConfMan.getInt("SENSITIVITY") : 0;
-	_wcomfy99RecordHostEnabled = false;
-	_wcomfy99SubsystemWord = 0;
-	_wcomfy99MixedHostFirstWord = 0;
-	_wcomfy99MixedHostSecondWord = 0;
-	_wcomfy99MixedHostThirdWord = 0;
-	_wcomfy99MixedHostFourthWord = 0;
-	_wcomfy99HostWordA = 0;
-	_wcomfy99HostWordB = 0;
-	_wcomfy99WaveVolumePercent = 0;
-	_wcomfy99WaveLeftPercent = 0;
-	_wcomfy99WaveRightPercent = 0;
-	_wcomfy99MixerVolumePercent = 0;
-	_wcomfy99MixerAltPercent = 0;
-	_wcomfy99RangeHostStart = 0;
-	_wcomfy99RangeHostEnd = 0;
-	_wcomfy99RangeHostCount = 0;
-	memset(_wcomfy99FeatureWords, 0, sizeof(_wcomfy99FeatureWords));
-	_pendingScene = 0;
-	_musicEventMask = 0;
-	_musicEventFlag = 0;
-	_musicEnabled = false;
-	for (uint i = 0; i < COMFY_VOC_QUEUE_CAPACITY; i++)
-		_vocQueue[i] = VocQueueEntry();
-	_soundEventIndex = 0;
-	_soundEventMaximum = 0;
-	_soundEventSubIndex = 0xFFFF;
-	_soundEventPreviousSubIndex = 0xFFFF;
 	_scriptFault = false;
 
 	return true;
 }
 
 void ComfyEngine::assetsUnload(byte freeAudio) {
-	animFileShutdown(true);
+	if (_engineVersion == kEngineVersion3) {
+		_objectCacheEntries.clear();
+		_frameCacheEntries.clear();
+		_scenePoolData.clear();
+		spriteInvalidateHostCache(_frameSpriteResource);
+		_frameSpriteResource.id = 0;
+		_environmentData.clear();
+		_headerXmsData.clear();
+
+		if (_picFileMapped)
+			soundShutdown();
+
+		_picFileData.clear();
+		_comfyObjData.clear();
+
+		if (_sceneOpen)
+			sceneShutdown();
+
+		animFileShutdown();
+		selPoolFree();
+	} else {
+		animFileShutdown();
+		_spriteHeaders.clear();
+		_spriteResources.clear();
+		_stringTable.clear();
+		_sceneHandles.clear();
+		_midiHandles.clear();
+		_actors.clear();
+		_sceneMemoryBlock.clear();
+		keyBitFree();
+		_objectCacheEntries.clear();
+		_frameCacheEntries.clear();
+		_scenePoolData.clear();
+		_environmentData.clear();
+		_headerXmsData.clear();
+
+		if (_picFileMapped)
+			soundShutdown();
+
+		_picFileData.clear();
+		_comfyObjData.clear();
+
+		if (_soundLoaded && _sceneOpen)
+			sceneShutdown();
+
+		selPoolFree();
+	}
+
 	_spriteHeaders.clear();
 	_spriteResources.clear();
-	spriteInvalidateHostCache(_frameSpriteResource);
-	_frameSpriteResource.id = 0;
 	_stringTable.clear();
 	_sceneHandles.clear();
 	_midiHandles.clear();
 	_actors.clear();
 	_sceneMemoryBlock.clear();
-	_scenePoolData.clear();
-	_environmentData.clear();
-	_headerXmsData.clear();
-	_objectCacheEntries.clear();
-	_frameCacheEntries.clear();
 	keyBitFree();
-	soundShutdown();
-
-	if (_sceneOpen)
-		sceneShutdown();
-
-	_comfyObjData.clear();
-	_picFileData.clear();
 	_midiFileData.clear();
-	selPoolFree();
 	_spriteConversionLoads = ResourceLoadList();
 	memset(_sceneEntryOffsets, 0, sizeof(_sceneEntryOffsets));
 	memset(_actorPcTable, 0, sizeof(_actorPcTable));
 	_usesWcomfy99ScriptOps = false;
-	_wcomfy99FeatureWordCount = 0;
-	_wcomfy99Sensitivity = 0;
-	_wcomfy99RecordHostEnabled = false;
-	_wcomfy99SubsystemWord = 0;
-	_wcomfy99MixedHostFirstWord = 0;
-	_wcomfy99MixedHostSecondWord = 0;
-	_wcomfy99MixedHostThirdWord = 0;
-	_wcomfy99MixedHostFourthWord = 0;
-	_wcomfy99HostWordA = 0;
-	_wcomfy99HostWordB = 0;
-	_wcomfy99WaveVolumePercent = 0;
-	_wcomfy99WaveLeftPercent = 0;
-	_wcomfy99WaveRightPercent = 0;
-	_wcomfy99MixerVolumePercent = 0;
-	_wcomfy99MixerAltPercent = 0;
-	_wcomfy99RangeHostStart = 0;
-	_wcomfy99RangeHostEnd = 0;
-	_wcomfy99RangeHostCount = 0;
-	memset(_wcomfy99FeatureWords, 0, sizeof(_wcomfy99FeatureWords));
-	_pendingScene = 0;
 	_currentActor = 0;
 	_scriptFault = false;
 	_stringCount = 0;
@@ -617,6 +638,14 @@ void ComfyEngine::assetsUnload(byte freeAudio) {
 	_activeSceneCount = 0;
 	_sceneEntryCount = 0;
 	_sceneEntryFrameSize = 0;
+	_sceneMidiInstanceOffset = 0;
+	_sceneEntryListOffset = 0;
+	_sceneActorPcOffset = 0;
+	_sceneStringTableOffset = 0;
+	_sceneHandlesOffset = 0;
+	_sceneActorsOffset = 0;
+	_sceneKeyBitsOffset = 0;
+	_sceneAnimStateOffset = 0;
 	_midiFileMode = 0;
 	_usesAnimFile = false;
 	_sceneEntryListActive = false;
@@ -624,10 +653,10 @@ void ComfyEngine::assetsUnload(byte freeAudio) {
 	_scenePoolEvictCursor = 0;
 	_scenePoolSize = 0;
 	_headerXmsObjectTableBase = 0;
-	_headerXmsPicEntriesBase = 0;
+	_headerXmsMidiEntriesBase = 0;
 	_headerXmsSoundHeadersBase = 0;
 	_headerXmsObjectTableBytes = 0;
-	_headerXmsPicEntriesBytes = 0;
+	_headerXmsMidiEntriesBytes = 0;
 	_headerXmsSoundHeadersBytes = 0;
 	// The original consumes one UI character here; ScummVM has no teardown prompt to acknowledge.
 	(void)freeAudio;
diff --git a/engines/comfy/input.cpp b/engines/comfy/input.cpp
index 6d33d09c657..3e0551ff90f 100644
--- a/engines/comfy/input.cpp
+++ b/engines/comfy/input.cpp
@@ -88,7 +88,11 @@ void ComfyEngine::lptKeyToFlags(uint16 key) {
 			flags |= 0x10;
 			break;
 		case 27:
-			flags |= 0x20;
+			if (_engineVersion == kEngineVersion3 && (_inputDeviceMode == 2 || _inputDeviceMode == 4) &&
+					!_inputKeyboardBit7Held)
+				_inputKeyboardResetRequested = true;
+			else
+				flags |= 0x20;
 			break;
 		default:
 			break;
@@ -109,6 +113,9 @@ void ComfyEngine::hostKeyboardResetMap() {
 }
 
 bool ComfyEngine::hostKeyboardLoadDatMap() {
+	if (_engineVersion == kEngineVersion3 && _inputDeviceMode == 1)
+		return true;
+
 	hostKeyboardResetMap();
 	Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(Common::Path("KEYBOARD.DAT"), false));
 	if (!stream)
@@ -196,7 +203,6 @@ void ComfyEngine::setKeyboardContact(uint16 contact, bool pressed, bool keymappe
 		*activeMask |= mask;
 		*latchedMask &= ~mask;
 	} else {
-		*activeMask &= ~mask;
 		*latchedMask |= mask;
 	}
 }
@@ -212,7 +218,57 @@ uint32 ComfyEngine::lptKeyboardScan() {
 	// iterations after each write, and sampled three bits from the status port. Concatenating those
 	// eight 3-bit samples produced the 24-contact scan word. ScummVM supplies that same word from the
 	// keymapper, KEYBOARD.DAT mappings, and the toy-keyboard UI instead of accessing an I/O port.
+	if (_engineVersion == kEngineVersion3 && _inputDeviceMode == 2) {
+		_keyboardActiveMask |= _keymapperActiveMask;
+		_keyboardLatchedMask |= _keymapperLatchedMask;
+		_keymapperActiveMask = 0;
+		_keymapperLatchedMask = 0;
+	}
+
+	if (_engineVersion == kEngineVersion3) {
+		if (_inputKeyboardResetRequested) {
+			_inputKeyboardResetRequested = false;
+			_inputKeyboardSyntheticBit7 = false;
+			_keyboardActiveMask &= ~0x80;
+			_keyboardLatchedMask &= ~0x80;
+		} else if ((_inputDeviceMode == 2 && _inputKeyboardBit7Held) || (_keyboardActiveMask & 0x80)) {
+			_inputKeyboardSyntheticBit7 = true;
+			_keyboardActiveMask |= 0x80;
+		}
+
+		if (_keyboardActiveMask & 0x02) {
+			uint32 timeCounter = _midiPlyrDriver ? _midiPlyrDriver->getTimeCounter() : _midiTimeCounter;
+			if (!_inputKeyboardPulseLatched && (_keyboardLatchedMask & 0x02) &&
+					timeCounter - _inputKeyboardPulseTime < 0x64)
+				_inputKeyboardPulseTicks = 6;
+		}
+
+		if (_keyboardActiveMask & 0x02)
+			_inputKeyboardPulseLatched = false;
+
+		if (_keyboardLatchedMask & 0x02) {
+			_inputKeyboardPulseLatched = true;
+			_inputKeyboardPulseTime = _midiPlyrDriver ? _midiPlyrDriver->getTimeCounter() : _midiTimeCounter;
+		}
+
+		_keyboardActiveMask &= ~0x02;
+		_keyboardLatchedMask &= ~0x02;
+		if (_inputKeyboardPulseTicks) {
+			_inputComfyboardSuppressBit1 = true;
+			_inputKeyboardPulseTicks--;
+			if (_inputKeyboardPulseTicks & 1) {
+				_keyboardActiveMask |= 0x02;
+				_keyboardLatchedMask |= 0x02;
+			}
+		} else {
+			_inputComfyboardSuppressBit1 = false;
+		}
+	}
+
 	uint32 keyboardState = (_keyboardActiveMask | _keyboardLatchedMask) & 0x00FFFFFF;
+	if (_inputKeyboardSyntheticBit7)
+		keyboardState |= 0x80;
+
 	uint32 comfyboardState = (_toyKeyboardActiveMask | _toyKeyboardHoldMask |
 		_toyKeyboardLatchedMask) & 0x00FFFFFF;
 	uint32 comfyboardHostState = (comfyboardState | _keymapperActiveMask | _keymapperLatchedMask) & 0x00FFFFFF;
@@ -238,9 +294,30 @@ uint32 ComfyEngine::lptKeyboardScan() {
 	if (_engineVersion == kEngineVersion3 && _inputDeviceMode == 1)
 		scanState = comfyboardState;
 	else if (_engineVersion == kEngineVersion3 && _inputDeviceMode == 2)
-		scanState = keyboardState;
-	else
+		scanState = keyboardState | (_inputKeyboardBit7Held ? 0x80 : 0);
+	else if (_engineVersion == kEngineVersion3 && (_inputDeviceMode == 3 || _inputDeviceMode == 4)) {
+		// Modes 3 and 4 used WinMM MIDI input. ScummVM supplies their logical contacts through the keymapper/UI.
+		scanState = (_toyKeyboardActiveMask | _toyKeyboardHoldMask | _toyKeyboardLatchedMask |
+				_keymapperActiveMask | _keymapperLatchedMask) & 0x00FFFFFF;
+		if (_inputDeviceMode == 4) {
+			scanState |= 0x2000;
+			if (_inputKeyboardSyntheticBit7)
+				scanState |= 0x80;
+		}
+	} else if (_engineVersion == kEngineVersion3 && !_inputDeviceMode) {
+		if (_inputComfyboardSuppressBit1)
+			comfyboardState &= ~0x02;
+
+		if (_inputKeyboardSyntheticBit7)
+			keyboardState |= 0x80;
+
 		scanState = comfyboardState | keyboardState;
+	} else {
+		scanState = comfyboardState | keyboardState;
+	}
+
+	if (_engineVersion == kEngineVersion3)
+		_inputKeyboardBit7Held = (scanState & 0x80) != 0;
 
 	_keyboardActiveMask &= ~_keyboardLatchedMask;
 	_keymapperActiveMask &= ~_keymapperLatchedMask;
@@ -343,16 +420,10 @@ void ComfyEngine::lptKeyboardDispatchEvents(uint32 scanState) {
 }
 
 void ComfyEngine::lptKeyboardInit() {
-	inputQueueReset();
-	hostKeyboardLoadDatMap();
-	_lptPrevScanState = 0;
-	_inputDeviceMode = _inputDevicePreference;
-	_inputPreviousComfyboardState = 0;
-	_inputPreviousKeyboardState = 0;
-	_inputComfyboardActivityCount = 0;
-	_inputKeyboardActivityCount = 0;
+	_inputInitialDeviceMode = _inputDeviceMode;
 	_keyboardUiVisible = true;
-	if (_engineVersion == kEngineVersion3 && _midiPlyrDriver) {
+	if (_engineVersion == kEngineVersion3 && _midiPlyrDriver &&
+			(_inputDeviceMode == 0 || _inputDeviceMode == 1)) {
 		if (!_inputDeviceMode)
 			_midiPlyrDriver->comfyboardStartSleepUse();
 
@@ -381,7 +452,8 @@ void ComfyEngine::lptKeyboardShutdown() {
 #endif
 
 	_keyboardUiInitialized = false;
-	if (_engineVersion == kEngineVersion3 && _midiPlyrDriver) {
+	if (_engineVersion == kEngineVersion3 && _midiPlyrDriver &&
+			(_inputInitialDeviceMode == 0 || _inputInitialDeviceMode == 1)) {
 		_midiPlyrDriver->comfyboardStopReading();
 		_midiPlyrDriver->comfyboardStopSleepUse();
 	}
diff --git a/engines/comfy/midi.cpp b/engines/comfy/midi.cpp
index e4cf247b041..4983e9202fc 100644
--- a/engines/comfy/midi.cpp
+++ b/engines/comfy/midi.cpp
@@ -27,6 +27,29 @@
 
 namespace Comfy {
 
+void ComfyEngine::midiHandleAddTo(uint16 handleIndex, int16 delta) {
+	if (handleIndex < _midiHandles.size())
+		_midiHandles[handleIndex] += delta;
+}
+
+void ComfyEngine::midiHandleCopy(uint16 destination, uint16 source) {
+	if (destination < _midiHandles.size() && source < _midiHandles.size())
+		_midiHandles[destination] = _midiHandles[source];
+}
+
+void ComfyEngine::midiHandleSet(uint16 handleIndex, uint16 value) {
+	if (handleIndex < _midiHandles.size())
+		_midiHandles[handleIndex] = value;
+}
+
+uint16 ComfyEngine::midiGetHandle(uint16 handleIndex) {
+	return handleIndex < _midiHandles.size() ? _midiHandles[handleIndex] : 0;
+}
+
+uint16 ComfyEngine::midiGetVersion() {
+	return COMFY_SCENE_MIDI_VERSION_BYTES_CLASSIC;
+}
+
 uint16 ComfyEngine::midiTick() {
 	if (!_midiPlyrDriver)
 		return 0;
@@ -173,12 +196,44 @@ void ComfyEngine::midiFindNext(MidiQueue &queue) {
 	}
 }
 
-void ComfyEngine::midiInitInstance() {
+void ComfyEngine::midiInitInstanceAt() {
 	_midiEvents = MidiQueue();
 	_midiTracks = MidiQueue();
+	_midiTimeCounter = 0;
+	_midiInstanceEventTime = _midiTimeCounter;
+	_midiInstanceTrackBase = 1;
 	_midiEvents.baseTime = 0;
 	_midiTracks.baseTime = 1;
+	if (_midiPlyrDriver)
+		_midiPlyrDriver->setTimeCounter(_midiTimeCounter);
+
+	midiFindNext(_midiEvents);
+	midiFindNext(_midiTracks);
+}
+
+void ComfyEngine::midiInitInstance() {
+	if (_engineVersion == kEngineVersion3) {
+		_midiTracks.nextTime = 0;
+		_midiTracks.nextIndex = 0x03E7;
+		_midiEvents.nextTime = 0;
+		_midiEvents.nextIndex = 0x03E7;
+		_midiTimeScale = 0x400;
+		if (_midiPlyrDriver) {
+			_midiPlyrDriver->setIncreaseVocCounter(0);
+			_midiPlyrDriver->setVocCounter(0);
+			_midiPlyrDriver->setTimeCounter(0);
+		}
+
+		return;
+	}
+
+	_midiEvents = MidiQueue();
+	_midiTracks = MidiQueue();
+	_midiTimeCounter = 0;
+	_midiInstanceEventTime = _midiTimeCounter;
 	_midiInstanceTrackBase = 1;
+	_midiEvents.baseTime = 0;
+	_midiTracks.baseTime = 1;
 	midiFindNext(_midiEvents);
 	midiFindNext(_midiTracks);
 }
@@ -187,9 +242,14 @@ void ComfyEngine::midiInitChannels() {
 	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
 		_midiChannels[channel] = MidiChannelState();
 		MidiChannelState &state = _midiChannels[channel];
-		state.volumeCurrent = state.volumeTarget = state.volumeDefault = 0x6400;
-		state.rateCurrent = state.rateTarget = state.rateDefault = 0x07D0;
-		state.pitchCurrent = state.pitchTarget = state.pitchDefault = 0x1388;
+		state.volumeCurrent = state.volumeDefault = 0x6400;
+		state.rateCurrent = state.rateDefault = 0x07D0;
+		state.pitchCurrent = state.pitchDefault = 0x1388;
+		if (_engineVersion != kEngineVersion3) {
+			state.volumeTarget = state.volumeDefault;
+			state.rateTarget = state.rateDefault;
+			state.pitchTarget = state.pitchDefault;
+		}
 	}
 }
 
@@ -212,17 +272,19 @@ void ComfyEngine::midiQueueAdd(MidiQueue &queue, uint16 id, int16 delta) {
 	midiFindNext(queue);
 }
 
-void ComfyEngine::midiQueueRemove(MidiQueue &queue, uint16 id) {
+bool ComfyEngine::midiQueueRemove(MidiQueue &queue, uint16 id) {
+	bool removed = false;
 	for (uint i = 0; i < queue.count;) {
 		if (queue.entries[i].id == id) {
 			queue.count--;
 			queue.entries[i] = queue.entries[queue.count];
+			removed = true;
 		} else {
 			i++;
 		}
 	}
 
-	midiFindNext(queue);
+	return removed;
 }
 
 void ComfyEngine::midiAddEvent(uint16 id, int16 delta) {
@@ -234,8 +296,11 @@ void ComfyEngine::midiAddTrack(uint16 id, int16 delta) {
 }
 
 void ComfyEngine::midiRemoveTrack(uint16 id) {
-	midiQueueRemove(_midiTracks, id);
+	if (midiQueueRemove(_midiTracks, id))
+		midiFindNext(_midiTracks);
+
 	midiQueueRemove(_midiEvents, id);
+	midiFindNext(_midiEvents);
 }
 
 void ComfyEngine::midiClearChannel(uint16 channel) {
@@ -243,7 +308,27 @@ void ComfyEngine::midiClearChannel(uint16 channel) {
 		return;
 
 	_midiChannels[channel].loadedFrameSize = 0;
-	_midiChannels[channel].playing = false;
+}
+
+void ComfyEngine::midiFireClearMarker(uint16 channel, int16 marker) {
+	if (channel >= COMFY_MIDI_CHANNEL_COUNT || marker <= 0)
+		return;
+
+	MidiTrackEntry &entry = _midiChannels[channel].entries[0];
+	if (marker <= entry.frameCount && marker <= COMFY_ANIM_FRAME_CAPACITY)
+		keyBitSet(entry.frames[marker - 1]);
+}
+
+void ComfyEngine::midiPollSceneEntries() {
+	if (!_midiPlyrDriver)
+		return;
+
+	for (uint channel = 0; channel < COMFY_SCENE_MUSIC_CHANNEL_COUNT; channel++) {
+		if (_sceneEntryCompletionKeys[channel] && !_midiPlyrDriver->musicIsSongPlaying(channel)) {
+			keyBitSet(_sceneEntryCompletionKeys[channel]);
+			_sceneEntryCompletionKeys[channel] = 0;
+		}
+	}
 }
 
 void ComfyEngine::midiResumeAll() {
@@ -269,10 +354,8 @@ void ComfyEngine::midiStopChannel(uint16 channel) {
 
 	uint16 size = state.loadedFrameSize;
 	state.rateCurrent = state.rateDefault = size >= 4 ? READ_LE_UINT16(song + 2) : 0x07D0;
-	state.rateTarget = state.rateCurrent;
+	state.rateTicksLeft = 0;
 	_midiPlyrDriver->musicPlaySong(song, size, channel);
-	_midiPlyrDriver->musicSetVolume(uint16(state.volumeCurrent >> 8), channel);
-	state.playing = true;
 }
 
 void ComfyEngine::midiStopAll() {
@@ -320,6 +403,7 @@ void ComfyEngine::midiFinishChannel(uint16 channel) {
 	if (_midiPlyrDriver)
 		_midiPlyrDriver->musicStopSong(1, channel);
 
+	midiClearChannel(channel);
 	if (state.entries[0].completionKey)
 		keyBitSet(state.entries[0].completionKey);
 
@@ -327,7 +411,6 @@ void ComfyEngine::midiFinishChannel(uint16 channel) {
 		state.entries[i - 1] = state.entries[i];
 
 	state.entryCount--;
-	midiClearChannel(channel);
 	if (state.entryCount)
 		midiStopChannel(channel);
 }
@@ -368,7 +451,7 @@ void ComfyEngine::midiAddTrackEntry(uint16 channel, uint16 songId, uint16 comple
 		channel = 0;
 
 	MidiChannelState &state = _midiChannels[channel];
-	if (state.entryCount == COMFY_MIDI_TRACK_ENTRY_CAPACITY)
+	if (state.entryCount >= COMFY_MIDI_TRACK_ENTRY_CAPACITY)
 		return;
 
 	MidiTrackEntry &entry = state.entries[state.entryCount];
@@ -376,7 +459,6 @@ void ComfyEngine::midiAddTrackEntry(uint16 channel, uint16 songId, uint16 comple
 	entry.completionKey = completionKey;
 	entry.loadFlag = loadFlag;
 	entry.frameCount = frameCount;
-	memset(entry.frames, 0, sizeof(entry.frames));
 	for (uint i = 0; i < frameCount && i < COMFY_ANIM_FRAME_CAPACITY; i++)
 		entry.frames[i] = frames ? frames[i] : 0;
 
@@ -430,13 +512,16 @@ int16 ComfyEngine::midiApproachTarget(int16 current, int16 target, int16 &ticksL
 
 void ComfyEngine::musicSetEnabled(byte value) {
 	_musicEnabled = value;
-	_soundPaused = value != 0;
-	_mixer->pauseHandle(_soundHandle, _soundPaused);
+	if (!_animFrameReady || !_animUsesWaveVocCounter || value) {
+		_soundPaused = value != 0;
+		_mixer->pauseHandle(_soundHandle, _soundPaused);
+		if (_midiPlyrDriver)
+			_midiPlyrDriver->setIncreaseVocCounter(_soundPaused ? 0 : 1);
+	}
+
 	if (!_midiPlyrDriver)
 		return;
 
-	_midiPlyrDriver->setIncreaseVocCounter(_soundPaused ? 0 : 1);
-
 	if (_musicEnabled) {
 		_midiPlyrDriver->musicStopAll(0);
 	} else {
diff --git a/engines/comfy/module.mk b/engines/comfy/module.mk
index ba53f6b79b1..2914102c847 100644
--- a/engines/comfy/module.mk
+++ b/engines/comfy/module.mk
@@ -6,7 +6,6 @@ MODULE_OBJS = \
 	comfy.o \
 	comfy_keyboard_ui.o \
 	console.o \
-	entry.o \
 	expr.o \
 	game.o \
 	input.o \
diff --git a/engines/comfy/palette.cpp b/engines/comfy/palette.cpp
index db98fcae6ba..03a20a4b0b5 100644
--- a/engines/comfy/palette.cpp
+++ b/engines/comfy/palette.cpp
@@ -93,7 +93,9 @@ void ComfyEngine::paletteFadeStep(uint16 delta) {
 
 void ComfyEngine::paletteLoadWithFade(uint16 paletteId, uint16 fadeTicks) {
 	colorDatReadEntry(paletteId);
-	_palettePage = 'S';
+	if (_engineVersion != kEngineVersion3)
+		_palettePage = 'S';
+
 	if (_paletteFading)
 		memcpy(_paletteFadeSource, _paletteDisplay, COMFY_PALETTE_BYTES);
 
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index acd5a76ffe0..04360f714a2 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -50,6 +50,29 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 	WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x184], _midiInstanceTrackBase);
 	WRITE_LE_UINT16(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x188], _midiEvents.count);
 	WRITE_LE_UINT16(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x18A], _midiTracks.count);
+	if (_engineVersion == kEngineVersion3) {
+		byte *vocState = &_sceneMemoryBlock[_sceneMidiInstanceOffset + COMFY_SCENE_MIDI_INSTANCE_BYTES];
+		vocState[0] = _wcomfy99VocState0;
+		vocState[1] = _wcomfy99VocState1;
+		vocState[2] = _wcomfy99VocState2;
+		vocState[3] = _wcomfy99VocState3;
+		vocState[6] = _wcomfy99VocState6;
+		for (uint i = 0; i < COMFY_VOC_QUEUE_CAPACITY; i++) {
+			byte *packedEntry = vocState + 7 + i * 0x1F;
+			VocQueueEntry1999 &entry = _vocQueue1999[i];
+			WRITE_LE_UINT16(packedEntry, entry.soundId);
+			WRITE_LE_UINT16(packedEntry + 2, entry.argumentCount);
+			WRITE_LE_UINT16(packedEntry + 4, entry.state);
+			for (uint argument = 0; argument < COMFY_VOC_ARG_CAPACITY_1999; argument++)
+				WRITE_LE_UINT16(packedEntry + 6 + argument * 2, entry.arguments[argument]);
+
+			packedEntry[0x1E] = entry.clearArgumentKeys;
+		}
+
+		WRITE_LE_UINT16(vocState + 0x1F7, _soundEventIndex);
+		WRITE_LE_UINT16(vocState + 0x1F9, _soundEventMaximum);
+	}
+
 	byte *sceneEntries = &_sceneMemoryBlock[_sceneEntryListOffset];
 	sceneEntries[0] = _sceneEntryListActive;
 	WRITE_LE_UINT16(sceneEntries + 1, _sceneEntryCount);
@@ -57,9 +80,17 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 	for (uint i = 0; i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
 		WRITE_LE_UINT16(sceneEntries + 5 + i * 2, uint16(_sceneEntryOffsets[i]));
 
+	if (_engineVersion == kEngineVersion3) {
+		for (uint channel = 0; channel < COMFY_SCENE_MUSIC_CHANNEL_COUNT; channel++) {
+			WRITE_LE_UINT16(sceneEntries + 0x25 + channel * 2, _sceneEntryVolumes[channel]);
+			WRITE_LE_UINT16(sceneEntries + 0x31 + channel * 2, _sceneEntryCompletionKeys[channel]);
+		}
+	}
+
+	uint32 channelTableOffset = _engineVersion == kEngineVersion3 ? 0x3D : 0x25;
 	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
 		MidiChannelState &state = _midiChannels[channel];
-		byte *packed = sceneEntries + 0x25 + channel * 0xA1;
+		byte *packed = sceneEntries + channelTableOffset + channel * 0xA1;
 		WRITE_LE_UINT16(packed + 0x87, state.entryCount);
 		WRITE_LE_UINT16(packed + 0x89, state.volumeCurrent);
 		WRITE_LE_UINT16(packed + 0x8B, state.volumeTarget);
@@ -91,32 +122,36 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 	if (!_sceneHandles.empty())
 		memcpy(&_sceneMemoryBlock[_sceneHandlesOffset], &_sceneHandles[0], _sceneHandles.size() * sizeof(uint16));
 
-	if (!_actors.empty())
-		memcpy(&_sceneMemoryBlock[_sceneActorsOffset], &_actors[0], _actors.size() * sizeof(Actor));
+	uint32 actorStride = _engineVersion == kEngineVersion3 ? COMFY_ACTOR_SIZE_V3 : sizeof(Actor);
+	for (uint i = 0; i < _actors.size(); i++)
+		memcpy(&_sceneMemoryBlock[_sceneActorsOffset + i * actorStride], &_actors[i], sizeof(Actor));
 
 	if (_keyBits && _keyBitsSize)
 		memcpy(&_sceneMemoryBlock[_sceneKeyBitsOffset], _keyBits, _keyBitsSize);
+
+	if (_usesAnimFile)
+		animFilePackState(&_sceneMemoryBlock[_sceneAnimStateOffset]);
 }
 
 void ComfyEngine::envConvToXms(byte *source, uint16 index) {
 	if (!index || _sceneMemoryBlock.empty())
-		return;
+		error("Invalid environment XMS destination %u", uint(index));
 
 	sceneBlockPackRuntimeState();
 	uint32 offset = uint32(index - 1) * _sceneMemoryBlock.size();
 	if (offset > _environmentData.size() || _sceneMemoryBlock.size() > _environmentData.size() - offset)
-		return;
+		error("Environment XMS destination %u is outside the allocated block", uint(index));
 
 	memcpy(&_environmentData[offset], source, _sceneMemoryBlock.size());
 }
 
 bool ComfyEngine::envXmsToConv(byte *destination, uint16 index) {
 	if (!index || _sceneMemoryBlock.empty())
-		return true;
+		error("Invalid environment XMS source %u", uint(index));
 
 	uint32 offset = uint32(index - 1) * _sceneMemoryBlock.size();
 	if (offset > _environmentData.size() || _sceneMemoryBlock.size() > _environmentData.size() - offset)
-		return true;
+		error("Environment XMS source %u is outside the allocated block", uint(index));
 
 	memcpy(destination, &_environmentData[offset], _sceneMemoryBlock.size());
 	sceneBlockUnpackRuntimeState();
@@ -144,6 +179,29 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 	_midiTracks.baseTime = _midiInstanceTrackBase;
 	midiFindNext(_midiEvents);
 	midiFindNext(_midiTracks);
+	if (_engineVersion == kEngineVersion3) {
+		byte *vocState = &_sceneMemoryBlock[_sceneMidiInstanceOffset + COMFY_SCENE_MIDI_INSTANCE_BYTES];
+		_wcomfy99VocState0 = vocState[0];
+		_wcomfy99VocState1 = vocState[1];
+		_wcomfy99VocState2 = vocState[2];
+		_wcomfy99VocState3 = vocState[3];
+		_wcomfy99VocState6 = vocState[6];
+		for (uint i = 0; i < COMFY_VOC_QUEUE_CAPACITY; i++) {
+			byte *packedEntry = vocState + 7 + i * 0x1F;
+			VocQueueEntry1999 &entry = _vocQueue1999[i];
+			entry.soundId = READ_LE_UINT16(packedEntry);
+			entry.argumentCount = MIN<uint16>(READ_LE_UINT16(packedEntry + 2), COMFY_VOC_ARG_CAPACITY_1999);
+			entry.state = READ_LE_UINT16(packedEntry + 4);
+			for (uint argument = 0; argument < COMFY_VOC_ARG_CAPACITY_1999; argument++)
+				entry.arguments[argument] = READ_LE_UINT16(packedEntry + 6 + argument * 2);
+
+			entry.clearArgumentKeys = packedEntry[0x1E] != 0;
+		}
+
+		_soundEventIndex = READ_LE_UINT16(vocState + 0x1F7) % COMFY_VOC_QUEUE_CAPACITY;
+		_soundEventMaximum = READ_LE_UINT16(vocState + 0x1F9) % COMFY_VOC_QUEUE_CAPACITY;
+	}
+
 	byte *sceneEntries = &_sceneMemoryBlock[_sceneEntryListOffset];
 	_sceneEntryListActive = sceneEntries[0] != 0;
 	_sceneEntryCount = READ_LE_UINT16(sceneEntries + 1);
@@ -151,9 +209,17 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 	for (uint i = 0; i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
 		_sceneEntryOffsets[i] = READ_LE_UINT16(sceneEntries + 5 + i * 2);
 
+	if (_engineVersion == kEngineVersion3) {
+		for (uint channel = 0; channel < COMFY_SCENE_MUSIC_CHANNEL_COUNT; channel++) {
+			_sceneEntryVolumes[channel] = READ_LE_UINT16(sceneEntries + 0x25 + channel * 2);
+			_sceneEntryCompletionKeys[channel] = READ_LE_UINT16(sceneEntries + 0x31 + channel * 2);
+		}
+	}
+
+	uint32 channelTableOffset = _engineVersion == kEngineVersion3 ? 0x3D : 0x25;
 	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
 		MidiChannelState &state = _midiChannels[channel];
-		byte *packed = sceneEntries + 0x25 + channel * 0xA1;
+		byte *packed = sceneEntries + channelTableOffset + channel * 0xA1;
 		state.entryCount = MIN<uint16>(READ_LE_UINT16(packed + 0x87), COMFY_MIDI_TRACK_ENTRY_CAPACITY);
 		state.volumeCurrent = READ_LE_UINT16(packed + 0x89);
 		state.volumeTarget = READ_LE_UINT16(packed + 0x8B);
@@ -180,10 +246,15 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 	memcpy(_actorPcTable, &_sceneMemoryBlock[_sceneActorPcOffset], sizeof(_actorPcTable));
 	memcpy(&_stringTable[0], &_sceneMemoryBlock[_sceneStringTableOffset], _stringTable.size() * sizeof(uint16));
 	memcpy(&_sceneHandles[0], &_sceneMemoryBlock[_sceneHandlesOffset], _sceneHandles.size() * sizeof(uint16));
-	memcpy(&_actors[0], &_sceneMemoryBlock[_sceneActorsOffset], _actors.size() * sizeof(Actor));
+	uint32 actorStride = _engineVersion == kEngineVersion3 ? COMFY_ACTOR_SIZE_V3 : sizeof(Actor);
+	for (uint i = 0; i < _actors.size(); i++)
+		memcpy(&_actors[i], &_sceneMemoryBlock[_sceneActorsOffset + i * actorStride], sizeof(Actor));
 	if (_keyBits && _keyBitsSize)
 		memcpy(_keyBits, &_sceneMemoryBlock[_sceneKeyBitsOffset], _keyBitsSize);
 
+	if (_usesAnimFile)
+		animFileUnpackState(&_sceneMemoryBlock[_sceneAnimStateOffset]);
+
 }
 
 void ComfyEngine::sceneGoto(uint16 count) {
@@ -192,9 +263,17 @@ void ComfyEngine::sceneGoto(uint16 count) {
 
 	_sceneEntryListActive = true;
 	_sceneEntryCount = count;
-	_sceneEntryFrameSize = count ? COMFY_SCENE_FRAME_BYTES / int16(count) : 0;
-	for (uint i = 0; i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
+	uint32 frameSize = _engineVersion == kEngineVersion3 ? COMFY_SCENE_FRAME_BYTES_V3 : COMFY_SCENE_FRAME_BYTES;
+	_sceneEntryFrameSize = count ? frameSize / int16(count) : 0;
+	for (uint i = 0; i < count && i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
 		_sceneEntryOffsets[i] = 0xFFFF;
+
+	if (_engineVersion == kEngineVersion3) {
+		for (uint channel = 0; channel < COMFY_SCENE_MUSIC_CHANNEL_COUNT; channel++) {
+			_sceneEntryVolumes[channel] = 100;
+			_sceneEntryCompletionKeys[channel] = 0;
+		}
+	}
 }
 
 void ComfyEngine::sceneStop() {
@@ -224,7 +303,7 @@ void ComfyEngine::sceneStartWithMusic(uint16 scene) {
 	if (root) {
 		paletteLoadWithFade(actorReadU16(*root, kActorXFixed), 0);
 		if (actorReadU32(*root, kActorYFixed))
-			paletteApplyBrightness(actorReadU16(*root, kActorYFixed));
+			paletteApplyBrightness(byte(actorReadU16(*root, kActorYFixed)));
 	}
 
 	if (_keyBits)
@@ -250,7 +329,7 @@ bool ComfyEngine::sceneEntryLoad(uint16 descriptor, uint16 index) {
 }
 
 void ComfyEngine::sceneEntryReadFromXms(byte *destination, uint16 row, uint16 size) {
-	objHdrReadFromXms(destination, _headerXmsPicEntriesBase, size, row);
+	objHdrReadFromXms(destination, _headerXmsMidiEntriesBase, size, row);
 }
 
 byte *ComfyEngine::sceneFrameGetPtr(uint16 kind, uint16 size) {
@@ -288,14 +367,14 @@ byte *ComfyEngine::spriteLoadFromFile(uint16 fileOffset, uint16 index) {
 }
 
 void ComfyEngine::midiStopSong(uint16 channel) {
-	if (_midiPlyrDriver && channel < COMFY_MIDI_CHANNEL_COUNT)
+	if (_midiPlyrDriver && channel < COMFY_SCENE_MUSIC_CHANNEL_COUNT)
 		_midiPlyrDriver->musicStopSong(1, channel);
 }
 
 void ComfyEngine::midiPlaySongAtFrame(uint16 channel, uint16 frame) {
 	midiStopSong(channel);
 	uint32 offset = uint32(_sceneEntryFrameSize) * frame;
-	if (!_midiPlyrDriver || channel >= COMFY_MIDI_CHANNEL_COUNT ||
+	if (!_midiPlyrDriver || channel >= COMFY_SCENE_MUSIC_CHANNEL_COUNT ||
 			offset > _sceneFrameData.size() || 6 > _sceneFrameData.size() - offset)
 		return;
 
@@ -305,16 +384,31 @@ void ComfyEngine::midiPlaySongAtFrame(uint16 channel, uint16 frame) {
 		return;
 
 	_midiPlyrDriver->musicPlaySong(song, size, channel);
-	_midiPlyrDriver->musicSetVolume(0x64, channel);
+	if (_engineVersion == kEngineVersion3) {
+		_midiPlyrDriver->musicSetVolume(_sceneEntryVolumes[channel], channel);
+		_sceneEntryCompletionKeys[channel] = 0;
+	} else {
+		_midiPlyrDriver->musicSetVolume(0x64, channel);
+	}
+}
+
+void ComfyEngine::sceneEntrySetVolume(uint16 channel, uint16 volume) {
+	if (channel >= COMFY_SCENE_MUSIC_CHANNEL_COUNT)
+		return;
+
+	_sceneEntryVolumes[channel] = volume;
+	if (_midiPlyrDriver)
+		_midiPlyrDriver->musicSetVolume(volume, channel);
 }
 
 bool ComfyEngine::sceneOpen(uint32 sceneEntryListOffset) {
 	_sceneEntryListOffset = sceneEntryListOffset;
 	_sceneEntryListActive = false;
 	_sceneEntryCount = 0;
-	_sceneEntryFrameSize = 0x4E20;
+	uint32 frameSize = _engineVersion == kEngineVersion3 ? COMFY_SCENE_FRAME_BYTES_V3 : COMFY_SCENE_FRAME_BYTES;
+	_sceneEntryFrameSize = frameSize;
 	if (_sceneFrameData.empty()) {
-		_sceneFrameData.resize(0x4E20);
+		_sceneFrameData.resize(frameSize);
 		memset(&_sceneFrameData[0], 0, _sceneFrameData.size());
 	}
 
@@ -323,7 +417,9 @@ bool ComfyEngine::sceneOpen(uint32 sceneEntryListOffset) {
 
 	_sceneOpen = true;
 	memset(_sceneEntryOffsets, 0, sizeof(_sceneEntryOffsets));
-	midiInitInstance();
+	if (_engineVersion != kEngineVersion3)
+		midiInitInstance();
+
 	midiInitChannels();
 	return true;
 }
@@ -334,6 +430,11 @@ void ComfyEngine::sceneShutdown() {
 
 	midiPlyrStop();
 	_sceneFrameData.clear();
+	if (_engineVersion == kEngineVersion3) {
+		_wcomfy99VocState2 = 0xFF;
+		_wcomfy99VocState3 = 0xFF;
+	}
+
 	_sceneOpen = false;
 }
 
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 7064c2e4bda..271c57e8b9c 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -133,7 +133,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		bool current = target == &actor;
 		uint16 actorIndex = uint16(target - &_actors[0]);
 		actorUnlink(actorIndex);
-		actorFreeTree(actorIndex);
+		actorFreeTreePc(actorIndex);
 		_actorDestroyedCurrent = current;
 		return current ? kScriptYield : kScriptContinue;
 	}
@@ -426,8 +426,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint16 handle = scriptReadWord(pc);
 		int16 delta = scriptReadStringIndex(pc + 2);
 		pc += 4;
-		if (handle < _midiHandles.size())
-			_midiHandles[handle] += delta;
+		midiHandleAddTo(handle, delta);
 
 		return kScriptContinue;
 	}
@@ -535,9 +534,10 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		pc += 7;
 		if (destination < _midiHandles.size() && first < _midiHandles.size()) {
 			if (command == '=')
-				_midiHandles[destination] = _midiHandles[first];
+				midiHandleCopy(destination, first);
 			else if (command == 'm' && second < _midiHandles.size())
-				_midiHandles[destination] = int16(_midiHandles[second]) <= int16(_midiHandles[first]) ? _midiHandles[first] : _midiHandles[second];
+				midiHandleCopy(destination,
+					int16(midiGetHandle(second)) <= int16(midiGetHandle(first)) ? first : second);
 		}
 
 		return kScriptContinue;
@@ -546,16 +546,18 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	if (opcode == 0x30 && _usesAnimFile) {
 		byte subop = scriptReadByte(pc++);
 		if (subop == 0) {
-			animFileShutdown(true);
+			animFrameShutdown(true);
 		} else if (subop == 1) {
 			uint16 animIndex = scriptReadWord(pc);
 			uint16 frameKey = scriptReadWord(pc + 2);
 			pc += 4;
 			animFileLoadFrame(animIndex, frameKey, actorReadU16(actor, kActorSceneHandle));
 		} else if (subop == 2) {
-			_animVocCounterMode = 1;
+			animFrameSetReady(true);
 		} else if (subop == 3) {
-			_animVocCounterMode = 0;
+			animFrameSetReady(false);
+		} else if (subop == 6) {
+			animFrameInvalidateActorRect();
 		}
 
 		return kScriptContinue;
@@ -571,6 +573,8 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 			pc += uint32(count) * 2;
 		} else if (opcode == 0x32) {
+			_wcomfy99Stub32FirstWord = scriptReadWord(pc);
+			_wcomfy99Stub32SecondWord = scriptReadWord(pc + 2);
 			pc += 4;
 		} else if (opcode == 0x33) {
 			pc += 4;
@@ -607,13 +611,11 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 				else
 					keyBitClear(value);
 			} else if (subop == 6) {
+				key.trim();
 				byte last = key.empty() ? 0 : key.lastChar();
 				if (value < _stringTable.size())
 					_stringTable[value] = Common::isSpace(last) ? 0x81 : Common::isDigit(last) ? 0x12 :
 						(Common::isAlpha(last) ? (Common::isUpper(last) ? 0x04 : 0x08) : 0x40);
-
-				pathSetGameDataDir(Common::Path(key));
-				_languageSessionRestartRequested = true;
 			}
 		} else if (opcode == 0x35) {
 			byte subop = scriptReadByte(pc++);
@@ -804,8 +806,10 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptYield;
 	}
 
-	if (opcode == 0x73)
+	if (opcode == 0x73) {
+		_waveOutputActive = false;
 		return kScriptContinue;
+	}
 
 	if (opcode == 0x74) {
 		uint16 key = scriptReadWord(pc);
diff --git a/engines/comfy/sound.cpp b/engines/comfy/sound.cpp
index 4859eda1bb9..1c737ac9d71 100644
--- a/engines/comfy/sound.cpp
+++ b/engines/comfy/sound.cpp
@@ -60,7 +60,6 @@ private:
 };
 
 bool ComfyEngine::soundInit() {
-	soundShutdown();
 	if (!readAssetFile(Common::Path("VOCFILE.DAT"), _vocFileData) || _vocFileData.size() < 4)
 		return false;
 
@@ -68,11 +67,21 @@ bool ComfyEngine::soundInit() {
 		return false;
 
 	_soundCompressed = _vocFileData[1] == 'W';
-	_soundTileStride = assetsReadLe16At(_vocFileData, 2);
+	_soundEntryCount = assetsReadLe16At(_vocFileData, 2);
 	_soundEventIndex = 0;
 	_soundEventMaximum = 0;
 	_soundEventSubIndex = 0xFFFF;
 	_soundEventPreviousSubIndex = 0xFFFF;
+	for (uint i = 0; i < COMFY_VOC_QUEUE_CAPACITY; i++) {
+		_vocQueue[i] = VocQueueEntry();
+		_vocQueue1999[i] = VocQueueEntry1999();
+	}
+
+	_wcomfy99VocState0 = 0;
+	_wcomfy99VocState1 = 0;
+	_wcomfy99VocState2 = 0;
+	_wcomfy99VocState3 = 0;
+	_wcomfy99VocState6 = 0;
 	return true;
 }
 
@@ -81,7 +90,7 @@ void ComfyEngine::soundShutdown() {
 	_soundPcm.clear();
 	_soundCues.clear();
 	_vocFileData.clear();
-	_soundTileStride = 0;
+	_soundEntryCount = 0;
 	_soundNextCue = 0;
 	_soundPaused = false;
 	if (_midiPlyrDriver)
@@ -92,6 +101,10 @@ void ComfyEngine::soundHdrReadFromXms(byte *destination, uint16 index, uint16 si
 	objHdrReadFromXms(destination, _headerXmsSoundHeadersBase, size, index);
 }
 
+void ComfyEngine::soundUnprepareHeader() {
+	soundAdvanceTick();
+}
+
 bool ComfyEngine::soundLoadEntry(uint16 index) {
 	byte header[8];
 	memset(header, 0, sizeof(header));


Commit: 1b426a971e32d84598e83bdf2953c82c0f900a2d
    https://github.com/scummvm/scummvm/commit/1b426a971e32d84598e83bdf2953c82c0f900a2d
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Clear ImGui callbacks on shutdown

Changed paths:
    engines/comfy/comfy.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 1b32a6160ee..86e7b5395f1 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -145,6 +145,13 @@ Common::Error ComfyEngine::gameInit() {
 }
 
 void ComfyEngine::gameShutdown() {
+#ifdef USE_IMGUI
+	if (_keyboardUiInitialized) {
+		_system->setImGuiCallbacks(ImGuiCallbacks());
+		_keyboardUiInitialized = false;
+	}
+#endif
+
 	if (_lptKeyboardInitialized) {
 		lptKeyboardShutdown();
 		midiShutdown();


Commit: a8b587f214700d430870875c36d2d088109ffa82
    https://github.com/scummvm/scummvm/commit/a8b587f214700d430870875c36d2d088109ffa82
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Keep ImGui callbacks for the engine lifetime

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/input.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 86e7b5395f1..254463f5a53 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -93,6 +93,15 @@ Common::Error ComfyEngine::gameInit() {
 	if (!iniReadGameConfig())
 		return Common::kNoGameDataFoundError;
 
+#ifdef USE_IMGUI
+	ImGuiCallbacks imGuiCallbacks;
+	imGuiCallbacks.init = onImGuiInit;
+	imGuiCallbacks.render = onImGuiRender;
+	imGuiCallbacks.cleanup = onImGuiCleanup;
+	_system->setImGuiCallbacks(imGuiCallbacks);
+	_keyboardUiInitialized = true;
+#endif
+
 	timerInit();
 	_gameInitialized = true;
 	_currentScene = _language;
diff --git a/engines/comfy/input.cpp b/engines/comfy/input.cpp
index 3e0551ff90f..df80c3f8150 100644
--- a/engines/comfy/input.cpp
+++ b/engines/comfy/input.cpp
@@ -429,15 +429,6 @@ void ComfyEngine::lptKeyboardInit() {
 
 		_midiPlyrDriver->comfyboardStartReading(0x006D96DB, _lptPortBase);
 	}
-
-#ifdef USE_IMGUI
-	ImGuiCallbacks imGuiCallbacks;
-	imGuiCallbacks.init = onImGuiInit;
-	imGuiCallbacks.render = onImGuiRender;
-	imGuiCallbacks.cleanup = onImGuiCleanup;
-	_system->setImGuiCallbacks(imGuiCallbacks);
-	_keyboardUiInitialized = true;
-#endif
 }
 
 void ComfyEngine::lptKeyboardScanAndProcess() {
@@ -446,12 +437,6 @@ void ComfyEngine::lptKeyboardScanAndProcess() {
 }
 
 void ComfyEngine::lptKeyboardShutdown() {
-#ifdef USE_IMGUI
-	if (_keyboardUiInitialized)
-		_system->setImGuiCallbacks(ImGuiCallbacks());
-#endif
-
-	_keyboardUiInitialized = false;
 	if (_engineVersion == kEngineVersion3 && _midiPlyrDriver &&
 			(_inputInitialDeviceMode == 0 || _inputInitialDeviceMode == 1)) {
 		_midiPlyrDriver->comfyboardStopReading();


Commit: 5188a94f024c7d4499b8986a48bba6d719a992a5
    https://github.com/scummvm/scummvm/commit/5188a94f024c7d4499b8986a48bba6d719a992a5
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Attempt to fix ImGui keyboard exit

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/comfy_keyboard_ui.cpp
    engines/comfy/detection_tables.h


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 254463f5a53..1e51e3ebeb9 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -99,7 +99,6 @@ Common::Error ComfyEngine::gameInit() {
 	imGuiCallbacks.render = onImGuiRender;
 	imGuiCallbacks.cleanup = onImGuiCleanup;
 	_system->setImGuiCallbacks(imGuiCallbacks);
-	_keyboardUiInitialized = true;
 #endif
 
 	timerInit();
@@ -108,7 +107,7 @@ Common::Error ComfyEngine::gameInit() {
 	uint16 chooserScene = 2;
 	if (_multiLanguage && (ConfMan.getBool("force_language_setup") ||
 			!ConfMan.getBool("comfy_language_chosen"))) {
-		if (!iniGetGameDataPath(0x63)) {
+		if (!iniGetGameDataPath(99)) {
 			gameShutdown();
 			return Common::kNoGameDataFoundError;
 		}
@@ -124,7 +123,7 @@ Common::Error ComfyEngine::gameInit() {
 		ConfMan.flushToDisk();
 	}
 
-	if (!_hasDataPath && iniGetGameDataPath(0)) {
+	if (iniGetGameDataPath(0)) {
 		sceneRun(_currentScene, false, true);
 		if (shouldQuit()) {
 			gameShutdown();
@@ -138,29 +137,27 @@ Common::Error ComfyEngine::gameInit() {
 			return Common::kNoGameDataFoundError;
 		}
 
-		if (_currentScene == 0x63) {
+		if (_currentScene == 99) {
 			_currentScene = sceneRun(chooserScene, _multiLanguage, false);
 		} else {
 			chooserScene = _currentScene;
 			_currentScene = sceneRun(_currentScene, _multiLanguage, false);
 		}
 
-		if (_currentScene && _currentScene != 0x63)
+		if (_currentScene && _currentScene != 99)
 			iniWriteLanguage(_currentScene);
 	}
 
 	gameShutdown();
-	return Common::kNoError;
-}
 
-void ComfyEngine::gameShutdown() {
 #ifdef USE_IMGUI
-	if (_keyboardUiInitialized) {
-		_system->setImGuiCallbacks(ImGuiCallbacks());
-		_keyboardUiInitialized = false;
-	}
+	_system->setImGuiCallbacks(ImGuiCallbacks());
 #endif
 
+	return Common::kNoError;
+}
+
+void ComfyEngine::gameShutdown() {
 	if (_lptKeyboardInitialized) {
 		lptKeyboardShutdown();
 		midiShutdown();
@@ -197,7 +194,10 @@ uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
 	byte restorePalette = 1;
 	byte shouldStartNext = 0;
 	uint16 nextScene = 0;
+
 	_lptKeyboardInitialized = true;
+	_keyboardUiInitialized = true;
+
 	hostKeyboardLoadDatMap();
 
 	if (_sceneRunBuffer.empty()) {
@@ -251,7 +251,9 @@ uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
 	}
 
 	videoShutdown(restorePalette);
+
 	_lptKeyboardInitialized = false;
+	_keyboardUiInitialized = false;
 
 	return nextScene;
 }
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index bcba95f9666..d425e25f699 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -420,7 +420,6 @@ private:
 	uint16 _inputKeyboardPulseTicks = 0;
 	bool _inputKeyboardPulseLatched = false;
 	uint32 _inputKeyboardPulseTime = 0;
-	bool _keyboardUiInitialized = false;
 	bool _keyboardUiVisible = true;
 	Common::Array<byte> _comfyObjData;
 	Common::Array<byte> _picFileData;
@@ -855,6 +854,7 @@ protected:
 public:
 	ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc);
 	~ComfyEngine() override;
+
 	void setToyKeyboardState(uint32 activeMask, uint32 latchedMask, uint32 holdMask);
 
 	/**
@@ -873,6 +873,7 @@ public:
 		return (f == kSupportsReturnToLauncher);
 	};
 
+	bool _keyboardUiInitialized = false;
 };
 
 extern ComfyEngine *g_engine;
diff --git a/engines/comfy/comfy_keyboard_ui.cpp b/engines/comfy/comfy_keyboard_ui.cpp
index 0ba66a06c99..37a13961b35 100644
--- a/engines/comfy/comfy_keyboard_ui.cpp
+++ b/engines/comfy/comfy_keyboard_ui.cpp
@@ -130,9 +130,6 @@ static void keyboardDrawToggle(const char *label, uint bit, ImVec2 size, ImU32 o
 }
 
 void onImGuiInit() {
-	ImGuiIO &io = ImGui::GetIO();
-	io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
-
 	_state = new ImGuiState();
 	_state->_engine = (ComfyEngine *)g_engine;
 }
@@ -141,6 +138,9 @@ void onImGuiRender() {
 	if (!_state || !_state->_engine || _state->_engine->shouldQuit())
 		return;
 
+	if (!_state->_engine->_keyboardUiInitialized)
+		return;
+
 	if (!_state->_visible) {
 		_state->_engine->setToyKeyboardState(0, _state->_latchedMask | _state->_activeMask, 0);
 		_state->_activeMask = 0;
@@ -149,8 +149,6 @@ void onImGuiRender() {
 		return;
 	}
 
-	ImGui::GetIO().ConfigFlags &= ~(ImGuiConfigFlags_NoMouseCursorChange | ImGuiConfigFlags_NoMouse);
-
 	ImGui::SetNextWindowPos(ImVec2(8, 8), ImGuiCond_FirstUseEver);
 	ImGui::SetNextWindowSize(ImVec2(740, 440), ImGuiCond_FirstUseEver);
 
diff --git a/engines/comfy/detection_tables.h b/engines/comfy/detection_tables.h
index f841e83f957..16ca5eee163 100644
--- a/engines/comfy/detection_tables.h
+++ b/engines/comfy/detection_tables.h
@@ -74,7 +74,7 @@ const ADGameDescription gameDescriptions[] = {
 
 	{
 		"first",
-		nullptr,
+		"1999",
 		AD_ENTRY2s("FIRST/ENGLISH/COMFY.OBJ",    "c187ac3fd5d547f59ff18b98a6a2f10b", 43008,
 				   "FIRST/ENGLISH/MIDIFILE.DAT", "4ab6c35308ed504a8abb96ae3fe81fe4", 1232),
 		Common::UNK_LANG,
@@ -83,6 +83,17 @@ const ADGameDescription gameDescriptions[] = {
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 	},
 
+	{
+		"first",
+		nullptr,
+		AD_ENTRY2s("FIRST/ENGLISH/COMFY.OBJ",    "fe23f262d2282f76488fbe401067a76c", 43008,
+				   "FIRST/ENGLISH/MIDIFILE.DAT", "4ab6c35308ed504a8abb96ae3fe81fe4", 1232),
+		Common::UNK_LANG,
+		Common::kPlatformWindows,
+		ADGF_UNSTABLE,
+		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+	},
+
 	{
 		"match",
 		nullptr,


Commit: 9331aa6f5345737e1b345f8ceac9c91b26bfab3d
    https://github.com/scummvm/scummvm/commit/9331aa6f5345737e1b345f8ceac9c91b26bfab3d
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Casts clean up

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/anim_file.cpp
    engines/comfy/comfy.cpp
    engines/comfy/expr.cpp
    engines/comfy/game.cpp
    engines/comfy/keybits.cpp
    engines/comfy/midi.cpp
    engines/comfy/midiplyr/midiplyr.cpp
    engines/comfy/palette.cpp
    engines/comfy/scene.cpp
    engines/comfy/script_vm.cpp
    engines/comfy/sound.cpp
    engines/comfy/timer.cpp
    engines/comfy/video.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index d9994a4741e..9d67b514d06 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -160,7 +160,7 @@ void ComfyEngine::objHdrReadFromXms(byte *destination, uint32 base, uint16 size,
 	if (!destination)
 		return;
 
-	uint32 offset = base + uint32(size) * row;
+	uint32 offset = base + (uint32)size * row;
 	if (offset > _headerXmsData.size() || size > _headerXmsData.size() - offset)
 		error("Headers move (XMS->memory)");
 
@@ -175,8 +175,8 @@ void ComfyEngine::objHdrRead(SpriteObjectHeader &destination, uint16 index) {
 	destination.dataSize = READ_LE_UINT16(raw + 0x04);
 	destination.width = READ_LE_UINT16(raw + 0x06);
 	destination.height = READ_LE_UINT16(raw + 0x08);
-	destination.hotspotX = int16(READ_LE_UINT16(raw + 0x0A));
-	destination.hotspotY = int16(READ_LE_UINT16(raw + 0x0C));
+	destination.hotspotX = (int16)READ_LE_UINT16(raw + 0x0A);
+	destination.hotspotY = (int16)READ_LE_UINT16(raw + 0x0C);
 	destination.reserved = raw[0x0E];
 	destination.tiledSize = READ_LE_UINT16(raw + 0x0F);
 	_spriteLastHeader = destination;
@@ -187,16 +187,16 @@ void ComfyEngine::scenePoolEvict() {
 		return;
 
 	byte *entry = &_scenePoolData[_scenePoolEvictCursor];
-	int16 id = int16(READ_LE_UINT16(entry));
+	int16 id = (int16)READ_LE_UINT16(entry);
 	uint16 slotSize = READ_LE_UINT16(entry + 2);
 	if (id > 0) {
-		if (uint16(id) < _spriteResources.size())
+		if ((uint16)id < _spriteResources.size())
 			spriteInvalidateHostCache(_spriteResources[id]);
 
-		if (uint16(id) < _objectCacheEntries.size())
+		if ((uint16)id < _objectCacheEntries.size())
 			_objectCacheEntries[id].slotSize = 0xFFFF;
 	} else {
-		uint16 frameId = uint16(-id);
+		uint16 frameId = (uint16)-id;
 		if (_frameSpriteResource.id == frameId)
 			spriteInvalidateHostCache(_frameSpriteResource);
 
@@ -241,20 +241,20 @@ void ComfyEngine::spriteCache(int16 spriteId) {
 	soundUnprepareHeader();
 
 	if (spriteId < 0) {
-		uint16 frameId = uint16(-spriteId);
-		uint32 fileOffset = uint32(frameId - 1) * COMFY_TILE_SIZE;
+		uint16 frameId = (uint16)-spriteId;
+		uint32 fileOffset = (uint32)(frameId - 1) * COMFY_TILE_SIZE;
 		if (fileOffset >= _picDataSize || fileOffset >= _comfyObjData.size())
 			return;
 
 		uint32 size = MIN<uint32>(COMFY_TILE_SIZE,
 			MIN<uint32>(_picDataSize - fileOffset, _comfyObjData.size() - fileOffset));
-		uint16 slotSize = uint16(size + (size & 1) + 0x0C);
-		scenePoolReserveSlot(uint32(slotSize) + 2);
+		uint16 slotSize = (uint16)(size + (size & 1) + 0x0C);
+		scenePoolReserveSlot((uint32)slotSize + 2);
 		if (_scenePoolCursor > _scenePoolData.size() || slotSize > _scenePoolData.size() - _scenePoolCursor)
 			return;
 
 		byte *entryData = &_scenePoolData[_scenePoolCursor];
-		WRITE_LE_UINT16(entryData, uint16(spriteId));
+		WRITE_LE_UINT16(entryData, (uint16)spriteId);
 		WRITE_LE_UINT16(entryData + 2, slotSize);
 		memcpy(entryData + 0x0C, &_comfyObjData[fileOffset], size);
 		_frameSpriteResource.id = frameId;
@@ -277,7 +277,7 @@ void ComfyEngine::spriteCache(int16 spriteId) {
 		return;
 	}
 
-	if (uint16(spriteId) >= _spriteResources.size())
+	if ((uint16)spriteId >= _spriteResources.size())
 		return;
 
 	SpriteResource &sprite = _spriteResources[spriteId];
@@ -303,17 +303,17 @@ void ComfyEngine::spriteCache(int16 spriteId) {
 
 	uint16 payloadSize = sprite.pixels.size() + (sprite.pixels.size() & 1);
 	uint16 slotSize = payloadSize + 0x0C;
-	scenePoolReserveSlot(uint32(slotSize) + 2);
+	scenePoolReserveSlot((uint32)slotSize + 2);
 	if (_scenePoolCursor > _scenePoolData.size() || slotSize > _scenePoolData.size() - _scenePoolCursor)
 		return;
 
 	byte *entryData = &_scenePoolData[_scenePoolCursor];
-	WRITE_LE_UINT16(entryData, uint16(spriteId));
+	WRITE_LE_UINT16(entryData, (uint16)spriteId);
 	WRITE_LE_UINT16(entryData + 2, slotSize);
 	WRITE_LE_UINT16(entryData + 4, header.width);
 	WRITE_LE_UINT16(entryData + 6, header.height);
-	WRITE_LE_UINT16(entryData + 8, uint16(header.hotspotX));
-	WRITE_LE_UINT16(entryData + 0x0A, uint16(header.hotspotY));
+	WRITE_LE_UINT16(entryData + 8, (uint16)header.hotspotX);
+	WRITE_LE_UINT16(entryData + 0x0A, (uint16)header.hotspotY);
 	memcpy(entryData + 0x0C, &sprite.pixels[0], sprite.pixels.size());
 	SpriteCacheEntry &entry = _objectCacheEntries[spriteId];
 	entry.poolOffset = _scenePoolCursor;
@@ -339,11 +339,11 @@ ComfyEngine::SpriteResource *ComfyEngine::spriteLookup(uint16 spriteId, int16 x,
 
 	int16 left = x - sprite.header.hotspotX;
 	int16 top = y - sprite.header.hotspotY;
-	int16 right = left + int16(sprite.header.width) - 1;
-	int16 bottom = top + int16(sprite.header.height) - 1;
+	int16 right = left + (int16)sprite.header.width - 1;
+	int16 bottom = top + (int16)sprite.header.height - 1;
 	bool fullscreen = sprite.header.width == _logicalScreenWidth && sprite.header.height == _logicalScreenHeight;
-	bool offscreen = left > int16(_logicalScreenWidth - 1) || right < 0 ||
-		top > int16(_logicalScreenHeight - 1) || bottom < 0;
+	bool offscreen = left > (int16)(_logicalScreenWidth - 1) || right < 0 ||
+		top > (int16)(_logicalScreenHeight - 1) || bottom < 0;
 
 	if (entry && entry->slotSize == 0xFFFF && !fullscreen && offscreen) {
 		_objFileOffset = _spriteLastHeader.fileOffset;
@@ -352,14 +352,14 @@ ComfyEngine::SpriteResource *ComfyEngine::spriteLookup(uint16 spriteId, int16 x,
 	}
 
 	if ((entry && entry->slotSize == 0xFFFF) || (!entry && !sprite.loaded))
-		spriteCache(int16(spriteId));
+		spriteCache((int16)spriteId);
 
 	return &sprite;
 }
 
 ComfyEngine::SpriteResource *ComfyEngine::spriteGetPtr(int16 spriteId) {
 	if (spriteId > 0) {
-		if (uint16(spriteId) >= _spriteResources.size())
+		if ((uint16)spriteId >= _spriteResources.size())
 			return nullptr;
 
 		if (_objectCacheEntries[spriteId].slotSize == 0xFFFF)
@@ -371,7 +371,7 @@ ComfyEngine::SpriteResource *ComfyEngine::spriteGetPtr(int16 spriteId) {
 	if (!spriteId)
 		return nullptr;
 
-	uint16 frameId = uint16(-spriteId);
+	uint16 frameId = (uint16)-spriteId;
 	if (frameId >= _frameCacheEntries.size() || _frameCacheEntries[frameId].slotSize == 0xFFFF ||
 			!_frameSpriteResource.loaded || _frameSpriteResource.id != frameId)
 		spriteCache(spriteId);
@@ -440,7 +440,7 @@ void ComfyEngine::spriteBlitClipped(int16 spriteId, int16 x, int16 y) {
 
 				byte value = sprite.pixels[packetPos++];
 				for (uint i = 0; i < count; i++, drawX++) {
-					if (drawX >= 0 && drawX < int16(_logicalScreenWidth) && drawY >= 0 && drawY < int16(_logicalScreenHeight))
+					if (drawX >= 0 && drawX < (int16)_logicalScreenWidth && drawY >= 0 && drawY < (int16)_logicalScreenHeight)
 						_framebufPtr[drawY * _logicalScreenWidth + drawX] = value;
 				}
 			} else if (op & 0x40) {
@@ -451,7 +451,7 @@ void ComfyEngine::spriteBlitClipped(int16 spriteId, int16 x, int16 y) {
 
 				for (uint i = 0; i < count; i++, drawX++) {
 					byte value = sprite.pixels[packetPos++];
-					if (drawX >= 0 && drawX < int16(_logicalScreenWidth) && drawY >= 0 && drawY < int16(_logicalScreenHeight))
+					if (drawX >= 0 && drawX < (int16)_logicalScreenWidth && drawY >= 0 && drawY < (int16)_logicalScreenHeight)
 						_framebufPtr[drawY * _logicalScreenWidth + drawX] = value;
 				}
 			}
@@ -510,12 +510,12 @@ ComfyEngine::Actor *ComfyEngine::rootActor() {
 void ComfyEngine::actorSetFrame(int16 frame) {
 	Actor *root = rootActor();
 	if (root)
-		actorWriteU32(*root, kActorSpriteSelector, uint32(int32(frame)));
+		actorWriteU32(*root, kActorSpriteSelector, (uint32)(int32)frame);
 }
 
 uint16 ComfyEngine::actorGetFrame() {
 	Actor *root = rootActor();
-	return root ? uint16(actorReadU32(*root, kActorSpriteSelector)) : 0;
+	return root ? (uint16)actorReadU32(*root, kActorSpriteSelector) : 0;
 }
 
 ComfyEngine::Actor *ComfyEngine::actorResolve(uint16 sceneOrActor, uint16 fallbackActor) {
@@ -626,9 +626,9 @@ uint16 ComfyEngine::actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible,
 	actorWriteU32(*actor, kActorCurrentPc, pc);
 	actorWriteU32(*actor, kActorCallPc, 0);
 	actorWriteU32(*actor, kActorResetPc, pc);
-	actorWriteU32(*actor, kActorXFixed, uint32(int32(x) * 0x1000));
-	actorWriteU32(*actor, kActorYFixed, uint32(int32(y) * 0x1000));
-	actorWriteU32(*actor, kActorSpriteSelector, uint32(int32(sprite)));
+	actorWriteU32(*actor, kActorXFixed, (uint32)((int32)x * 0x1000));
+	actorWriteU32(*actor, kActorYFixed, (uint32)((int32)y * 0x1000));
+	actorWriteU32(*actor, kActorSpriteSelector, (uint32)(int32)sprite);
 	actorWriteU16(*actor, kActorChildTail, 0);
 	actorWriteU16(*actor, kActorChildHead, 0);
 	actorWriteU16(*actor, kActorSiblingHead, 0);
@@ -672,7 +672,7 @@ void ComfyEngine::actorSetPc(Actor &actor, uint32 pc) {
 			WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneActorPcOffset + entry * 4], _actorPcTable[entry]);
 		}
 
-		packed = (uint32(entry) << 24) + pc;
+		packed = ((uint32)entry << 24) + pc;
 	}
 
 	actorWriteU32(actor, kActorCallPc, packed);
@@ -684,7 +684,7 @@ uint32 ComfyEngine::actorPopPc(Actor &actor) {
 	if (entry) {
 		actorWriteU32(actor, kActorCallPc, _actorPcTable[entry]);
 		_actorPcTable[entry] = _actorPcTable[0];
-		_actorPcTable[0] = uint32(entry) << 24;
+		_actorPcTable[0] = (uint32)entry << 24;
 		if (_sceneActorPcOffset + sizeof(_actorPcTable) <= _sceneMemoryBlock.size()) {
 			WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneActorPcOffset], _actorPcTable[0]);
 			WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneActorPcOffset + entry * 4], _actorPcTable[entry]);
@@ -703,7 +703,7 @@ void ComfyEngine::actorFreePcChain(Actor &actor) {
 		byte next = _actorPcTable[entry] >> 24;
 		if (!next) {
 			_actorPcTable[entry] = _actorPcTable[0];
-			_actorPcTable[0] = uint32(first) << 24;
+			_actorPcTable[0] = (uint32)first << 24;
 			if (_sceneActorPcOffset + sizeof(_actorPcTable) <= _sceneMemoryBlock.size())
 				memcpy(&_sceneMemoryBlock[_sceneActorPcOffset], _actorPcTable, sizeof(_actorPcTable));
 
@@ -825,7 +825,7 @@ bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
 
 	int16 moveTicks = actorReadU16(*actor, kActorMoveTicks);
 	if (moveTicks) {
-		int16 stepTicks = int16(uint16(_timerCurrent + _timer0 + _timer1 + _timer2 + 2)) / 4;
+		int16 stepTicks = (int16)(uint16)(_timerCurrent + _timer0 + _timer1 + _timer2 + 2) / 4;
 		if (stepTicks > 20)
 			stepTicks = 20;
 
@@ -836,8 +836,8 @@ bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
 
 		int32 moveDx = actorReadU32(*actor, kActorMoveDx);
 		int32 moveDy = actorReadU32(*actor, kActorMoveDy);
-		int32 stepDx = (int32(stepTicks) * moveDx) / moveTicks;
-		int32 stepDy = (int32(stepTicks) * moveDy) / moveTicks;
+		int32 stepDx = ((int32)stepTicks * moveDx) / moveTicks;
+		int32 stepDy = ((int32)stepTicks * moveDy) / moveTicks;
 		actorWriteU32(*actor, kActorXFixed, actorReadU32(*actor, kActorXFixed) + stepDx);
 		actorWriteU32(*actor, kActorYFixed, actorReadU32(*actor, kActorYFixed) + stepDy);
 		actorWriteU32(*actor, kActorMoveDx, moveDx - stepDx);
@@ -952,10 +952,10 @@ uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &m
 		maskRecord.right = 0;
 		maskRecord.bottom = 0;
 	} else {
-		_keymaskBits = uint16(maskRecord.right) | (uint32(uint16(maskRecord.bottom)) << 16);
+		_keymaskBits = (uint16)maskRecord.right | ((uint32)(uint16)maskRecord.bottom << 16);
 	}
 
-	int16 wordsLeft = int16(scriptReadWord(pc) - 1);
+	int16 wordsLeft = (int16)(scriptReadWord(pc) - 1);
 	pc += 2;
 	uint16 bitIndex = 0xFFFF;
 	_keymaskCount = wordsLeft;
@@ -974,14 +974,14 @@ uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &m
 		if (spriteId & 0x8000) {
 			wordsLeft -= 2;
 			_keymaskCount = wordsLeft;
-			uint32 mask = uint32(1) << (bitIndex & 31);
+			uint32 mask = (uint32)1 << (bitIndex & 31);
 			if (mode == 1) {
 				uint16 key = scriptReadWord(pc);
 				_keymaskResult = keyBitTest(key) ? 1 : 0;
 				if (_keymaskResult) {
 					_keymaskBits |= mask;
-					maskRecord.right = uint16(_keymaskBits);
-					maskRecord.bottom = uint16(_keymaskBits >> 16);
+					maskRecord.right = (uint16)_keymaskBits;
+					maskRecord.bottom = (uint16)(_keymaskBits >> 16);
 				}
 
 				pc += 2;
@@ -1014,20 +1014,20 @@ uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &m
 		if (!spriteId)
 			continue;
 
-		_keymaskX = baseX + int16(dx);
-		_keymaskY = baseY + int16(dy);
-		if (_keymaskX >= 0x0280 || _keymaskX <= int16(0xFEC0) ||
-				_keymaskY >= 0x0190 || _keymaskY <= int16(0xFF38))
+		_keymaskX = baseX + (int16)dx;
+		_keymaskY = baseY + (int16)dy;
+		if (_keymaskX >= 0x0280 || _keymaskX <= (int16)0xFEC0 ||
+				_keymaskY >= 0x0190 || _keymaskY <= (int16)0xFF38)
 			continue;
 
-		SpriteResource *sprite = spriteGetPtr(int16(spriteId));
+		SpriteResource *sprite = spriteGetPtr((int16)spriteId);
 		if (!sprite)
 			continue;
 
 		int16 left = _keymaskX - sprite->header.hotspotX;
 		int16 top = _keymaskY - sprite->header.hotspotY;
 		if (mode == 1)
-			spriteBlitClipped(int16(spriteId), left, top);
+			spriteBlitClipped((int16)spriteId, left, top);
 
 		if (rect) {
 			rect->left = left;
@@ -1105,8 +1105,8 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 	if (!animFrameShouldDraw(1))
 		return false;
 
-	int16 drawX = int16(int32(actorReadU32(*actor, kActorXFixed)) >> 12) + x;
-	int16 drawY = int16(int32(actorReadU32(*actor, kActorYFixed)) >> 12) + y;
+	int16 drawX = (int16)((int32)actorReadU32(*actor, kActorXFixed) >> 12) + x;
+	int16 drawY = (int16)((int32)actorReadU32(*actor, kActorYFixed) >> 12) + y;
 	byte oldVisible = actorReadU8(*actor, kActorCachedVisible);
 	uint32 oldSelector = actorReadU32(*actor, kActorCachedSprite);
 	VideoRectRecord oldRect = actorReadCachedRect(*actor);
@@ -1138,7 +1138,7 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 			if (scriptedLastRect != 0xFFFF && scriptedLastRect >= COMFY_RESOLUTION_CHANGE_CAPACITY)
 				scriptedLastRect = COMFY_RESOLUTION_CHANGE_CAPACITY - 1;
 		} else {
-			int16 wordsLeft = int16(scriptReadWord(pc) - 1);
+			int16 wordsLeft = (int16)(scriptReadWord(pc) - 1);
 			pc += 2;
 			while (wordsLeft > 0 && !_scriptFault) {
 				uint16 spriteId = scriptReadWord(pc);
@@ -1159,9 +1159,9 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 				}
 
 				if (spriteId) {
-					SpriteResource *sprite = spriteGetPtr(int16(spriteId));
+					SpriteResource *sprite = spriteGetPtr((int16)spriteId);
 					if (sprite)
-						spriteBlitClipped(int16(spriteId), drawX + dx - sprite->header.hotspotX,
+						spriteBlitClipped((int16)spriteId, drawX + dx - sprite->header.hotspotX,
 							drawY + dy - sprite->header.hotspotY);
 				}
 			}
@@ -1181,14 +1181,14 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 		newRect.area = frameWidth * frameHeight;
 		animFrameBlitAt(drawX, drawY);
 	} else if (selector) {
-		SpriteResource *sprite = spriteLookup(uint16(selector), drawX, drawY);
+		SpriteResource *sprite = spriteLookup((uint16)selector, drawX, drawY);
 		if (sprite) {
 			newRect.left = drawX - sprite->header.hotspotX;
 			newRect.top = drawY - sprite->header.hotspotY;
 			newRect.right = newRect.left + sprite->header.width;
 			newRect.bottom = newRect.top + sprite->header.height;
 			newRect.area = sprite->header.width * sprite->header.height;
-			spriteBlitClipped(int16(selector), drawX - sprite->header.hotspotX, drawY - sprite->header.hotspotY);
+			spriteBlitClipped((int16)selector, drawX - sprite->header.hotspotX, drawY - sprite->header.hotspotY);
 		}
 	}
 	animFrameRecordVocCounter(2);
diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
index ac3b325ac9b..3138bc9f689 100644
--- a/engines/comfy/anim_file.cpp
+++ b/engines/comfy/anim_file.cpp
@@ -81,7 +81,7 @@ bool ComfyEngine::animFileOpen() {
 		return false;
 
 	uint16 count = READ_LE_UINT16(&_animFileData[2]);
-	if (uint32(COMFY_ANMFILE_HEADER_BYTES) + uint32(count) * 4 > _animFileData.size())
+	if ((uint32)COMFY_ANMFILE_HEADER_BYTES + (uint32)count * 4 > _animFileData.size())
 		return false;
 
 	_animIndexTable.resize(count);
@@ -135,12 +135,12 @@ void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 ac
 
 	uint32 offset = _animIndexTable[animIndex];
 	if (offset > _animFileData.size() || COMFY_ANMFILE_HEADER_BYTES > _animFileData.size() - offset)
-		error("ANMFILE.DAT is truncated while loading animation %u", uint(animIndex));
+		error("ANMFILE.DAT is truncated while loading animation %u", (uint)animIndex);
 
 	memcpy(_animFrameHeader, &_animFileData[offset], sizeof(_animFrameHeader));
 	uint16 magic = READ_LE_UINT16(_animFrameHeader);
 	if (magic != COMFY_ANMFRAME_MAGIC && magic != COMFY_ANMFRAME_PANTHER_MAGIC)
-		error("Invalid frame header in ANMFILE.DAT for animation %u", uint(animIndex));
+		error("Invalid frame header in ANMFILE.DAT for animation %u", (uint)animIndex);
 
 	_animFrameBuffer.resize(COMFY_ANMFRAME_BYTES);
 	memset(&_animFrameBuffer[0], 0xFF, _animFrameBuffer.size());
@@ -199,7 +199,7 @@ uint32 ComfyEngine::animDecompressRle(const byte *source, uint32 sourceSize, byt
 			if (word == 0)
 				return destinationPosition;
 
-			if (int16(word) > 0) {
+			if ((int16)word > 0) {
 				destinationPosition = MIN<uint32>(destinationPosition + word, destinationSize);
 				continue;
 			}
@@ -258,7 +258,7 @@ uint32 ComfyEngine::animDecodePanther(const byte *source, uint32 sourceSize) {
 			uint16 runCount = READ_LE_UINT16(source + sourcePosition);
 			sourcePosition += 2;
 			if (runCount & 0x4000) {
-				destinationPosition += uint32(uint16(0 - runCount)) * COMFY_SCREEN_WIDTH;
+				destinationPosition += (uint32)(uint16)(0 - runCount) * COMFY_SCREEN_WIDTH;
 				continue;
 			}
 
@@ -383,7 +383,7 @@ void ComfyEngine::animFileTickCommands() {
 		} else if (command == kAnimCommandStoreFrameBytes) {
 			uint32 oldSize = _animFrameStorage.size();
 			uint32 frameStart = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
-			animFilePushStorageChunk(uint32(payload - &_animFileData[frameStart]), oldSize, uint16(payloadSize));
+			animFilePushStorageChunk((uint32)(payload - &_animFileData[frameStart]), oldSize, (uint16)payloadSize);
 			_animFrameStorage.resize(oldSize + payloadSize);
 			if (payloadSize)
 				memcpy(&_animFrameStorage[oldSize], payload, payloadSize);
@@ -426,24 +426,24 @@ int16 ComfyEngine::animFrameVocCounterDelta() {
 	if (_animVocClockHz == 0)
 		error("Invalid VOC clock frequency in ANMFILE.DAT");
 
-	int32 expected = (int32(int16(_animVocTargetCounter)) * 100) / int16(_animVocClockHz);
-	return int16(uint16(counter) - uint16(expected));
+	int32 expected = ((int32)(int16)_animVocTargetCounter * 100) / (int16)_animVocClockHz;
+	return (int16)((uint16)counter - (uint16)expected);
 }
 
 bool ComfyEngine::animFrameShouldDraw(uint16 phase) {
 	if (!animFrameIsPending())
 		return true;
 
-	int16 baseStep = 100 / int16(_animVocClockHz);
+	int16 baseStep = 100 / (int16)_animVocClockHz;
 	int16 threshold = phase == 1 ? baseStep / 2 : baseStep;
 	int16 delta = animFrameVocCounterDelta();
-	int16 adjustedDelta = int16((phase == 1 ? int16(delta + _animVocDeltaA) : delta) + _animVocDeltaB);
+	int16 adjustedDelta = (int16)((phase == 1 ? (int16)(delta + _animVocDeltaA) : delta) + _animVocDeltaB);
 	bool shouldDraw = adjustedDelta <= threshold;
 	if (!shouldDraw) {
-		if (int16(_animVocDeltaA) > 0)
+		if ((int16)_animVocDeltaA > 0)
 			_animVocDeltaA--;
 
-		if (int16(_animVocDeltaB) > 0)
+		if ((int16)_animVocDeltaB > 0)
 			_animVocDeltaB--;
 	}
 
@@ -459,12 +459,12 @@ void ComfyEngine::animFrameRecordVocCounter(uint16 phase) {
 		_animVocCounterStartA = counter;
 	} else if (phase == 2) {
 		_animVocCounterEndA = counter;
-		_animVocDeltaA = uint16(_animVocCounterEndA - _animVocCounterStartA);
+		_animVocDeltaA = (uint16)(_animVocCounterEndA - _animVocCounterStartA);
 	} else if (phase == 3) {
 		_animVocCounterStartB = counter;
 	} else if (phase == 4) {
 		_animVocCounterEndB = counter;
-		_animVocDeltaB = uint16(_animVocCounterEndB - _animVocCounterStartB);
+		_animVocDeltaB = (uint16)(_animVocCounterEndB - _animVocCounterStartB);
 	}
 }
 
@@ -472,7 +472,7 @@ void ComfyEngine::animFrameWaitForVocCounter() {
 	if (!animFrameIsPending())
 		return;
 
-	while (animFrameVocCounterDelta() < -int16(_animVocDeltaB + 3)) {
+	while (animFrameVocCounterDelta() < -(int16)(_animVocDeltaB + 3)) {
 		processEvents();
 		if (shouldQuit())
 			break;
@@ -511,8 +511,8 @@ bool ComfyEngine::animFrameBlitAt(int16 x, int16 y) {
 			continue;
 
 		for (int16 row = clippedTop; row < clippedBottom; row++) {
-			uint32 sourceOffset = uint32(row - y) * COMFY_SCREEN_WIDTH + clippedLeft - x;
-			uint32 destinationOffset = uint32(row) * _logicalScreenWidth + clippedLeft;
+			uint32 sourceOffset = (uint32)(row - y) * COMFY_SCREEN_WIDTH + clippedLeft - x;
+			uint32 destinationOffset = (uint32)row * _logicalScreenWidth + clippedLeft;
 			uint32 width = clippedRight - clippedLeft;
 			if (sourceOffset >= _animFrameBuffer.size())
 				break;
@@ -630,7 +630,7 @@ void ComfyEngine::animFileRebuildStorage(uint32 targetSize) {
 			uint32 copySize = MIN<uint32>(payloadSize, targetSize - _animFrameStorage.size());
 			uint32 oldSize = _animFrameStorage.size();
 			uint32 frameStart = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
-			animFilePushStorageChunk(uint32(payload - &_animFileData[frameStart]), oldSize, uint16(copySize));
+			animFilePushStorageChunk((uint32)(payload - &_animFileData[frameStart]), oldSize, (uint16)copySize);
 			_animFrameStorage.resize(oldSize + copySize);
 			if (copySize)
 				memcpy(&_animFrameStorage[oldSize], payload, copySize);
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 1e51e3ebeb9..2ababe03531 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -229,7 +229,7 @@ uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
 		if (sceneGetActiveCount() > 1 && _midiHandles.size() > 1)
 			nextScene = midiGetHandle(1);
 
-		if (int16(nextScene) > 0 && int16(nextScene) < 0x65 && nextScene != sceneId)
+		if ((int16)nextScene > 0 && (int16)nextScene < 0x65 && nextScene != sceneId)
 			shouldStartNext = 1;
 
 		if (_engineVersion == kEngineVersion3)
@@ -294,8 +294,8 @@ void ComfyEngine::processEvents() {
 			break;
 		case Common::EVENT_MOUSEMOVE:
 			if (_engineVersion == kEngineVersion3) {
-				_mouseX = CLIP<int16>(int32(event.mouse.x) * 320 / _logicalScreenWidth, 0, 319);
-				_mouseY = CLIP<int16>(int32(event.mouse.y) * 200 / _logicalScreenHeight, 0, 199);
+				_mouseX = CLIP<int16>((int32)event.mouse.x * 320 / _logicalScreenWidth, 0, 319);
+				_mouseY = CLIP<int16>((int32)event.mouse.y * 200 / _logicalScreenHeight, 0, 199);
 			}
 			break;
 		case Common::EVENT_LBUTTONDOWN:
@@ -369,9 +369,9 @@ void ComfyEngine::mouseUpdateCursor() {
 		return;
 	}
 
-	_mouseCursorSprite = spriteGetPtr(int16(selector));
+	_mouseCursorSprite = spriteGetPtr((int16)selector);
 	if (_mouseCursorSprite)
-		_mouseCursorSpriteId = uint16(_mouseCursorSprite->id);
+		_mouseCursorSpriteId = (uint16)_mouseCursorSprite->id;
 
 	if (!actorReadU8(*_mouseActor, kActorVisible) && !(_mouseFlags & 8))
 		_mouseFlags |= 8;
@@ -424,7 +424,7 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 
 		uint16 frame = actorGetFrame();
 		if (frame) {
-			SpriteResource *background = spriteGetPtr(int16(frame));
+			SpriteResource *background = spriteGetPtr((int16)frame);
 			if (background && background->header.width == _logicalScreenWidth &&
 					background->header.height == _logicalScreenHeight && !background->pixels.empty()) {
 				spriteBlitRle(&background->pixels[0], background->pixels.size());
@@ -470,7 +470,7 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 			if (vocQueueIsIdle() || _musicEnabled) {
 				uint16 track = 1;
 				for (;;) {
-					_musicEventMask = uint16(int16(_musicEventMask) >> 1);
+					_musicEventMask = (uint16)((int16)_musicEventMask >> 1);
 					if (!_musicEventMask)
 						break;
 
@@ -625,7 +625,7 @@ void ComfyEngine::midiPollChannels(uint16 ticks) {
 
 		int16 volume = midiApproachTarget(state.volumeCurrent, state.volumeTarget, state.volumeTicksLeft, ticks);
 		if ((state.volumeCurrent & 0x7F00) != (volume & 0x7F00))
-			_midiPlyrDriver->musicSetVolume(uint16(volume >> 8), channel);
+			_midiPlyrDriver->musicSetVolume((uint16)(volume >> 8), channel);
 
 		state.volumeCurrent = volume;
 		int16 pitch = midiApproachTarget(state.pitchCurrent, state.pitchTarget, state.pitchTicksLeft, ticks);
diff --git a/engines/comfy/expr.cpp b/engines/comfy/expr.cpp
index 6571ec9b5c8..be9988d487b 100644
--- a/engines/comfy/expr.cpp
+++ b/engines/comfy/expr.cpp
@@ -75,7 +75,7 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 					position += actorReadU32(*actor, offset);
 				}
 
-				value = uint16(position >> 12);
+				value = (uint16)(position >> 12);
 			} else if (opcode == 0x14)
 				value = actorReadU16(*actor, kActorSpriteSelector);
 
@@ -88,7 +88,7 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 		if (opcode == 0x16) {
 			if (_exprStackTop) {
 				int16 maximum = _exprStack[_exprStackTop - 1];
-				_exprStack[_exprStackTop - 1] = uint16((int32(getRandomNumber(0x7FFF)) * maximum) / 0x8000);
+				_exprStack[_exprStackTop - 1] = (uint16)(((int32)getRandomNumber(0x7FFF) * maximum) / 0x8000);
 			}
 
 			continue;
@@ -158,18 +158,18 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 		int16 rhs = _exprStack[--_exprStackTop];
 		int16 lhs = _exprStack[_exprStackTop - 1];
 		if (opcode == 0x08)
-			_exprStack[_exprStackTop - 1] = uint16(lhs + rhs);
+			_exprStack[_exprStackTop - 1] = (uint16)(lhs + rhs);
 		else if (opcode == 0x09)
-			_exprStack[_exprStackTop - 1] = uint16(lhs - rhs);
+			_exprStack[_exprStackTop - 1] = (uint16)(lhs - rhs);
 		else if (opcode == 0x0A)
-			_exprStack[_exprStackTop - 1] = uint16(lhs * rhs);
+			_exprStack[_exprStackTop - 1] = (uint16)(lhs * rhs);
 		else if ((opcode == 0x0B || opcode == 0x0E) && !rhs) {
 			_scriptFault = true;
 			return 0;
 		} else if (opcode == 0x0B)
-			_exprStack[_exprStackTop - 1] = uint16(lhs / rhs);
+			_exprStack[_exprStackTop - 1] = (uint16)(lhs / rhs);
 		else if (opcode == 0x0E)
-			_exprStack[_exprStackTop - 1] = uint16(lhs % rhs);
+			_exprStack[_exprStackTop - 1] = (uint16)(lhs % rhs);
 	}
 }
 
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index 72cc61bb764..32f81a58cd6 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -230,7 +230,7 @@ Common::SeekableReadStream *ComfyEngine::pathFOpen(const Common::Path &filename,
 
 bool ComfyEngine::readAssetFile(const Common::Path &filename, Common::Array<byte> &data) {
 	Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(filename, true));
-	if (!stream || stream->size() < 0 || uint64(stream->size()) > UINT32_MAX)
+	if (!stream || stream->size() < 0 || (uint64)stream->size() > UINT32_MAX)
 		return false;
 
 	uint32 size = stream->size();
@@ -263,7 +263,7 @@ bool ComfyEngine::picFileOpen() {
 		return false;
 
 	uint16 count = assetsReadLe16At(_picFileData, 0);
-	uint32 tableSize = 2 + uint32(count) * 0x11;
+	uint32 tableSize = 2 + (uint32)count * 0x11;
 	if (tableSize > _picFileData.size())
 		return false;
 
@@ -322,7 +322,7 @@ void ComfyEngine::midiFileReadEntries(byte *destination) {
 	if (!destination || _midiFileData.size() <= 4)
 		return;
 
-	uint32 size = uint32(_midiEntryCount) * 6;
+	uint32 size = (uint32)_midiEntryCount * 6;
 	memcpy(destination, &_midiFileData[4], MIN<uint32>(size, _midiFileData.size() - 4));
 }
 
@@ -374,7 +374,7 @@ bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16
 
 	memset(_actorPcTable, 0, sizeof(_actorPcTable));
 	for (uint i = 0; i < 0xC7 && i < ARRAYSIZE(_actorPcTable); i++)
-		_actorPcTable[i] = uint32(i + 1) << 24;
+		_actorPcTable[i] = (uint32)(i + 1) << 24;
 
 	if (0xC7 < ARRAYSIZE(_actorPcTable))
 		_actorPcTable[0xC7] = 0;
@@ -382,7 +382,7 @@ bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16
 	uint32 stringBytes = _stringTable.size() * sizeof(uint16);
 	uint32 handleBytes = _sceneHandles.size() * sizeof(uint16);
 	uint32 actorBytes = _actors.size() * (_engineVersion == kEngineVersion3 ? COMFY_ACTOR_SIZE_V3 : COMFY_ACTOR_SIZE);
-	uint32 keyBytes = (uint32(keyBitCount) + 1) / 8 + 1;
+	uint32 keyBytes = ((uint32)keyBitCount + 1) / 8 + 1;
 	_sceneMidiInstanceOffset = 0;
 	if (_engineVersion == kEngineVersion3) {
 		_sceneEntryListOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES + COMFY_SCENE_VOC_STATE_BYTES_V3 +
@@ -458,15 +458,15 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 		memset(&_environmentData[0], 0, environmentBytes);
 	_xmsEnvAllocated = !_environmentData.empty();
 
-	uint32 midiHeaderBytes = assetsAlignEven32(uint32(_midiEntryCount) * 6);
+	uint32 midiHeaderBytes = assetsAlignEven32((uint32)_midiEntryCount * 6);
 	uint16 soundEntryCount = 0;
 	uint16 soundEntrySize = 0;
 	soundGetTileParams(&soundEntryCount, &soundEntrySize);
-	uint32 soundHeaderBytes = assetsAlignEven32(uint32(soundEntryCount) * soundEntrySize);
-	uint32 objectTableBytes = assetsAlignEven32(uint32(_numObjects) * 0x11);
+	uint32 soundHeaderBytes = assetsAlignEven32((uint32)soundEntryCount * soundEntrySize);
+	uint32 objectTableBytes = assetsAlignEven32((uint32)_numObjects * 0x11);
 	uint32 headerTotalBytes = midiHeaderBytes + soundHeaderBytes + objectTableBytes;
 	uint16 headerPages = (headerTotalBytes + 0x400) / 0x400;
-	_headerXmsData.resize(uint32(headerPages) * 0x400);
+	_headerXmsData.resize((uint32)headerPages * 0x400);
 	if (!_headerXmsData.empty())
 		memset(&_headerXmsData[0], 0, _headerXmsData.size());
 
@@ -550,7 +550,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	_sceneEntryCount = 0;
 	_sceneEntryFrameSize = 0;
 	Common::ScopedPtr<Common::SeekableReadStream> message(pathFOpen(Common::Path("MESSAGE"), true));
-	_usesWcomfy99ScriptOps = bool(message);
+	_usesWcomfy99ScriptOps = (bool)message;
 	_scriptFault = false;
 
 	return true;
diff --git a/engines/comfy/keybits.cpp b/engines/comfy/keybits.cpp
index 3b3ef38c078..5d5078ab2c3 100644
--- a/engines/comfy/keybits.cpp
+++ b/engines/comfy/keybits.cpp
@@ -28,7 +28,7 @@ namespace Comfy {
 bool ComfyEngine::keyBitAllocate(uint16 keyBitCount) {
 	keyBitFree();
 
-	_keyBitsSize = uint16(keyBitCount + 1) / 8 + 1;
+	_keyBitsSize = (uint16)(keyBitCount + 1) / 8 + 1;
 	_keyBits = new byte[_keyBitsSize]();
 	return true;
 }
diff --git a/engines/comfy/midi.cpp b/engines/comfy/midi.cpp
index 4983e9202fc..4d7ee05745f 100644
--- a/engines/comfy/midi.cpp
+++ b/engines/comfy/midi.cpp
@@ -58,8 +58,8 @@ uint16 ComfyEngine::midiTick() {
 	if (_engineVersion == kEngineVersion3) {
 		int16 adjustment = midiGetCounterAdjustment();
 		if (adjustment) {
-			_midiPlyrDriver->setVocCounter(uint32(int32(_midiPlyrDriver->getVocCounter()) + adjustment));
-			_midiPlyrDriver->setTimeCounter(uint32(int32(_midiPlyrDriver->getTimeCounter()) + adjustment));
+			_midiPlyrDriver->setVocCounter((uint32)((int32)_midiPlyrDriver->getVocCounter() + adjustment));
+			_midiPlyrDriver->setTimeCounter((uint32)((int32)_midiPlyrDriver->getTimeCounter() + adjustment));
 		}
 	}
 
@@ -77,37 +77,37 @@ uint16 ComfyEngine::midiTick() {
 		(_engineVersion != kEngineVersion3 && _midiTimeCounter == previousCounter));
 
 	_midiInstanceEventTime = _midiTimeCounter;
-	_midiEventBaseTime = int32(_midiInstanceEventTime);
+	_midiEventBaseTime = (int32)_midiInstanceEventTime;
 	_midiEvents.baseTime = _midiEventBaseTime;
 
-	int16 delta = int16(uint16(_midiInstanceEventTime - previousCounter));
+	int16 delta = (int16)(uint16)(_midiInstanceEventTime - previousCounter);
 	if (delta < 1)
 		delta = 1;
 
 	if (_midiTimeScale != 0x400) {
-		_midiTimeDelta = int16((int32(delta) * _midiTimeScale) >> 10);
+		_midiTimeDelta = (int16)(((int32)delta * _midiTimeScale) >> 10);
 		if (!_midiTimeDelta)
 			_midiTimeDelta = 1;
 
 		if (_midiTimeDelta != delta) {
-			_midiTimeCounter = uint32(int32(_midiTimeCounter) + _midiTimeDelta - delta);
+			_midiTimeCounter = (uint32)((int32)_midiTimeCounter + _midiTimeDelta - delta);
 			_midiPlyrDriver->setTimeCounter(_midiTimeCounter);
 
-			_midiInstanceEventTime = uint32(int32(_midiInstanceEventTime) + _midiTimeDelta - delta);
-			_midiEventBaseTime = int32(_midiInstanceEventTime);
+			_midiInstanceEventTime = (uint32)((int32)_midiInstanceEventTime + _midiTimeDelta - delta);
+			_midiEventBaseTime = (int32)_midiInstanceEventTime;
 			_midiEvents.baseTime = _midiEventBaseTime;
 			delta = _midiTimeDelta;
 		}
 	}
 
-	while (_midiEvents.nextIndex != 0x03E7 && int32(_midiInstanceEventTime) >= _midiEvents.nextTime) {
+	while (_midiEvents.nextIndex != 0x03E7 && (int32)_midiInstanceEventTime >= _midiEvents.nextTime) {
 		keyBitSet(_midiEvents.entries[_midiEvents.nextIndex].id);
 		_midiEvents.count--;
 		_midiEvents.entries[_midiEvents.nextIndex] = _midiEvents.entries[_midiEvents.count];
 		midiFindNext(_midiEvents);
 	}
 
-	return uint16(delta);
+	return (uint16)delta;
 }
 
 bool ComfyEngine::midiPlyrStart() {
@@ -171,7 +171,7 @@ void ComfyEngine::midiSetTimeScale(int16 delta) {
 		return;
 	}
 
-	_midiTimeScale = (int32(delta) * _midiTimeScale) >> 10;
+	_midiTimeScale = ((int32)delta * _midiTimeScale) >> 10;
 	if (_midiTimeScale < 100)
 		_midiTimeScale = 100;
 
@@ -479,7 +479,7 @@ void ComfyEngine::midiSetChannelParam(uint16 channel, byte parameter, uint16 val
 		state.pitchTarget = value;
 		state.pitchTicksLeft = ticks;
 	} else if (parameter == 4) {
-		state.volumeTarget = int16(value << 8);
+		state.volumeTarget = (int16)(value << 8);
 		state.volumeTicksLeft = ticks;
 	}
 
@@ -492,7 +492,7 @@ void ComfyEngine::midiSetChannelParam(uint16 channel, byte parameter, uint16 val
 			_midiPlyrDriver->musicSetPitch(state.pitchCurrent, channel);
 		} else if (parameter == 4) {
 			state.volumeCurrent = state.volumeTarget;
-			_midiPlyrDriver->musicSetVolume(uint16(state.volumeCurrent >> 8), channel);
+			_midiPlyrDriver->musicSetVolume((uint16)(state.volumeCurrent >> 8), channel);
 		}
 	}
 }
@@ -507,7 +507,7 @@ int16 ComfyEngine::midiApproachTarget(int16 current, int16 target, int16 &ticksL
 	}
 
 	ticksLeft -= ticks;
-	return int16((int32(current) * ticksLeft + int32(target) * ticks) / (ticksLeft + ticks));
+	return (int16)(((int32)current * ticksLeft + (int32)target * ticks) / (ticksLeft + ticks));
 }
 
 void ComfyEngine::musicSetEnabled(byte value) {
diff --git a/engines/comfy/midiplyr/midiplyr.cpp b/engines/comfy/midiplyr/midiplyr.cpp
index e897d90d643..9dc0feccba6 100644
--- a/engines/comfy/midiplyr/midiplyr.cpp
+++ b/engines/comfy/midiplyr/midiplyr.cpp
@@ -515,9 +515,9 @@ void MidiPlyrDriver::musicSetVolume(uint16 volume, uint16 trackIndex) {
 		return;
 
 	if (_midiFileFormat != 1)
-		volume = (int16(volume) * 0x55) / 100;
+		volume = ((int16)volume * 0x55) / 100;
 
-	volume = (int16(volume) * 0x7F) / 100;
+	volume = ((int16)volume * 0x7F) / 100;
 	Track &track = _tracks[trackIndex];
 
 	for (uint i = 0; i < MIDIPLYR_CHANNEL_COUNT; i++) {
@@ -766,7 +766,7 @@ void MidiPlyrDriver::vocSrUpdateCounters() {
 
 void MidiPlyrDriver::vocSrGetCounters(uint32 &timeFrac, uint16 &blockNo) const {
 	Common::StackLock lock(_mutex);
-	timeFrac = (uint32(_vocSnapshotHi) << 16) | _vocSnapshotLo;
+	timeFrac = ((uint32)_vocSnapshotHi << 16) | _vocSnapshotLo;
 	blockNo = _vocBlockNo;
 }
 
diff --git a/engines/comfy/palette.cpp b/engines/comfy/palette.cpp
index 03a20a4b0b5..99e91a3c2dc 100644
--- a/engines/comfy/palette.cpp
+++ b/engines/comfy/palette.cpp
@@ -42,12 +42,12 @@ void ComfyEngine::colorDatClose() {
 
 void ComfyEngine::colorDatReadEntry(uint16 paletteId) {
 	colorDatOpen();
-	uint16 offset = uint16(paletteId * COMFY_PALETTE_BYTES);
+	uint16 offset = (uint16)(paletteId * COMFY_PALETTE_BYTES);
 	if (!_colorDatStream->seek(offset))
-		error("Could not seek to palette %u in COLORS.DAT", uint(paletteId));
+		error("Could not seek to palette %u in COLORS.DAT", (uint)paletteId);
 
 	if (_colorDatStream->read(_paletteTarget, COMFY_PALETTE_BYTES) != COMFY_PALETTE_BYTES)
-		error("COLORS.DAT is truncated while reading palette %u", uint(paletteId));
+		error("COLORS.DAT is truncated while reading palette %u", (uint)paletteId);
 
 	if (_engineVersion == kEngineVersion3) {
 		// Version 3 forces color 0 to black immediately after reading the palette...
@@ -66,11 +66,11 @@ void ComfyEngine::paletteInterpolate(uint16 step, uint16 maximum) {
 	if (!maximum)
 		return;
 
-	int16 remaining = int16(maximum - step);
+	int16 remaining = (int16)(maximum - step);
 	for (uint i = 0; i < COMFY_PALETTE_BYTES; i++) {
 		int32 from = _paletteFadeSource[i];
 		int32 to = _paletteTarget[i];
-		_paletteDisplay[i] = byte((from * remaining + to * int16(step)) / int16(maximum));
+		_paletteDisplay[i] = (byte)((from * remaining + to * (int16)step) / (int16)maximum);
 	}
 }
 
@@ -78,8 +78,8 @@ void ComfyEngine::paletteFadeStep(uint16 delta) {
 	if (!_paletteFading)
 		return;
 
-	_fadeStep = uint16(_fadeStep + delta);
-	if (int16(_fadeStep) >= int16(_fadeMax)) {
+	_fadeStep = (uint16)(_fadeStep + delta);
+	if ((int16)_fadeStep >= (int16)_fadeMax) {
 		_fadeStep = _fadeMax;
 		memcpy(_paletteFadeSource, _paletteTarget, COMFY_PALETTE_BYTES);
 		memcpy(_paletteDisplay, _paletteTarget, COMFY_PALETTE_BYTES);
@@ -115,7 +115,7 @@ void ComfyEngine::paletteApplyBrightness(uint16 brightness) {
 	if (_paletteFading)
 		_paletteFading = false;
 
-	uint16 inverse = uint16(0x100 - brightness);
+	uint16 inverse = (uint16)(0x100 - brightness);
 	memcpy(_paletteFadeSource, _paletteDisplay, COMFY_PALETTE_BYTES);
 	memcpy(_paletteDisplay, _paletteFadeSource + inverse * 3, brightness * 3);
 	memcpy(_paletteDisplay + brightness * 3, _paletteFadeSource, inverse * 3);
@@ -124,9 +124,9 @@ void ComfyEngine::paletteApplyBrightness(uint16 brightness) {
 
 void ComfyEngine::paletteConvertRgbToLogical(byte *source, byte *destination) {
 	for (uint i = 0; i < 256; i++) {
-		destination[i * 4 + 2] = byte(source[i * 3] << 2);
-		destination[i * 4 + 1] = byte(source[i * 3 + 1] << 2);
-		destination[i * 4] = byte(source[i * 3 + 2] << 2);
+		destination[i * 4 + 2] = (byte)(source[i * 3] << 2);
+		destination[i * 4 + 1] = (byte)(source[i * 3 + 1] << 2);
+		destination[i * 4] = (byte)(source[i * 3 + 2] << 2);
 	}
 }
 
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index 04360f714a2..87c31d34318 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -78,7 +78,7 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 	WRITE_LE_UINT16(sceneEntries + 1, _sceneEntryCount);
 	WRITE_LE_UINT16(sceneEntries + 3, _sceneEntryFrameSize);
 	for (uint i = 0; i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
-		WRITE_LE_UINT16(sceneEntries + 5 + i * 2, uint16(_sceneEntryOffsets[i]));
+		WRITE_LE_UINT16(sceneEntries + 5 + i * 2, (uint16)_sceneEntryOffsets[i]);
 
 	if (_engineVersion == kEngineVersion3) {
 		for (uint channel = 0; channel < COMFY_SCENE_MUSIC_CHANNEL_COUNT; channel++) {
@@ -135,23 +135,23 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 
 void ComfyEngine::envConvToXms(byte *source, uint16 index) {
 	if (!index || _sceneMemoryBlock.empty())
-		error("Invalid environment XMS destination %u", uint(index));
+		error("Invalid environment XMS destination %u", (uint)index);
 
 	sceneBlockPackRuntimeState();
-	uint32 offset = uint32(index - 1) * _sceneMemoryBlock.size();
+	uint32 offset = (uint32)(index - 1) * _sceneMemoryBlock.size();
 	if (offset > _environmentData.size() || _sceneMemoryBlock.size() > _environmentData.size() - offset)
-		error("Environment XMS destination %u is outside the allocated block", uint(index));
+		error("Environment XMS destination %u is outside the allocated block", (uint)index);
 
 	memcpy(&_environmentData[offset], source, _sceneMemoryBlock.size());
 }
 
 bool ComfyEngine::envXmsToConv(byte *destination, uint16 index) {
 	if (!index || _sceneMemoryBlock.empty())
-		error("Invalid environment XMS source %u", uint(index));
+		error("Invalid environment XMS source %u", (uint)index);
 
-	uint32 offset = uint32(index - 1) * _sceneMemoryBlock.size();
+	uint32 offset = (uint32)(index - 1) * _sceneMemoryBlock.size();
 	if (offset > _environmentData.size() || _sceneMemoryBlock.size() > _environmentData.size() - offset)
-		error("Environment XMS source %u is outside the allocated block", uint(index));
+		error("Environment XMS source %u is outside the allocated block", (uint)index);
 
 	memcpy(destination, &_environmentData[offset], _sceneMemoryBlock.size());
 	sceneBlockUnpackRuntimeState();
@@ -264,7 +264,7 @@ void ComfyEngine::sceneGoto(uint16 count) {
 	_sceneEntryListActive = true;
 	_sceneEntryCount = count;
 	uint32 frameSize = _engineVersion == kEngineVersion3 ? COMFY_SCENE_FRAME_BYTES_V3 : COMFY_SCENE_FRAME_BYTES;
-	_sceneEntryFrameSize = count ? frameSize / int16(count) : 0;
+	_sceneEntryFrameSize = count ? frameSize / (int16)count : 0;
 	for (uint i = 0; i < count && i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
 		_sceneEntryOffsets[i] = 0xFFFF;
 
@@ -303,7 +303,7 @@ void ComfyEngine::sceneStartWithMusic(uint16 scene) {
 	if (root) {
 		paletteLoadWithFade(actorReadU16(*root, kActorXFixed), 0);
 		if (actorReadU32(*root, kActorYFixed))
-			paletteApplyBrightness(byte(actorReadU16(*root, kActorYFixed)));
+			paletteApplyBrightness((byte)actorReadU16(*root, kActorYFixed));
 	}
 
 	if (_keyBits)
@@ -316,7 +316,7 @@ bool ComfyEngine::sceneEntryLoad(uint16 descriptor, uint16 index) {
 	sceneEntryReadFromXms(header, descriptor, sizeof(header));
 	uint16 size = READ_LE_UINT16(header);
 	uint32 fileOffset = READ_LE_UINT32(header + 2);
-	uint32 destinationOffset = uint32(_sceneEntryFrameSize) * index;
+	uint32 destinationOffset = (uint32)_sceneEntryFrameSize * index;
 	if (fileOffset > _midiFileData.size() || size > _midiFileData.size() - fileOffset ||
 			destinationOffset > _sceneFrameData.size() || size > _sceneFrameData.size() - destinationOffset)
 		return false;
@@ -373,7 +373,7 @@ void ComfyEngine::midiStopSong(uint16 channel) {
 
 void ComfyEngine::midiPlaySongAtFrame(uint16 channel, uint16 frame) {
 	midiStopSong(channel);
-	uint32 offset = uint32(_sceneEntryFrameSize) * frame;
+	uint32 offset = (uint32)_sceneEntryFrameSize * frame;
 	if (!_midiPlyrDriver || channel >= COMFY_SCENE_MUSIC_CHANNEL_COUNT ||
 			offset > _sceneFrameData.size() || 6 > _sceneFrameData.size() - offset)
 		return;
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 271c57e8b9c..9e3ce24cd40 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -39,37 +39,37 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		if (!target)
 			return kScriptUnhandled;
 
-		if ((opcode == 0x01 && x == int16(0xF830)) || (opcode == 0x02 && x == int16(0x8AD0))) {
-			Actor *other = actorResolve(uint16(y), _currentActor);
+		if ((opcode == 0x01 && x == (int16)0xF830) || (opcode == 0x02 && x == (int16)0x8AD0)) {
+			Actor *other = actorResolve((uint16)y, _currentActor);
 			if (!other)
 				return kScriptUnhandled;
 
-			x = int16(int32(actorReadU32(*other, kActorXFixed)) >> 12);
-			y = int16(int32(actorReadU32(*other, kActorYFixed)) >> 12);
-		} else if (opcode == 0x01 && x == int16(0xF448)) {
-			x = int16(-int32(actorReadU32(*target, kActorXFixed)) >> 12);
+			x = (int16)((int32)actorReadU32(*other, kActorXFixed) >> 12);
+			y = (int16)((int32)actorReadU32(*other, kActorYFixed) >> 12);
+		} else if (opcode == 0x01 && x == (int16)0xF448) {
+			x = (int16)(-(int32)actorReadU32(*target, kActorXFixed) >> 12);
 		}
 
-		if (opcode == 0x01 && y == int16(0xF448))
-			y = int16(-int32(actorReadU32(*target, kActorYFixed)) >> 12);
+		if (opcode == 0x01 && y == (int16)0xF448)
+			y = (int16)(-(int32)actorReadU32(*target, kActorYFixed) >> 12);
 
 		if (randomize) {
-			if (x != int16(0xFC18))
-				x = int16((int32(getRandomNumber(0x7FFF)) * x) / 0x8000);
+			if (x != (int16)0xFC18)
+				x = (int16)(((int32)getRandomNumber(0x7FFF) * x) / 0x8000);
 
-			if (y != int16(0xFC18))
-				y = int16((int32(getRandomNumber(0x7FFF)) * y) / 0x8000);
+			if (y != (int16)0xFC18)
+				y = (int16)(((int32)getRandomNumber(0x7FFF) * y) / 0x8000);
 		}
 
 		if (opcode == 0x01) {
-			if (x != int16(0xFC18))
-				actorWriteU32(*target, kActorXFixed, uint32(int32(x) * 0x1000));
+			if (x != (int16)0xFC18)
+				actorWriteU32(*target, kActorXFixed, (uint32)((int32)x * 0x1000));
 
-			if (y != int16(0xFC18))
-				actorWriteU32(*target, kActorYFixed, uint32(int32(y) * 0x1000));
+			if (y != (int16)0xFC18)
+				actorWriteU32(*target, kActorYFixed, (uint32)((int32)y * 0x1000));
 		} else {
-			actorWriteU32(*target, kActorXFixed, actorReadU32(*target, kActorXFixed) + uint32(int32(x) * 0x1000));
-			actorWriteU32(*target, kActorYFixed, actorReadU32(*target, kActorYFixed) + uint32(int32(y) * 0x1000));
+			actorWriteU32(*target, kActorXFixed, actorReadU32(*target, kActorXFixed) + (uint32)((int32)x * 0x1000));
+			actorWriteU32(*target, kActorYFixed, actorReadU32(*target, kActorYFixed) + (uint32)((int32)y * 0x1000));
 		}
 
 		return kScriptContinue;
@@ -81,7 +81,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint16 frame = scriptReadStringIndex(pc);
 		pc += 2;
 		if (target)
-			actorWriteU32(*target, kActorSpriteSelector, uint32(int32(int16(frame))));
+			actorWriteU32(*target, kActorSpriteSelector, (uint32)(int32)(int16)frame);
 
 		return kScriptContinue;
 	}
@@ -102,7 +102,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		byte state = scriptReadByte(pc + 2);
 		uint32 targetPc = scriptReadDword(pc + 3);
 		pc += 7;
-		if (!key || byte(keyBitTest(key)) == state) {
+		if (!key || (byte)keyBitTest(key) == state) {
 			if (opcode == 0x19)
 				actorSetPc(actor, pc);
 
@@ -131,7 +131,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			return kScriptUnhandled;
 
 		bool current = target == &actor;
-		uint16 actorIndex = uint16(target - &_actors[0]);
+		uint16 actorIndex = (uint16)(target - &_actors[0]);
 		actorUnlink(actorIndex);
 		actorFreeTreePc(actorIndex);
 		_actorDestroyedCurrent = current;
@@ -158,7 +158,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	}
 
 	if (opcode == 0x09) {
-		actorSetFrame(int16(scriptReadWord(pc)));
+		actorSetFrame((int16)scriptReadWord(pc));
 		pc += 2;
 		return kScriptContinue;
 	}
@@ -194,7 +194,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		if (!target)
 			return kScriptUnhandled;
 
-		int16 actual = int32(actorReadU32(*target, opcode == 0x0E || opcode == 0x10 ? kActorXFixed : kActorYFixed)) >> 12;
+		int16 actual = (int32)actorReadU32(*target, opcode == 0x0E || opcode == 0x10 ? kActorXFixed : kActorYFixed) >> 12;
 		bool matched = ((mode & 2) && expected == actual) || ((mode & 4) && expected < actual) || ((mode & 1) && expected > actual);
 		if (matched) {
 			if (opcode == 0x0E || opcode == 0x0F)
@@ -218,7 +218,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		byte totalWeight = scriptReadByte(pc++);
 		byte installReturnPc = scriptReadByte(pc++);
 		uint32 returnPc = pc + installReturnPc - 3;
-		byte choice = byte((getRandomNumber(0x7FFF) * totalWeight) / 0x8000);
+		byte choice = (byte)((getRandomNumber(0x7FFF) * totalWeight) / 0x8000);
 		byte accumulated = 0;
 		uint32 targetPc = 0;
 		do {
@@ -241,7 +241,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		if (!target)
 			return kScriptUnhandled;
 
-		uint16 targetIndex = uint16(target - &_actors[0]);
+		uint16 targetIndex = (uint16)(target - &_actors[0]);
 		uint16 oldParent = actorReadU16(*target, kActorParent);
 		actorUnlink(targetIndex);
 		if (mode == 'O')
@@ -258,7 +258,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			uint16 id = scriptReadWord(pc);
 			pc += 2;
 			if (opcode == 0x15) {
-				spriteGetPtr(int16(id));
+				spriteGetPtr((int16)id);
 				if (_spriteConversionLoads.count < COMFY_RESOURCE_LIST_CAPACITY)
 					_spriteConversionLoads.ids[_spriteConversionLoads.count++] = id;
 			} else {
@@ -279,7 +279,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		pc += 2;
 		byte count = scriptReadByte(pc++);
 		vocQueuePush(soundId, count, pc);
-		pc += uint32(count) * 2;
+		pc += (uint32)count * 2;
 		return kScriptContinue;
 	}
 
@@ -381,7 +381,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	if (opcode == 0x1F) {
 		uint16 bit = scriptReadWord(pc);
 		pc += 2;
-		if (int16(bit) >= 0x32) {
+		if ((int16)bit >= 0x32) {
 			bit -= 0x32;
 			_musicEventFlag = 1;
 		}
@@ -395,7 +395,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	if (opcode == 0x20) {
 		uint16 scene = scriptReadWord(pc);
 		pc += 2;
-		if (!_pendingScene || int16(scene) < int16(_pendingScene))
+		if (!_pendingScene || (int16)scene < (int16)_pendingScene)
 			_pendingScene = scene;
 
 		renderSetDirty();
@@ -432,7 +432,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	}
 
 	if (opcode == 0x24) {
-		midiSetTimeScale(int16(scriptReadStringIndex(pc)));
+		midiSetTimeScale((int16)scriptReadStringIndex(pc));
 		pc += 2;
 		return kScriptContinue;
 	}
@@ -461,7 +461,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint16 key = scriptReadWord(pc + 4);
 		pc += 6;
 		int16 lhs = first < _midiHandles.size() ? _midiHandles[first] : 0;
-		int16 rhs = opcode == 0x26 ? int16(second) : (second < _midiHandles.size() ? int16(_midiHandles[second]) : 0);
+		int16 rhs = opcode == 0x26 ? (int16)second : (second < _midiHandles.size() ? (int16)_midiHandles[second] : 0);
 		if (lhs >= rhs)
 			keyBitSet(key);
 
@@ -484,7 +484,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	}
 
 	if (opcode == 0x2B) {
-		pc = uint32(int32(pc) + int16(scriptReadWord(pc) * 2));
+		pc = (uint32)((int32)pc + (int16)(scriptReadWord(pc) * 2));
 		return kScriptContinue;
 	}
 
@@ -537,7 +537,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 				midiHandleCopy(destination, first);
 			else if (command == 'm' && second < _midiHandles.size())
 				midiHandleCopy(destination,
-					int16(midiGetHandle(second)) <= int16(midiGetHandle(first)) ? first : second);
+					(int16)midiGetHandle(second) <= (int16)midiGetHandle(first) ? first : second);
 		}
 
 		return kScriptContinue;
@@ -571,7 +571,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			for (uint i = 0; i < _wcomfy99FeatureWordCount; i++)
 				_wcomfy99FeatureWords[i] = scriptReadWord(pc + i * 2);
 
-			pc += uint32(count) * 2;
+			pc += (uint32)count * 2;
 		} else if (opcode == 0x32) {
 			_wcomfy99Stub32FirstWord = scriptReadWord(pc);
 			_wcomfy99Stub32SecondWord = scriptReadWord(pc + 2);
@@ -580,14 +580,14 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			pc += 4;
 			byte inlineBytes = scriptReadByte(pc++);
 			byte tripleCount = scriptReadByte(pc++);
-			pc += inlineBytes + uint32(tripleCount) * 3;
+			pc += inlineBytes + (uint32)tripleCount * 3;
 		} else if (opcode == 0x34) {
 			byte subop = scriptReadByte(pc++);
 			uint16 value = scriptReadWord(pc);
 			pc += 2;
 			Common::String key;
 			for (byte character = scriptReadByte(pc++); character; character = scriptReadByte(pc++))
-				key += char(character);
+				key += (char)character;
 
 			key.trim();
 
@@ -655,7 +655,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 				uint16 argument = scriptReadWord(pc);
 				pc += 2;
 				uint16 percentage = argument == 0x00FF ? 0x00FF :
-					(int16(argument) < 0 ? 0 : MIN<uint16>(argument, 100));
+					((int16)argument < 0 ? 0 : MIN<uint16>(argument, 100));
 				if (subop == 1)
 					_wcomfy99HostWordA = argument;
 				else if (subop == 2 && percentage != 0x00FF)
@@ -716,43 +716,43 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			return kScriptUnhandled;
 
 		bool moveTo = opcode == 0x52 || opcode == 0x71;
-		if ((moveTo && x == int16(0xF830)) || (!moveTo && x == int16(0x8AD0))) {
-			Actor *other = actorResolve(uint16(y), _currentActor);
+		if ((moveTo && x == (int16)0xF830) || (!moveTo && x == (int16)0x8AD0)) {
+			Actor *other = actorResolve((uint16)y, _currentActor);
 			if (!other)
 				return kScriptUnhandled;
 
 			if (moveTo) {
-				x = int16(int32(actorReadU32(*other, kActorXFixed)) >> 12);
-				y = int16(int32(actorReadU32(*other, kActorYFixed)) >> 12);
+				x = (int16)((int32)actorReadU32(*other, kActorXFixed) >> 12);
+				y = (int16)((int32)actorReadU32(*other, kActorYFixed) >> 12);
 			} else {
-				x = int16(actorReadU16(*other, kActorXFixed)) >> 12;
-				y = int16(actorReadU16(*other, kActorYFixed)) >> 12;
+				x = (int16)actorReadU16(*other, kActorXFixed) >> 12;
+				y = (int16)actorReadU16(*other, kActorYFixed) >> 12;
 			}
 		}
 
 		if (randomize) {
-			if (!moveTo || x != int16(0xFC18))
-				x = int16((int32(getRandomNumber(0x7FFF)) * x) / 0x8000);
+			if (!moveTo || x != (int16)0xFC18)
+				x = (int16)(((int32)getRandomNumber(0x7FFF) * x) / 0x8000);
 
-			if (!moveTo || y != int16(0xFC18))
-				y = int16((int32(getRandomNumber(0x7FFF)) * y) / 0x8000);
+			if (!moveTo || y != (int16)0xFC18)
+				y = (int16)(((int32)getRandomNumber(0x7FFF) * y) / 0x8000);
 		}
 
-		int32 dx = int32(x) * 0x1000;
-		int32 dy = int32(y) * 0x1000;
+		int32 dx = (int32)x * 0x1000;
+		int32 dy = (int32)y * 0x1000;
 		if (moveTo) {
-			dx = x == int16(0xFC18) ? 0 : dx - int32(actorReadU32(*target, kActorXFixed));
-			dy = y == int16(0xFC18) ? 0 : dy - int32(actorReadU32(*target, kActorYFixed));
+			dx = x == (int16)0xFC18 ? 0 : dx - (int32)actorReadU32(*target, kActorXFixed);
+			dy = y == (int16)0xFC18 ? 0 : dy - (int32)actorReadU32(*target, kActorYFixed);
 		}
 
 		if (opcode == 0x51 || opcode == 0x52 || (moveTo && duration < 0)) {
 			if (duration < 0)
 				duration = -duration;
 
-			int16 distanceX = ABS(int16(dx >> 12));
-			int16 distanceY = ABS(int16(dy >> 12));
+			int16 distanceX = ABS((int16)(dx >> 12));
+			int16 distanceY = ABS((int16)(dy >> 12));
 			int16 distance = MAX(distanceX, distanceY);
-			duration = int16((int32(distance) * 100) / duration);
+			duration = (int16)(((int32)distance * 100) / duration);
 			if (!duration)
 				duration = 1;
 		}
@@ -798,7 +798,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 		if (balance) {
 			uint16 step = balance < 5 ? balance : 5;
-			balance = step < uint16(requested - 1) ? step : uint16(requested - 1);
+			balance = step < (uint16)(requested - 1) ? step : (uint16)(requested - 1);
 			actorWriteU16(actor, kActorWaitAccum, actorReadU16(actor, kActorWaitAccum) - balance);
 		}
 
@@ -841,7 +841,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 					condition = _wcomfy99RecordHostEnabled;
 				} else if (argument == 30) {
 					Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(Common::Path("comfy.htm"), true));
-					condition = bool(stream);
+					condition = (bool)stream;
 				}
 			}
 		} else if (kind == 1) {
diff --git a/engines/comfy/sound.cpp b/engines/comfy/sound.cpp
index 1c737ac9d71..d5f53198235 100644
--- a/engines/comfy/sound.cpp
+++ b/engines/comfy/sound.cpp
@@ -41,7 +41,7 @@ public:
 				return value;
 			}
 
-			value |= uint32((_data[bytePosition] >> (_bitPosition & 7)) & 1) << bit;
+			value |= (uint32)((_data[bytePosition] >> (_bitPosition & 7)) & 1) << bit;
 			_bitPosition++;
 		}
 
@@ -139,7 +139,7 @@ bool ComfyEngine::soundDecodeEntry(uint16 index) {
 	while (pc < end && commandCount++ < dataSize) {
 		byte command = _vocFileData[pc++];
 		if (!command) {
-			SoundCue cue = {0, uint32((_soundPcm.size() * 100) / _soundSampleRate)};
+			SoundCue cue = {0, (uint32)((_soundPcm.size() * 100) / _soundSampleRate)};
 			_soundCues.push_back(cue);
 			break;
 		}
@@ -147,8 +147,8 @@ bool ComfyEngine::soundDecodeEntry(uint16 index) {
 		if (3 > end - pc)
 			return false;
 
-		uint32 argument = uint32(_vocFileData[pc]) | (uint32(_vocFileData[pc + 1]) << 8) |
-			(uint32(_vocFileData[pc + 2]) << 16);
+		uint32 argument = (uint32)_vocFileData[pc] | ((uint32)_vocFileData[pc + 1] << 8) |
+			((uint32)_vocFileData[pc + 2] << 16);
 		pc += 3;
 		if (command == 1 || command == 2) {
 			uint32 length = argument;
@@ -184,7 +184,7 @@ bool ComfyEngine::soundDecodeEntry(uint16 index) {
 			if (nextSample != sample) {
 				uint32 oldRate = _soundSampleRate;
 				uint32 newRate = 0x0F4240 / (0x100 - nextSample);
-				fill = uint16((uint32(fill) * oldRate) / newRate);
+				fill = (uint16)(((uint32)fill * oldRate) / newRate);
 			}
 
 			uint32 oldSize = _soundPcm.size();
@@ -194,7 +194,7 @@ bool ComfyEngine::soundDecodeEntry(uint16 index) {
 			if (2 > end - pc)
 				return false;
 
-			SoundCue cue = {READ_LE_UINT16(&_vocFileData[pc]), uint32((_soundPcm.size() * 100) / _soundSampleRate)};
+			SoundCue cue = {READ_LE_UINT16(&_vocFileData[pc]), (uint32)((_soundPcm.size() * 100) / _soundSampleRate)};
 			_soundCues.push_back(cue);
 			pc += 2;
 		} else if (command == 6) {
@@ -262,7 +262,7 @@ bool ComfyEngine::soundDecodeCompressedEntry(uint32 dataOffset, uint32 dataSize)
 		}
 
 		if (command == 0) {
-			SoundCue cue = {0, uint32((_soundPcm.size() * 100) / _soundSampleRate)};
+			SoundCue cue = {0, (uint32)((_soundPcm.size() * 100) / _soundSampleRate)};
 			_soundCues.push_back(cue);
 			break;
 		} else if (command == 1 || command == 2) {
@@ -299,7 +299,7 @@ bool ComfyEngine::soundDecodeCompressedEntry(uint32 dataOffset, uint32 dataSize)
 							value = bits.read(8);
 						else {
 							byte predictor = output >= predictorDistance ? _soundPcm[output - predictorDistance] : 0x80;
-							value = predictor + byte(delta - (1 << (width - 1)));
+							value = predictor + (byte)(delta - (1 << (width - 1)));
 						}
 					}
 
@@ -316,7 +316,7 @@ bool ComfyEngine::soundDecodeCompressedEntry(uint32 dataOffset, uint32 dataSize)
 		} else if (command == 4) {
 			uint16 mode = bits.read(2);
 			uint16 value = mode == 0 ? 1 : mode == 1 ? 2 : mode == 2 ? bits.read(8) : bits.read(16);
-			SoundCue cue = {value, uint32((_soundPcm.size() * 100) / _soundSampleRate)};
+			SoundCue cue = {value, (uint32)((_soundPcm.size() * 100) / _soundSampleRate)};
 			_soundCues.push_back(cue);
 		} else if (command == 6) {
 			loopCount = bits.read(16);
@@ -372,7 +372,7 @@ void ComfyEngine::soundAdvanceTick() {
 	}
 
 	uint32 counter = _midiPlyrDriver ? _midiPlyrDriver->getVocCounter() :
-		uint32((_mixer->getSoundElapsedTime(_soundHandle) + 9) / 10);
+		(uint32)((_mixer->getSoundElapsedTime(_soundHandle) + 9) / 10);
 	uint32 compareCounter = counter >= 2 ? counter - 2 : 0;
 	bool phaseCueSeen = false;
 	while (_soundNextCue < _soundCues.size() && compareCounter > _soundCues[_soundNextCue].counterThreshold &&
diff --git a/engines/comfy/timer.cpp b/engines/comfy/timer.cpp
index 4346abdef6a..14a6bba6581 100644
--- a/engines/comfy/timer.cpp
+++ b/engines/comfy/timer.cpp
@@ -27,8 +27,8 @@ uint16 ComfyEngine::timerTick() {
 	_timer2 = _timer1;
 	_timer1 = _timer0;
 	_timer0 = _timerCurrent;
-	_timerCurrent = int16(midiTick());
-	return uint16(_timerCurrent);
+	_timerCurrent = (int16)midiTick();
+	return (uint16)_timerCurrent;
 }
 
 } // End of namespace Comfy
diff --git a/engines/comfy/video.cpp b/engines/comfy/video.cpp
index 4699729b064..525636f96dd 100644
--- a/engines/comfy/video.cpp
+++ b/engines/comfy/video.cpp
@@ -26,7 +26,7 @@
 namespace Comfy {
 
 uint32 ComfyEngine::framebufferBytes() {
-	return uint32(_logicalScreenWidth) * _logicalScreenHeight;
+	return (uint32)_logicalScreenWidth * _logicalScreenHeight;
 }
 
 void ComfyEngine::videoInit() {
@@ -113,9 +113,9 @@ void ComfyEngine::videoFindBestMode(VideoRectRecord record) {
 		merged.right = (MAX(existing.right, record.right) + 1) / 2 * 2;
 		merged.top = MIN(existing.top, record.top) / 2 * 2;
 		merged.bottom = (MAX(existing.bottom, record.bottom) + 1) / 2 * 2;
-		merged.area = uint16((merged.right - merged.left) * (merged.bottom - merged.top));
+		merged.area = (uint16)((merged.right - merged.left) * (merged.bottom - merged.top));
 
-		if (uint32(existing.area) + record.area >= merged.area) {
+		if ((uint32)existing.area + record.area >= merged.area) {
 			existing = merged;
 			return;
 		}
@@ -130,7 +130,7 @@ void ComfyEngine::framebufCopyAll(byte *destination, byte *source) {
 }
 
 void ComfyEngine::framebufClear(uint16 color) {
-	memset(_framebufPtr, byte(color), framebufferBytes());
+	memset(_framebufPtr, (byte)color, framebufferBytes());
 }
 
 void ComfyEngine::videoPresentFrame() {
@@ -168,12 +168,12 @@ void ComfyEngine::videoPresentFrame() {
 					continue;
 
 				for (int16 y = record.top; y < record.bottom; y++) {
-					byte *source = _framebufPtr + uint32(y) * _logicalScreenWidth + record.left;
-					byte *destination = _presentBuffer + uint32(y) * _logicalScreenWidth + record.left;
+					byte *source = _framebufPtr + (uint32)y * _logicalScreenWidth + record.left;
+					byte *destination = _presentBuffer + (uint32)y * _logicalScreenWidth + record.left;
 					memcpy(destination, source, width);
 				}
 
-				byte *source = _presentBuffer + uint32(record.top) * _logicalScreenWidth + record.left;
+				byte *source = _presentBuffer + (uint32)record.top * _logicalScreenWidth + record.left;
 				_screen->copyRectToSurface(source, _logicalScreenWidth, record.left, record.top, width, height);
 			}
 		}


Commit: 789f27bd10a8d5939395926a12b6ef5d7a1f6e4e
    https://github.com/scummvm/scummvm/commit/789f27bd10a8d5939395926a12b6ef5d7a1f6e4e
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Add numeric engine version to detection entries

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/detection.h
    engines/comfy/detection_tables.h
    engines/comfy/expr.cpp
    engines/comfy/game.cpp
    engines/comfy/input.cpp
    engines/comfy/metaengine.cpp
    engines/comfy/metaengine.h
    engines/comfy/midi.cpp
    engines/comfy/palette.cpp
    engines/comfy/scene.cpp
    engines/comfy/script_vm.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 2ababe03531..71eef16f494 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -34,26 +34,11 @@ namespace Comfy {
 
 ComfyEngine *g_engine;
 
-static ComfyEngineVersion getEngineVersion(const ADGameDescription *gameDesc) {
-	if (!strcmp(gameDesc->gameId, "comfyland")) {
-		if (gameDesc->extra && !strcmp(gameDesc->extra, "1999"))
-			return kEngineVersion3;
-
-		return kEngineVersion1;
-	}
-
-	if (!strcmp(gameDesc->gameId, "boo") || !strcmp(gameDesc->gameId, "first") ||
-			!strcmp(gameDesc->gameId, "match"))
-		return kEngineVersion2;
-
-	return kEngineVersion3;
-}
-
-ComfyEngine::ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc) : Engine(syst),
-	_gameDescription(gameDesc), _engineVersion(getEngineVersion(gameDesc)),
+ComfyEngine::ComfyEngine(OSystem *syst, const ComfyGameDescription *gameDesc) : Engine(syst),
+	_game(gameDesc), _engineVersion(gameDesc->version),
 	_randomSource("Comfy"),
-	_logicalScreenWidth(!strcmp(gameDesc->gameId, "panther") ? COMFY_PANTHER_SCREEN_WIDTH : COMFY_SCREEN_WIDTH),
-	_logicalScreenHeight(!strcmp(gameDesc->gameId, "panther") ? COMFY_PANTHER_SCREEN_HEIGHT : COMFY_SCREEN_HEIGHT) {
+	_logicalScreenWidth(!strcmp(gameDesc->desc.gameId, "panther") ? COMFY_PANTHER_SCREEN_WIDTH : COMFY_SCREEN_WIDTH),
+	_logicalScreenHeight(!strcmp(gameDesc->desc.gameId, "panther") ? COMFY_PANTHER_SCREEN_HEIGHT : COMFY_SCREEN_HEIGHT) {
 	memset(_paletteFadeSource, 0, sizeof(_paletteFadeSource));
 	memset(_paletteTarget, 0, sizeof(_paletteTarget));
 	memset(_paletteDisplay, 0, sizeof(_paletteDisplay));
@@ -77,7 +62,7 @@ ComfyEngine::~ComfyEngine() {
 }
 
 Common::String ComfyEngine::getGameId() const {
-	return _gameDescription->gameId;
+	return _game->desc.gameId;
 }
 
 Common::Error ComfyEngine::run() {
@@ -209,7 +194,7 @@ uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
 
 	if (!assetsLoad(0x4000, _sceneRunPtr)) {
 		assetsUnload(0);
-		if (_engineVersion != kEngineVersion3) {
+		if (_engineVersion != 3) {
 			_sceneRunBuffer.clear();
 			_sceneRunPtr = nullptr;
 		}
@@ -222,7 +207,7 @@ uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
 	}
 
 	gameMainLoop(sceneId);
-	if (_engineVersion == kEngineVersion3 && _languageSessionRestartRequested) {
+	if (_engineVersion == 3 && _languageSessionRestartRequested) {
 		nextScene = sceneId;
 		_languageSessionRestartRequested = false;
 	} else if (checkNext) {
@@ -232,20 +217,20 @@ uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
 		if ((int16)nextScene > 0 && (int16)nextScene < 0x65 && nextScene != sceneId)
 			shouldStartNext = 1;
 
-		if (_engineVersion == kEngineVersion3)
+		if (_engineVersion == 3)
 			shouldStartNext = 1;
 	}
 
 	if (exitFlag || shouldStartNext)
 		restorePalette = 0;
 
-	if (_engineVersion == kEngineVersion3)
+	if (_engineVersion == 3)
 		animFileShutdown();
 
 	midiShutdown();
 	assetsUnload(0);
 	inputQueueReset();
-	if (_engineVersion != kEngineVersion3) {
+	if (_engineVersion != 3) {
 		_sceneRunBuffer.clear();
 		_sceneRunPtr = nullptr;
 	}
@@ -293,29 +278,29 @@ void ComfyEngine::processEvents() {
 			hostKeyboardSetKeyState(hostKeyboardVirtualKey(event.kbd.keycode), false);
 			break;
 		case Common::EVENT_MOUSEMOVE:
-			if (_engineVersion == kEngineVersion3) {
+			if (_engineVersion == 3) {
 				_mouseX = CLIP<int16>((int32)event.mouse.x * 320 / _logicalScreenWidth, 0, 319);
 				_mouseY = CLIP<int16>((int32)event.mouse.y * 200 / _logicalScreenHeight, 0, 199);
 			}
 			break;
 		case Common::EVENT_LBUTTONDOWN:
-			if (_engineVersion == kEngineVersion3) {
+			if (_engineVersion == 3) {
 				_mouseLeftButton = true;
 				_mouseLeftButtonEdge = false;
 			}
 			break;
 		case Common::EVENT_LBUTTONUP:
-			if (_engineVersion == kEngineVersion3)
+			if (_engineVersion == 3)
 				_mouseLeftButtonEdge = true;
 			break;
 		case Common::EVENT_RBUTTONDOWN:
-			if (_engineVersion == kEngineVersion3) {
+			if (_engineVersion == 3) {
 				_mouseRightButton = true;
 				_mouseRightButtonEdge = false;
 			}
 			break;
 		case Common::EVENT_RBUTTONUP:
-			if (_engineVersion == kEngineVersion3)
+			if (_engineVersion == 3)
 				_mouseRightButtonEdge = true;
 			break;
 		default:
@@ -382,11 +367,11 @@ void ComfyEngine::mouseUpdateCursor() {
 void ComfyEngine::gameMainLoop(uint16 argument) {
 	byte keepRunning = 1;
 	uint16 lastKey = 0xFFFF;
-	if (_engineVersion == kEngineVersion3)
+	if (_engineVersion == 3)
 		midiInitInstance();
 
 	actorInit(1, 0, 1, 1, 0x14, 0, 0, 0, 1);
-	if (_engineVersion == kEngineVersion3)
+	if (_engineVersion == 3)
 		mouseSetActor(nullptr);
 
 	keyBitSet(2);
@@ -417,7 +402,7 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 		lptKeyboardScanAndProcess();
 		lptKeyToFlags(lastKey);
 		actorTickTree(rootIndex);
-		if (_engineVersion == kEngineVersion3) {
+		if (_engineVersion == 3) {
 			mouseClearButtonEdges();
 			mouseUpdateCursor();
 		}
@@ -446,7 +431,7 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 			renderSetDirty();
 		}
 
-		if (_engineVersion == kEngineVersion3)
+		if (_engineVersion == 3)
 			_waveOutputActive = true;
 
 		lastKey = 0xFFFF;
@@ -517,7 +502,7 @@ void ComfyEngine::sceneTickEvent() {
 	if (_soundEventIndex == _soundEventMaximum)
 		return;
 
-	if (_engineVersion == kEngineVersion3) {
+	if (_engineVersion == 3) {
 		VocQueueEntry1999 &entry = _vocQueue1999[_soundEventIndex];
 		bool started = false;
 		if (entry.state == 0xFFFF && (entry.soundId != 0xFFFF || !animFrameIsReady())) {
@@ -646,7 +631,7 @@ bool ComfyEngine::vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc)
 	if (next == _soundEventIndex)
 		return false;
 
-	if (_engineVersion == kEngineVersion3) {
+	if (_engineVersion == 3) {
 		VocQueueEntry1999 &entry = _vocQueue1999[_soundEventMaximum];
 		entry.clearArgumentKeys = (argumentCount & 0x80) != 0;
 		argumentCount &= 0x3F;
@@ -686,7 +671,7 @@ bool ComfyEngine::vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc)
 void ComfyEngine::vocQueuePlayAll() {
 	_mixer->stopHandle(_soundHandle);
 	_soundCues.clear();
-	if (_engineVersion == kEngineVersion3) {
+	if (_engineVersion == 3) {
 		uint16 slot = _soundEventIndex;
 		while (slot != _soundEventMaximum) {
 			VocQueueEntry1999 &entry = _vocQueue1999[slot];
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index d425e25f699..9c498fb6168 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -85,12 +85,6 @@ namespace Comfy {
 
 class MidiPlyrDriver;
 
-enum ComfyEngineVersion {
-	kEngineVersion1, // 1994-1995
-	kEngineVersion2, // 1996-1997
-	kEngineVersion3  // 1999
-};
-
 #ifdef USE_IMGUI
 void onImGuiInit();
 void onImGuiRender();
@@ -343,8 +337,8 @@ private:
 		kScriptDeactivatedRoot
 	};
 
-	const ADGameDescription *_gameDescription;
-	ComfyEngineVersion _engineVersion;
+	const ComfyGameDescription *_game;
+	byte _engineVersion;
 	Common::Path _gameDirectory;
 	Common::Path _introDirectory;
 	Common::Path _gameDataPath;
@@ -852,7 +846,7 @@ protected:
 	Common::Error run() override;
 
 public:
-	ComfyEngine(OSystem *syst, const ADGameDescription *gameDesc);
+	ComfyEngine(OSystem *syst, const ComfyGameDescription *gameDesc);
 	~ComfyEngine() override;
 
 	void setToyKeyboardState(uint32 activeMask, uint32 latchedMask, uint32 holdMask);
diff --git a/engines/comfy/detection.h b/engines/comfy/detection.h
index 78023535eb3..d84513d34f6 100644
--- a/engines/comfy/detection.h
+++ b/engines/comfy/detection.h
@@ -40,15 +40,22 @@ enum ComfyDebugChannels {
 	kDebugScript,
 };
 
+struct ComfyGameDescription {
+	AD_GAME_DESCRIPTION_HELPERS(desc);
+
+	ADGameDescription desc;
+	byte version;
+};
+
 extern const PlainGameDescriptor comfyGames[];
 
-extern const ADGameDescription gameDescriptions[];
+extern const ComfyGameDescription gameDescriptions[];
 
 #define GAMEOPTION_FORCE_LANGUAGE_SETUP GUIO_GAMEOPTIONS1
 
 } // End of namespace Comfy
 
-class ComfyMetaEngineDetection : public AdvancedMetaEngineDetection<ADGameDescription> {
+class ComfyMetaEngineDetection : public AdvancedMetaEngineDetection<Comfy::ComfyGameDescription> {
 	static const DebugChannelDef debugFlagList[];
 
 public:
diff --git a/engines/comfy/detection_tables.h b/engines/comfy/detection_tables.h
index 16ca5eee163..e4fe5146e5b 100644
--- a/engines/comfy/detection_tables.h
+++ b/engines/comfy/detection_tables.h
@@ -33,8 +33,9 @@ const PlainGameDescriptor comfyGames[] = {
 	{ 0, 0 }
 };
 
-const ADGameDescription gameDescriptions[] = {
+const ComfyGameDescription gameDescriptions[] = {
 	{
+		{
 		"comfyland",
 		nullptr,
 		AD_ENTRY3s("COMFY1/ENGLISH/COMFY.OBJ",    "7b4ce03e92a27c2271d3657d3c13084b", 221184,
@@ -44,9 +45,12 @@ const ADGameDescription gameDescriptions[] = {
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		},
+		1
 	},
 
 	{
+		{
 		"comfyland",
 		"1999",
 		AD_ENTRY5s("COMFY1/ENGLISH/COMFY.OBJ",    "8bbeefa3c59c8e80046f35a9202f6095", 221184,
@@ -58,9 +62,12 @@ const ADGameDescription gameDescriptions[] = {
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		},
+		3
 	},
 
 	{
+		{
 		"boo",
 		nullptr,
 		AD_ENTRY3s("BOO/ENGLISH/COMFY.OBJ",    "5d847524a1e1cfce9799a31acca777f3", 301056,
@@ -70,9 +77,12 @@ const ADGameDescription gameDescriptions[] = {
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		},
+		3
 	},
 
 	{
+		{
 		"first",
 		"1999",
 		AD_ENTRY2s("FIRST/ENGLISH/COMFY.OBJ",    "c187ac3fd5d547f59ff18b98a6a2f10b", 43008,
@@ -81,9 +91,12 @@ const ADGameDescription gameDescriptions[] = {
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		},
+		3
 	},
 
 	{
+		{
 		"first",
 		nullptr,
 		AD_ENTRY2s("FIRST/ENGLISH/COMFY.OBJ",    "fe23f262d2282f76488fbe401067a76c", 43008,
@@ -92,9 +105,12 @@ const ADGameDescription gameDescriptions[] = {
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		},
+		2
 	},
 
 	{
+		{
 		"match",
 		nullptr,
 		AD_ENTRY2s("MATCH/ENGLISH/COMFY.OBJ",    "daf2c1e6d3bc019f026edbe5465df13b", 337920,
@@ -103,9 +119,12 @@ const ADGameDescription gameDescriptions[] = {
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		},
+		2
 	},
 
 	{
+		{
 		"colors",
 		nullptr,
 		AD_ENTRY3s("COLORS/ENGLISH/COMFY.OBJ",    "6679b5e35db4c4312d4cb85076403760", 268288,
@@ -115,9 +134,12 @@ const ADGameDescription gameDescriptions[] = {
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		},
+		3
 	},
 
 	{
+		{
 		"concert",
 		nullptr,
 		AD_ENTRY3s("CONCERT/ENGLISH/COMFY.OBJ",    "c060145864e951fc13ba6106e75f4845", 272384,
@@ -127,9 +149,12 @@ const ADGameDescription gameDescriptions[] = {
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		},
+		3
 	},
 
 	{
+		{
 		"friends",
 		nullptr,
 		AD_ENTRY3s("FRIENDS/ENGLISH/COMFY.OBJ",    "d4c620ba375834094b4151ebef862647", 364544,
@@ -139,9 +164,12 @@ const ADGameDescription gameDescriptions[] = {
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		},
+		3
 	},
 
 	{
+		{
 		"panther",
 		nullptr,
 		AD_ENTRY3s("PANTHER/ENGLISH/COMFY.OBJ",    "05420f4122187233112a9dc374303c15", 65536,
@@ -151,9 +179,11 @@ const ADGameDescription gameDescriptions[] = {
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		},
+		3
 	},
 
-	AD_TABLE_END_MARKER
+	{ AD_TABLE_END_MARKER, 0 }
 };
 
 } // End of namespace Comfy
diff --git a/engines/comfy/expr.cpp b/engines/comfy/expr.cpp
index be9988d487b..371f807c84b 100644
--- a/engines/comfy/expr.cpp
+++ b/engines/comfy/expr.cpp
@@ -94,7 +94,7 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 			continue;
 		}
 
-		if (_engineVersion == kEngineVersion3 && opcode >= 0x17 && opcode <= 0x21) {
+		if (_engineVersion == 3 && opcode >= 0x17 && opcode <= 0x21) {
 			uint16 value = 0;
 			bool pushValue = true;
 			if (opcode == 0x17)
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index 32f81a58cd6..e6c1a67a22b 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -74,28 +74,28 @@ static uint16 getLanguageId(const Common::String &directory) {
 }
 
 void ComfyEngine::gameConfigInit() {
-	if (!strcmp(_gameDescription->gameId, "comfyland")) {
+	if (!strcmp(_game->desc.gameId, "comfyland")) {
 		_gameDirectory = Common::Path("COMFY1");
 		_introDirectory = Common::Path("INTRO");
-	} else if (!strcmp(_gameDescription->gameId, "boo")) {
+	} else if (!strcmp(_game->desc.gameId, "boo")) {
 		_gameDirectory = Common::Path("BOO");
 		_introDirectory = Common::Path("FINTRO");
-	} else if (!strcmp(_gameDescription->gameId, "first")) {
+	} else if (!strcmp(_game->desc.gameId, "first")) {
 		_gameDirectory = Common::Path("FIRST");
 		_introDirectory = Common::Path("FINTRO");
-	} else if (!strcmp(_gameDescription->gameId, "match")) {
+	} else if (!strcmp(_game->desc.gameId, "match")) {
 		_gameDirectory = Common::Path("MATCH");
 		_introDirectory = Common::Path("MINTRO");
-	} else if (!strcmp(_gameDescription->gameId, "colors")) {
+	} else if (!strcmp(_game->desc.gameId, "colors")) {
 		_gameDirectory = Common::Path("COLORS");
 		_introDirectory = Common::Path("INTRO");
-	} else if (!strcmp(_gameDescription->gameId, "concert")) {
+	} else if (!strcmp(_game->desc.gameId, "concert")) {
 		_gameDirectory = Common::Path("CONCERT");
 		_introDirectory = Common::Path("INTRO");
-	} else if (!strcmp(_gameDescription->gameId, "friends")) {
+	} else if (!strcmp(_game->desc.gameId, "friends")) {
 		_gameDirectory = Common::Path("FRIENDS");
 		_introDirectory = Common::Path("INTRO");
-	} else if (!strcmp(_gameDescription->gameId, "panther")) {
+	} else if (!strcmp(_game->desc.gameId, "panther")) {
 		_gameDirectory = Common::Path("PANTHER");
 		_introDirectory.clear(); // No intro
 	}
@@ -381,10 +381,10 @@ bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16
 
 	uint32 stringBytes = _stringTable.size() * sizeof(uint16);
 	uint32 handleBytes = _sceneHandles.size() * sizeof(uint16);
-	uint32 actorBytes = _actors.size() * (_engineVersion == kEngineVersion3 ? COMFY_ACTOR_SIZE_V3 : COMFY_ACTOR_SIZE);
+	uint32 actorBytes = _actors.size() * (_engineVersion == 3 ? COMFY_ACTOR_SIZE_V3 : COMFY_ACTOR_SIZE);
 	uint32 keyBytes = ((uint32)keyBitCount + 1) / 8 + 1;
 	_sceneMidiInstanceOffset = 0;
-	if (_engineVersion == kEngineVersion3) {
+	if (_engineVersion == 3) {
 		_sceneEntryListOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES + COMFY_SCENE_VOC_STATE_BYTES_V3 +
 				COMFY_ANM_STATE_BYTES;
 		_sceneActorPcOffset = _sceneEntryListOffset + COMFY_SCENE_STATE_BYTES_V3;
@@ -398,7 +398,7 @@ bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16
 	_sceneHandlesOffset = _sceneStringTableOffset + stringBytes;
 	_sceneActorsOffset = _sceneHandlesOffset + handleBytes;
 	_sceneKeyBitsOffset = _sceneActorsOffset + actorBytes;
-	_sceneAnimStateOffset = _engineVersion == kEngineVersion3 ?
+	_sceneAnimStateOffset = _engineVersion == 3 ?
 			COMFY_SCENE_MIDI_INSTANCE_BYTES + COMFY_SCENE_VOC_STATE_BYTES_V3 : _sceneKeyBitsOffset + keyBytes;
 	uint32 sceneBytes = assetsAlignEven32(_sceneKeyBitsOffset + keyBytes);
 	_sceneMemoryBlock.resize(sceneBytes);
@@ -408,7 +408,7 @@ bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16
 	_envNumSprites = numSprites;
 	_activeSceneCount = handleCount;
 
-	if (_engineVersion == kEngineVersion3) {
+	if (_engineVersion == 3) {
 		midiInitInstanceAt();
 		if (!soundInit())
 			return false;
@@ -439,7 +439,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 		return false;
 	}
 
-	if (_engineVersion != kEngineVersion3 && !soundInit())
+	if (_engineVersion != 3 && !soundInit())
 		return false;
 
 	_picFileMapped = true;
@@ -485,7 +485,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	for (uint i = 0; i < _spriteResources.size(); i++)
 		spriteInvalidateHostCache(_spriteResources[i]);
 
-	if (_engineVersion != kEngineVersion3 && _usesAnimFile && !animFileOpen())
+	if (_engineVersion != 3 && _usesAnimFile && !animFileOpen())
 		return false;
 
 	if (_usesAnimFile) {
@@ -493,7 +493,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 		memset(&_animFrameBuffer[0], 0, _animFrameBuffer.size());
 	}
 
-	uint32 xmsLimit = _engineVersion == kEngineVersion3 ? 0x7D000 : 0x0800 << 10;
+	uint32 xmsLimit = _engineVersion == 3 ? 0x7D000 : 0x0800 << 10;
 	_scenePoolSize = xmsLimit > budget ? xmsLimit - budget : 0;
 	_scenePoolSize &= 0xFFFFFFFE;
 	_scenePoolData.resize(_scenePoolSize);
@@ -502,7 +502,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 
 	_scenePoolCursor = 0;
 	_scenePoolEvictCursor = 0;
-	if (_engineVersion != kEngineVersion3 && _scenePoolSize >= 2)
+	if (_engineVersion != 3 && _scenePoolSize >= 2)
 		WRITE_LE_UINT16(&_scenePoolData[0], 0x8000);
 
 	uint32 xmsOffset = 0;
@@ -557,7 +557,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 }
 
 void ComfyEngine::assetsUnload(byte freeAudio) {
-	if (_engineVersion == kEngineVersion3) {
+	if (_engineVersion == 3) {
 		_objectCacheEntries.clear();
 		_frameCacheEntries.clear();
 		_scenePoolData.clear();
diff --git a/engines/comfy/input.cpp b/engines/comfy/input.cpp
index df80c3f8150..b29b727fa71 100644
--- a/engines/comfy/input.cpp
+++ b/engines/comfy/input.cpp
@@ -88,7 +88,7 @@ void ComfyEngine::lptKeyToFlags(uint16 key) {
 			flags |= 0x10;
 			break;
 		case 27:
-			if (_engineVersion == kEngineVersion3 && (_inputDeviceMode == 2 || _inputDeviceMode == 4) &&
+			if (_engineVersion == 3 && (_inputDeviceMode == 2 || _inputDeviceMode == 4) &&
 					!_inputKeyboardBit7Held)
 				_inputKeyboardResetRequested = true;
 			else
@@ -113,7 +113,7 @@ void ComfyEngine::hostKeyboardResetMap() {
 }
 
 bool ComfyEngine::hostKeyboardLoadDatMap() {
-	if (_engineVersion == kEngineVersion3 && _inputDeviceMode == 1)
+	if (_engineVersion == 3 && _inputDeviceMode == 1)
 		return true;
 
 	hostKeyboardResetMap();
@@ -218,14 +218,14 @@ uint32 ComfyEngine::lptKeyboardScan() {
 	// iterations after each write, and sampled three bits from the status port. Concatenating those
 	// eight 3-bit samples produced the 24-contact scan word. ScummVM supplies that same word from the
 	// keymapper, KEYBOARD.DAT mappings, and the toy-keyboard UI instead of accessing an I/O port.
-	if (_engineVersion == kEngineVersion3 && _inputDeviceMode == 2) {
+	if (_engineVersion == 3 && _inputDeviceMode == 2) {
 		_keyboardActiveMask |= _keymapperActiveMask;
 		_keyboardLatchedMask |= _keymapperLatchedMask;
 		_keymapperActiveMask = 0;
 		_keymapperLatchedMask = 0;
 	}
 
-	if (_engineVersion == kEngineVersion3) {
+	if (_engineVersion == 3) {
 		if (_inputKeyboardResetRequested) {
 			_inputKeyboardResetRequested = false;
 			_inputKeyboardSyntheticBit7 = false;
@@ -272,15 +272,15 @@ uint32 ComfyEngine::lptKeyboardScan() {
 	uint32 comfyboardState = (_toyKeyboardActiveMask | _toyKeyboardHoldMask |
 		_toyKeyboardLatchedMask) & 0x00FFFFFF;
 	uint32 comfyboardHostState = (comfyboardState | _keymapperActiveMask | _keymapperLatchedMask) & 0x00FFFFFF;
-	if (_engineVersion == kEngineVersion3 && _midiPlyrDriver) {
+	if (_engineVersion == 3 && _midiPlyrDriver) {
 		_midiPlyrDriver->comfyboardSetHostButtons(comfyboardHostState);
 		comfyboardState |= _midiPlyrDriver->comfyboardGetButtons() & 0x00FFFFFF;
 	}
 
-	if (_engineVersion != kEngineVersion3 || _inputDeviceMode != 1)
+	if (_engineVersion != 3 || _inputDeviceMode != 1)
 		keyboardState |= _keymapperActiveMask | _keymapperLatchedMask;
 
-	if (_engineVersion == kEngineVersion3 && !_inputDeviceMode) {
+	if (_engineVersion == 3 && !_inputDeviceMode) {
 		_inputDeviceMode = inputDetectDevice(comfyboardState, keyboardState);
 		if (_inputDeviceMode == 1 && _midiPlyrDriver) {
 			_midiPlyrDriver->comfyboardStopSleepUse();
@@ -291,11 +291,11 @@ uint32 ComfyEngine::lptKeyboardScan() {
 	}
 
 	uint32 scanState;
-	if (_engineVersion == kEngineVersion3 && _inputDeviceMode == 1)
+	if (_engineVersion == 3 && _inputDeviceMode == 1)
 		scanState = comfyboardState;
-	else if (_engineVersion == kEngineVersion3 && _inputDeviceMode == 2)
+	else if (_engineVersion == 3 && _inputDeviceMode == 2)
 		scanState = keyboardState | (_inputKeyboardBit7Held ? 0x80 : 0);
-	else if (_engineVersion == kEngineVersion3 && (_inputDeviceMode == 3 || _inputDeviceMode == 4)) {
+	else if (_engineVersion == 3 && (_inputDeviceMode == 3 || _inputDeviceMode == 4)) {
 		// Modes 3 and 4 used WinMM MIDI input. ScummVM supplies their logical contacts through the keymapper/UI.
 		scanState = (_toyKeyboardActiveMask | _toyKeyboardHoldMask | _toyKeyboardLatchedMask |
 				_keymapperActiveMask | _keymapperLatchedMask) & 0x00FFFFFF;
@@ -304,7 +304,7 @@ uint32 ComfyEngine::lptKeyboardScan() {
 			if (_inputKeyboardSyntheticBit7)
 				scanState |= 0x80;
 		}
-	} else if (_engineVersion == kEngineVersion3 && !_inputDeviceMode) {
+	} else if (_engineVersion == 3 && !_inputDeviceMode) {
 		if (_inputComfyboardSuppressBit1)
 			comfyboardState &= ~0x02;
 
@@ -316,7 +316,7 @@ uint32 ComfyEngine::lptKeyboardScan() {
 		scanState = comfyboardState | keyboardState;
 	}
 
-	if (_engineVersion == kEngineVersion3)
+	if (_engineVersion == 3)
 		_inputKeyboardBit7Held = (scanState & 0x80) != 0;
 
 	_keyboardActiveMask &= ~_keyboardLatchedMask;
@@ -422,7 +422,7 @@ void ComfyEngine::lptKeyboardDispatchEvents(uint32 scanState) {
 void ComfyEngine::lptKeyboardInit() {
 	_inputInitialDeviceMode = _inputDeviceMode;
 	_keyboardUiVisible = true;
-	if (_engineVersion == kEngineVersion3 && _midiPlyrDriver &&
+	if (_engineVersion == 3 && _midiPlyrDriver &&
 			(_inputDeviceMode == 0 || _inputDeviceMode == 1)) {
 		if (!_inputDeviceMode)
 			_midiPlyrDriver->comfyboardStartSleepUse();
@@ -437,7 +437,7 @@ void ComfyEngine::lptKeyboardScanAndProcess() {
 }
 
 void ComfyEngine::lptKeyboardShutdown() {
-	if (_engineVersion == kEngineVersion3 && _midiPlyrDriver &&
+	if (_engineVersion == 3 && _midiPlyrDriver &&
 			(_inputInitialDeviceMode == 0 || _inputInitialDeviceMode == 1)) {
 		_midiPlyrDriver->comfyboardStopReading();
 		_midiPlyrDriver->comfyboardStopSleepUse();
diff --git a/engines/comfy/metaengine.cpp b/engines/comfy/metaengine.cpp
index 3fa84479f17..e3782fc1da6 100644
--- a/engines/comfy/metaengine.cpp
+++ b/engines/comfy/metaengine.cpp
@@ -55,7 +55,7 @@ const ADExtraGuiOptionsMap *ComfyMetaEngine::getAdvancedExtraGuiOptions() const
 	return Comfy::optionsList;
 }
 
-Common::Error ComfyMetaEngine::createInstance(OSystem *syst, Engine **engine, const ADGameDescription *desc) const {
+Common::Error ComfyMetaEngine::createInstance(OSystem *syst, Engine **engine, const Comfy::ComfyGameDescription *desc) const {
 	*engine = new Comfy::ComfyEngine(syst, desc);
 	return Common::kNoError;
 }
diff --git a/engines/comfy/metaengine.h b/engines/comfy/metaengine.h
index 2aa0f0aaa59..806d34be914 100644
--- a/engines/comfy/metaengine.h
+++ b/engines/comfy/metaengine.h
@@ -22,13 +22,13 @@
 #ifndef COMFY_METAENGINE_H
 #define COMFY_METAENGINE_H
 
-#include "engines/advancedDetector.h"
+#include "comfy/detection.h"
 
-class ComfyMetaEngine : public AdvancedMetaEngine<ADGameDescription> {
+class ComfyMetaEngine : public AdvancedMetaEngine<Comfy::ComfyGameDescription> {
 public:
 	const char *getName() const override;
 
-	Common::Error createInstance(OSystem *syst, Engine **engine, const ADGameDescription *desc) const override;
+	Common::Error createInstance(OSystem *syst, Engine **engine, const Comfy::ComfyGameDescription *desc) const override;
 
 	/**
 	 * Determine whether the engine supports the specified MetaEngine feature.
diff --git a/engines/comfy/midi.cpp b/engines/comfy/midi.cpp
index 4d7ee05745f..b3dd40578db 100644
--- a/engines/comfy/midi.cpp
+++ b/engines/comfy/midi.cpp
@@ -55,7 +55,7 @@ uint16 ComfyEngine::midiTick() {
 		return 0;
 
 	uint32 previousCounter = _midiInstanceEventTime;
-	if (_engineVersion == kEngineVersion3) {
+	if (_engineVersion == 3) {
 		int16 adjustment = midiGetCounterAdjustment();
 		if (adjustment) {
 			_midiPlyrDriver->setVocCounter((uint32)((int32)_midiPlyrDriver->getVocCounter() + adjustment));
@@ -65,16 +65,16 @@ uint16 ComfyEngine::midiTick() {
 
 	do {
 		_midiTimeCounter = _midiPlyrDriver->getTimeCounter();
-		if ((_engineVersion == kEngineVersion3 && _midiTimeCounter <= previousCounter) ||
-				(_engineVersion != kEngineVersion3 && _midiTimeCounter == previousCounter)) {
+		if ((_engineVersion == 3 && _midiTimeCounter <= previousCounter) ||
+				(_engineVersion != 3 && _midiTimeCounter == previousCounter)) {
 			processEvents();
 			if (shouldQuit())
 				return 0;
 
 			_system->delayMillis(1);
 		}
-	} while ((_engineVersion == kEngineVersion3 && _midiTimeCounter <= previousCounter) ||
-		(_engineVersion != kEngineVersion3 && _midiTimeCounter == previousCounter));
+	} while ((_engineVersion == 3 && _midiTimeCounter <= previousCounter) ||
+		(_engineVersion != 3 && _midiTimeCounter == previousCounter));
 
 	_midiInstanceEventTime = _midiTimeCounter;
 	_midiEventBaseTime = (int32)_midiInstanceEventTime;
@@ -128,7 +128,7 @@ bool ComfyEngine::midiPlyrStart() {
 		return false;
 
 	midiPlyrStop();
-	MidiPlyrDriver::DriverVersion version = _engineVersion == kEngineVersion3 ?
+	MidiPlyrDriver::DriverVersion version = _engineVersion == 3 ?
 		MidiPlyrDriver::kDriverVersion2 : MidiPlyrDriver::kDriverVersion1;
 	_midiPlyrDriver = new MidiPlyrDriver(version);
 	if (!_midiPlyrDriver->musicStart(flags)) {
@@ -212,7 +212,7 @@ void ComfyEngine::midiInitInstanceAt() {
 }
 
 void ComfyEngine::midiInitInstance() {
-	if (_engineVersion == kEngineVersion3) {
+	if (_engineVersion == 3) {
 		_midiTracks.nextTime = 0;
 		_midiTracks.nextIndex = 0x03E7;
 		_midiEvents.nextTime = 0;
@@ -245,7 +245,7 @@ void ComfyEngine::midiInitChannels() {
 		state.volumeCurrent = state.volumeDefault = 0x6400;
 		state.rateCurrent = state.rateDefault = 0x07D0;
 		state.pitchCurrent = state.pitchDefault = 0x1388;
-		if (_engineVersion != kEngineVersion3) {
+		if (_engineVersion != 3) {
 			state.volumeTarget = state.volumeDefault;
 			state.rateTarget = state.rateDefault;
 			state.pitchTarget = state.pitchDefault;
diff --git a/engines/comfy/palette.cpp b/engines/comfy/palette.cpp
index 99e91a3c2dc..b7c68e976c5 100644
--- a/engines/comfy/palette.cpp
+++ b/engines/comfy/palette.cpp
@@ -49,7 +49,7 @@ void ComfyEngine::colorDatReadEntry(uint16 paletteId) {
 	if (_colorDatStream->read(_paletteTarget, COMFY_PALETTE_BYTES) != COMFY_PALETTE_BYTES)
 		error("COLORS.DAT is truncated while reading palette %u", (uint)paletteId);
 
-	if (_engineVersion == kEngineVersion3) {
+	if (_engineVersion == 3) {
 		// Version 3 forces color 0 to black immediately after reading the palette...
 		_paletteTarget[0] = 0;
 		_paletteTarget[1] = 0;
@@ -93,7 +93,7 @@ void ComfyEngine::paletteFadeStep(uint16 delta) {
 
 void ComfyEngine::paletteLoadWithFade(uint16 paletteId, uint16 fadeTicks) {
 	colorDatReadEntry(paletteId);
-	if (_engineVersion != kEngineVersion3)
+	if (_engineVersion != 3)
 		_palettePage = 'S';
 
 	if (_paletteFading)
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index 87c31d34318..79c83b2f729 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -50,7 +50,7 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 	WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x184], _midiInstanceTrackBase);
 	WRITE_LE_UINT16(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x188], _midiEvents.count);
 	WRITE_LE_UINT16(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x18A], _midiTracks.count);
-	if (_engineVersion == kEngineVersion3) {
+	if (_engineVersion == 3) {
 		byte *vocState = &_sceneMemoryBlock[_sceneMidiInstanceOffset + COMFY_SCENE_MIDI_INSTANCE_BYTES];
 		vocState[0] = _wcomfy99VocState0;
 		vocState[1] = _wcomfy99VocState1;
@@ -80,14 +80,14 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 	for (uint i = 0; i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
 		WRITE_LE_UINT16(sceneEntries + 5 + i * 2, (uint16)_sceneEntryOffsets[i]);
 
-	if (_engineVersion == kEngineVersion3) {
+	if (_engineVersion == 3) {
 		for (uint channel = 0; channel < COMFY_SCENE_MUSIC_CHANNEL_COUNT; channel++) {
 			WRITE_LE_UINT16(sceneEntries + 0x25 + channel * 2, _sceneEntryVolumes[channel]);
 			WRITE_LE_UINT16(sceneEntries + 0x31 + channel * 2, _sceneEntryCompletionKeys[channel]);
 		}
 	}
 
-	uint32 channelTableOffset = _engineVersion == kEngineVersion3 ? 0x3D : 0x25;
+	uint32 channelTableOffset = _engineVersion == 3 ? 0x3D : 0x25;
 	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
 		MidiChannelState &state = _midiChannels[channel];
 		byte *packed = sceneEntries + channelTableOffset + channel * 0xA1;
@@ -122,7 +122,7 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 	if (!_sceneHandles.empty())
 		memcpy(&_sceneMemoryBlock[_sceneHandlesOffset], &_sceneHandles[0], _sceneHandles.size() * sizeof(uint16));
 
-	uint32 actorStride = _engineVersion == kEngineVersion3 ? COMFY_ACTOR_SIZE_V3 : sizeof(Actor);
+	uint32 actorStride = _engineVersion == 3 ? COMFY_ACTOR_SIZE_V3 : sizeof(Actor);
 	for (uint i = 0; i < _actors.size(); i++)
 		memcpy(&_sceneMemoryBlock[_sceneActorsOffset + i * actorStride], &_actors[i], sizeof(Actor));
 
@@ -179,7 +179,7 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 	_midiTracks.baseTime = _midiInstanceTrackBase;
 	midiFindNext(_midiEvents);
 	midiFindNext(_midiTracks);
-	if (_engineVersion == kEngineVersion3) {
+	if (_engineVersion == 3) {
 		byte *vocState = &_sceneMemoryBlock[_sceneMidiInstanceOffset + COMFY_SCENE_MIDI_INSTANCE_BYTES];
 		_wcomfy99VocState0 = vocState[0];
 		_wcomfy99VocState1 = vocState[1];
@@ -209,14 +209,14 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 	for (uint i = 0; i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
 		_sceneEntryOffsets[i] = READ_LE_UINT16(sceneEntries + 5 + i * 2);
 
-	if (_engineVersion == kEngineVersion3) {
+	if (_engineVersion == 3) {
 		for (uint channel = 0; channel < COMFY_SCENE_MUSIC_CHANNEL_COUNT; channel++) {
 			_sceneEntryVolumes[channel] = READ_LE_UINT16(sceneEntries + 0x25 + channel * 2);
 			_sceneEntryCompletionKeys[channel] = READ_LE_UINT16(sceneEntries + 0x31 + channel * 2);
 		}
 	}
 
-	uint32 channelTableOffset = _engineVersion == kEngineVersion3 ? 0x3D : 0x25;
+	uint32 channelTableOffset = _engineVersion == 3 ? 0x3D : 0x25;
 	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
 		MidiChannelState &state = _midiChannels[channel];
 		byte *packed = sceneEntries + channelTableOffset + channel * 0xA1;
@@ -246,7 +246,7 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 	memcpy(_actorPcTable, &_sceneMemoryBlock[_sceneActorPcOffset], sizeof(_actorPcTable));
 	memcpy(&_stringTable[0], &_sceneMemoryBlock[_sceneStringTableOffset], _stringTable.size() * sizeof(uint16));
 	memcpy(&_sceneHandles[0], &_sceneMemoryBlock[_sceneHandlesOffset], _sceneHandles.size() * sizeof(uint16));
-	uint32 actorStride = _engineVersion == kEngineVersion3 ? COMFY_ACTOR_SIZE_V3 : sizeof(Actor);
+	uint32 actorStride = _engineVersion == 3 ? COMFY_ACTOR_SIZE_V3 : sizeof(Actor);
 	for (uint i = 0; i < _actors.size(); i++)
 		memcpy(&_actors[i], &_sceneMemoryBlock[_sceneActorsOffset + i * actorStride], sizeof(Actor));
 	if (_keyBits && _keyBitsSize)
@@ -263,12 +263,12 @@ void ComfyEngine::sceneGoto(uint16 count) {
 
 	_sceneEntryListActive = true;
 	_sceneEntryCount = count;
-	uint32 frameSize = _engineVersion == kEngineVersion3 ? COMFY_SCENE_FRAME_BYTES_V3 : COMFY_SCENE_FRAME_BYTES;
+	uint32 frameSize = _engineVersion == 3 ? COMFY_SCENE_FRAME_BYTES_V3 : COMFY_SCENE_FRAME_BYTES;
 	_sceneEntryFrameSize = count ? frameSize / (int16)count : 0;
 	for (uint i = 0; i < count && i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
 		_sceneEntryOffsets[i] = 0xFFFF;
 
-	if (_engineVersion == kEngineVersion3) {
+	if (_engineVersion == 3) {
 		for (uint channel = 0; channel < COMFY_SCENE_MUSIC_CHANNEL_COUNT; channel++) {
 			_sceneEntryVolumes[channel] = 100;
 			_sceneEntryCompletionKeys[channel] = 0;
@@ -384,7 +384,7 @@ void ComfyEngine::midiPlaySongAtFrame(uint16 channel, uint16 frame) {
 		return;
 
 	_midiPlyrDriver->musicPlaySong(song, size, channel);
-	if (_engineVersion == kEngineVersion3) {
+	if (_engineVersion == 3) {
 		_midiPlyrDriver->musicSetVolume(_sceneEntryVolumes[channel], channel);
 		_sceneEntryCompletionKeys[channel] = 0;
 	} else {
@@ -405,7 +405,7 @@ bool ComfyEngine::sceneOpen(uint32 sceneEntryListOffset) {
 	_sceneEntryListOffset = sceneEntryListOffset;
 	_sceneEntryListActive = false;
 	_sceneEntryCount = 0;
-	uint32 frameSize = _engineVersion == kEngineVersion3 ? COMFY_SCENE_FRAME_BYTES_V3 : COMFY_SCENE_FRAME_BYTES;
+	uint32 frameSize = _engineVersion == 3 ? COMFY_SCENE_FRAME_BYTES_V3 : COMFY_SCENE_FRAME_BYTES;
 	_sceneEntryFrameSize = frameSize;
 	if (_sceneFrameData.empty()) {
 		_sceneFrameData.resize(frameSize);
@@ -417,7 +417,7 @@ bool ComfyEngine::sceneOpen(uint32 sceneEntryListOffset) {
 
 	_sceneOpen = true;
 	memset(_sceneEntryOffsets, 0, sizeof(_sceneEntryOffsets));
-	if (_engineVersion != kEngineVersion3)
+	if (_engineVersion != 3)
 		midiInitInstance();
 
 	midiInitChannels();
@@ -430,7 +430,7 @@ void ComfyEngine::sceneShutdown() {
 
 	midiPlyrStop();
 	_sceneFrameData.clear();
-	if (_engineVersion == kEngineVersion3) {
+	if (_engineVersion == 3) {
 		_wcomfy99VocState2 = 0xFF;
 		_wcomfy99VocState3 = 0xFF;
 	}
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 9e3ce24cd40..1fa1d626eeb 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -348,7 +348,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			midiStopAndRemove(channel);
 		} else if (subop == 6 && channel < COMFY_MIDI_CHANNEL_COUNT) {
 			midiStopAndFireKeys(channel);
-		} else if ((subop == 7 || subop == 8) && _engineVersion == kEngineVersion3 &&
+		} else if ((subop == 7 || subop == 8) && _engineVersion == 3 &&
 				channel < COMFY_MIDI_CHANNEL_COUNT && _midiPlyrDriver) {
 			_midiPlyrDriver->musicSetLoop(subop == 7 ? 1 : 0, channel);
 		}


Commit: 4ae2db18376798fe053fc023c9d5376e98df1c45
    https://github.com/scummvm/scummvm/commit/4ae2db18376798fe053fc023c9d5376e98df1c45
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Fix engine version for one of the entries

Changed paths:
    engines/comfy/detection_tables.h


diff --git a/engines/comfy/detection_tables.h b/engines/comfy/detection_tables.h
index e4fe5146e5b..bd69bb16a26 100644
--- a/engines/comfy/detection_tables.h
+++ b/engines/comfy/detection_tables.h
@@ -106,7 +106,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 		},
-		2
+		1
 	},
 
 	{


Commit: e5539f1e847edb3f32551d4971b019d18ff5b142
    https://github.com/scummvm/scummvm/commit/e5539f1e847edb3f32551d4971b019d18ff5b142
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Script and engine version fixes

Changed paths:
    engines/comfy/comfy.h
    engines/comfy/detection.h
    engines/comfy/detection_tables.h
    engines/comfy/expr.cpp
    engines/comfy/game.cpp
    engines/comfy/scene.cpp
    engines/comfy/script_vm.cpp


diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 9c498fb6168..25452bb07cb 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -331,7 +331,6 @@ private:
 	};
 
 	enum ScriptDispatchStatus {
-		kScriptUnhandled,
 		kScriptContinue,
 		kScriptYield,
 		kScriptDeactivatedRoot
diff --git a/engines/comfy/detection.h b/engines/comfy/detection.h
index d84513d34f6..4baa9c89c99 100644
--- a/engines/comfy/detection.h
+++ b/engines/comfy/detection.h
@@ -45,8 +45,13 @@ struct ComfyGameDescription {
 
 	ADGameDescription desc;
 	byte version;
+	byte scriptFeatures;
 };
 
+#define COMFY_SCRIPT_OPCODE_31 (1 << 0)
+#define COMFY_SCRIPT_OPCODE_32 (1 << 1)
+#define COMFY_SCRIPT_OPCODE_33 (1 << 2)
+
 extern const PlainGameDescriptor comfyGames[];
 
 extern const ComfyGameDescription gameDescriptions[];
diff --git a/engines/comfy/detection_tables.h b/engines/comfy/detection_tables.h
index bd69bb16a26..96231033a6a 100644
--- a/engines/comfy/detection_tables.h
+++ b/engines/comfy/detection_tables.h
@@ -46,7 +46,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 		},
-		1
+		1,
+		0
 	},
 
 	{
@@ -63,7 +64,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 		},
-		3
+		3,
+		0
 	},
 
 	{
@@ -78,13 +80,14 @@ const ComfyGameDescription gameDescriptions[] = {
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 		},
-		3
+		2,
+		COMFY_SCRIPT_OPCODE_31
 	},
 
 	{
 		{
 		"first",
-		"1999",
+		"1997",
 		AD_ENTRY2s("FIRST/ENGLISH/COMFY.OBJ",    "c187ac3fd5d547f59ff18b98a6a2f10b", 43008,
 				   "FIRST/ENGLISH/MIDIFILE.DAT", "4ab6c35308ed504a8abb96ae3fe81fe4", 1232),
 		Common::UNK_LANG,
@@ -92,7 +95,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 		},
-		3
+		2,
+		COMFY_SCRIPT_OPCODE_31 | COMFY_SCRIPT_OPCODE_33
 	},
 
 	{
@@ -106,7 +110,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 		},
-		1
+		1,
+		0
 	},
 
 	{
@@ -120,7 +125,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 		},
-		2
+		2,
+		0
 	},
 
 	{
@@ -135,7 +141,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 		},
-		3
+		3,
+		0
 	},
 
 	{
@@ -150,7 +157,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 		},
-		3
+		3,
+		0
 	},
 
 	{
@@ -165,7 +173,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 		},
-		3
+		3,
+		0
 	},
 
 	{
@@ -180,10 +189,11 @@ const ComfyGameDescription gameDescriptions[] = {
 		ADGF_UNSTABLE,
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 		},
-		3
+		2,
+		COMFY_SCRIPT_OPCODE_31 | COMFY_SCRIPT_OPCODE_32
 	},
 
-	{ AD_TABLE_END_MARKER, 0 }
+	{ AD_TABLE_END_MARKER, 0, 0 }
 };
 
 } // End of namespace Comfy
diff --git a/engines/comfy/expr.cpp b/engines/comfy/expr.cpp
index 371f807c84b..61e3bd77b0d 100644
--- a/engines/comfy/expr.cpp
+++ b/engines/comfy/expr.cpp
@@ -148,7 +148,7 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 		}
 
 		if (opcode != 0x08 && opcode != 0x09 && opcode != 0x0A && opcode != 0x0B && opcode != 0x0E)
-			continue;
+			error("Unknown expression opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
 
 		if (_exprStackTop < 2) {
 			_exprStackTop = 0;
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index e6c1a67a22b..15b1ecc92c7 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -64,6 +64,9 @@ static uint16 getLanguageId(const Common::String &directory) {
 	if (directory.equalsIgnoreCase("SWEDISH"))
 		return 12;
 
+	if (directory.equalsIgnoreCase("FINISH") || directory.equalsIgnoreCase("FINNISH"))
+		return 13;
+
 	if (directory.equalsIgnoreCase("JAPANESE"))
 		return 14;
 
@@ -146,6 +149,12 @@ void ComfyEngine::findLanguageDirectories() {
 		}
 	}
 
+	for (uint language = 1; language < ARRAYSIZE(_languageDirectories); language++) {
+		Common::String key = Common::String::format("language%u", language);
+		ConfMan.set(key, _languageDirectories[language].empty() ? "?????" :
+			_languageDirectories[language].toString());
+	}
+
 	_multiLanguage = languageCount > 1;
 }
 
@@ -549,8 +558,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	_activeSceneCount = _resourceHandleCount;
 	_sceneEntryCount = 0;
 	_sceneEntryFrameSize = 0;
-	Common::ScopedPtr<Common::SeekableReadStream> message(pathFOpen(Common::Path("MESSAGE"), true));
-	_usesWcomfy99ScriptOps = (bool)message;
+	_usesWcomfy99ScriptOps = _engineVersion == 3;
 	_scriptFault = false;
 
 	return true;
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index 79c83b2f729..a271ac3ea5d 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -129,7 +129,7 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 	if (_keyBits && _keyBitsSize)
 		memcpy(&_sceneMemoryBlock[_sceneKeyBitsOffset], _keyBits, _keyBitsSize);
 
-	if (_usesAnimFile)
+	if (_engineVersion == 3 && _usesAnimFile)
 		animFilePackState(&_sceneMemoryBlock[_sceneAnimStateOffset]);
 }
 
@@ -252,7 +252,7 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 	if (_keyBits && _keyBitsSize)
 		memcpy(_keyBits, &_sceneMemoryBlock[_sceneKeyBitsOffset], _keyBitsSize);
 
-	if (_usesAnimFile)
+	if (_engineVersion == 3 && _usesAnimFile)
 		animFileUnpackState(&_sceneMemoryBlock[_sceneAnimStateOffset]);
 
 }
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 1fa1d626eeb..300633d515e 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -28,7 +28,9 @@
 namespace Comfy {
 
 ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte opcode, uint32 &pc) {
-	if (opcode == 0x01 || opcode == 0x02) {
+	switch (opcode) {
+	case 0x01:
+	case 0x02: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		pc += 2;
 		int16 x = scriptReadStringIndex(pc);
@@ -37,12 +39,12 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		pc += 2;
 		byte randomize = scriptReadByte(pc++);
 		if (!target)
-			return kScriptUnhandled;
+			error("Script opcode 0x%02X resolved an invalid actor", opcode);
 
 		if ((opcode == 0x01 && x == (int16)0xF830) || (opcode == 0x02 && x == (int16)0x8AD0)) {
 			Actor *other = actorResolve((uint16)y, _currentActor);
 			if (!other)
-				return kScriptUnhandled;
+				error("Script opcode 0x%02X resolved an invalid reference actor", opcode);
 
 			x = (int16)((int32)actorReadU32(*other, kActorXFixed) >> 12);
 			y = (int16)((int32)actorReadU32(*other, kActorYFixed) >> 12);
@@ -75,7 +77,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x03) {
+	case 0x03: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		pc += 2;
 		uint16 frame = scriptReadStringIndex(pc);
@@ -86,7 +88,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x04) {
+	case 0x04: {
 		uint16 key = scriptReadWord(pc);
 		if (key && !keyBitTest(key)) {
 			pc--;
@@ -97,7 +99,8 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x05 || opcode == 0x19) {
+	case 0x05:
+	case 0x19: {
 		uint16 key = scriptReadWord(pc);
 		byte state = scriptReadByte(pc + 2);
 		uint32 targetPc = scriptReadDword(pc + 3);
@@ -112,7 +115,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x06) {
+	case 0x06: {
 		uint16 key = scriptReadWord(pc);
 		byte state = scriptReadByte(pc + 2);
 		pc += 3;
@@ -124,11 +127,11 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x07) {
+	case 0x07: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		pc += 2;
 		if (!target)
-			return kScriptUnhandled;
+			error("Script opcode 0x07 resolved an invalid actor");
 
 		bool current = target == &actor;
 		uint16 actorIndex = (uint16)(target - &_actors[0]);
@@ -138,7 +141,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return current ? kScriptYield : kScriptContinue;
 	}
 
-	if (opcode == 0x08) {
+	case 0x08: {
 		uint16 sceneSlot = scriptReadWord(pc);
 		uint16 parentSlot = scriptReadWord(pc + 2);
 		byte flags = scriptReadByte(pc + 4);
@@ -157,56 +160,78 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x09) {
+	case 0x09: {
 		actorSetFrame((int16)scriptReadWord(pc));
 		pc += 2;
 		return kScriptContinue;
 	}
 
-	if (opcode >= 0x0A && opcode <= 0x0D) {
+	case 0x0A:
+	case 0x0B:
+	case 0x0C:
+	case 0x0D: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		pc += 2;
 		if (!target)
-			return kScriptUnhandled;
+			error("Script opcode 0x%02X resolved an invalid actor", opcode);
 
-		if (opcode == 0x0A)
+		switch (opcode) {
+		case 0x0A:
 			actorWriteU8(*target, kActorVisible, 1);
-		else if (opcode == 0x0B)
+			break;
+		case 0x0B:
 			actorWriteU8(*target, kActorVisible, 0);
-		else if (opcode == 0x0C)
+			break;
+		case 0x0C:
 			actorWriteU8(*target, kActorActive, 1);
-		else {
+			break;
+		case 0x0D:
 			actorWriteU16(*target, kActorMoveTicks, 0);
 			actorWriteU8(*target, kActorActive, 0);
 			if (target == &actor)
 				return kScriptYield;
+
+			break;
+		default:
+			break;
 		}
 
 		return kScriptContinue;
 	}
 
-	if (opcode >= 0x0E && opcode <= 0x11) {
+	case 0x0E:
+	case 0x0F:
+	case 0x10:
+	case 0x11: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		int16 expected = scriptReadWord(pc + 2);
 		uint16 key = scriptReadWord(pc + 4);
 		byte mode = scriptReadByte(pc + 6);
 		pc += 7;
 		if (!target)
-			return kScriptUnhandled;
+			error("Script opcode 0x%02X resolved an invalid actor", opcode);
 
 		int16 actual = (int32)actorReadU32(*target, opcode == 0x0E || opcode == 0x10 ? kActorXFixed : kActorYFixed) >> 12;
 		bool matched = ((mode & 2) && expected == actual) || ((mode & 4) && expected < actual) || ((mode & 1) && expected > actual);
 		if (matched) {
-			if (opcode == 0x0E || opcode == 0x0F)
+			switch (opcode) {
+			case 0x0E:
+			case 0x0F:
 				keyBitSet(key);
-			else
+				break;
+			case 0x10:
+			case 0x11:
 				keyBitClear(key);
+				break;
+			default:
+				break;
+			}
 		}
 
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x12) {
+	case 0x12: {
 		uint16 id = scriptReadWord(pc);
 		int16 delta = scriptReadStringIndex(pc + 2);
 		pc += 4;
@@ -214,7 +239,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x13) {
+	case 0x13: {
 		byte totalWeight = scriptReadByte(pc++);
 		byte installReturnPc = scriptReadByte(pc++);
 		uint32 returnPc = pc + installReturnPc - 3;
@@ -234,16 +259,17 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x14) {
+	case 0x14: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		byte mode = scriptReadByte(pc + 2);
 		pc += 3;
 		if (!target)
-			return kScriptUnhandled;
+			error("Script opcode 0x14 resolved an invalid actor");
 
 		uint16 targetIndex = (uint16)(target - &_actors[0]);
 		uint16 oldParent = actorReadU16(*target, kActorParent);
 		actorUnlink(targetIndex);
+
 		if (mode == 'O')
 			actorInsertChild(targetIndex, oldParent);
 		else
@@ -252,24 +278,30 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x15 || opcode == 0x16) {
+	case 0x15:
+	case 0x16: {
 		byte count = scriptReadByte(pc++);
 		for (uint i = 0; i < count; i++) {
 			uint16 id = scriptReadWord(pc);
 			pc += 2;
-			if (opcode == 0x15) {
+			switch (opcode) {
+			case 0x15:
 				spriteGetPtr((int16)id);
 				if (_spriteConversionLoads.count < COMFY_RESOURCE_LIST_CAPACITY)
 					_spriteConversionLoads.ids[_spriteConversionLoads.count++] = id;
-			} else {
+				break;
+			case 0x16:
 				soundLoadEntry(id);
+				break;
+			default:
+				break;
 			}
 		}
 
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x17) {
+	case 0x17: {
 		if (_musicEventMask) {
 			pc--;
 			return kScriptYield;
@@ -283,11 +315,11 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x18) {
+	case 0x18: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		pc += 2;
 		if (!target)
-			return kScriptUnhandled;
+			error("Script opcode 0x18 resolved an invalid actor");
 
 		uint32 resetPc = actorReadU32(*target, kActorResetPc);
 		actorWriteU32(*target, kActorCurrentPc, resetPc);
@@ -309,28 +341,30 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x1B) {
+	case 0x1B: {
 		vocQueuePlayAll();
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x1C) {
+	case 0x1C: {
 		midiRemoveTrack(scriptReadWord(pc));
 		pc += 2;
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x1D) {
+	case 0x1D: {
 		byte packed = scriptReadByte(pc++);
 		byte channel = (packed >> 4) - 1;
 		byte subop = packed & 0x0F;
-		if (subop == 1) {
+		switch (subop) {
+		case 1: {
 			uint16 songId = scriptReadWord(pc);
 			uint16 completionKey = scriptReadWord(pc + 2);
 			uint16 count = scriptReadWord(pc + 4);
 			pc += 6;
 			uint16 frames[COMFY_ANIM_FRAME_CAPACITY];
 			memset(frames, 0, sizeof(frames));
+
 			for (uint i = 0; i < count; i++) {
 				uint16 frame = scriptReadWord(pc);
 				pc += 2;
@@ -339,31 +373,48 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			}
 
 			midiAddTrackEntry(channel, songId, completionKey, 1, count, frames);
-		} else if (subop >= 2 && subop <= 4) {
+			break;
+		}
+		case 2:
+		case 3:
+		case 4: {
 			uint16 value = scriptReadWord(pc);
 			uint16 ticks = scriptReadWord(pc + 2);
 			pc += 4;
 			midiSetChannelParam(channel, subop, value, ticks);
-		} else if (subop == 5 && channel < COMFY_MIDI_CHANNEL_COUNT) {
-			midiStopAndRemove(channel);
-		} else if (subop == 6 && channel < COMFY_MIDI_CHANNEL_COUNT) {
-			midiStopAndFireKeys(channel);
-		} else if ((subop == 7 || subop == 8) && _engineVersion == 3 &&
-				channel < COMFY_MIDI_CHANNEL_COUNT && _midiPlyrDriver) {
-			_midiPlyrDriver->musicSetLoop(subop == 7 ? 1 : 0, channel);
+			break;
+		}
+		case 5:
+			if (channel < COMFY_MIDI_CHANNEL_COUNT)
+				midiStopAndRemove(channel);
+			break;
+		case 6:
+			if (channel < COMFY_MIDI_CHANNEL_COUNT)
+				midiStopAndFireKeys(channel);
+			break;
+		case 7:
+		case 8:
+			if (_engineVersion == 3 && channel < COMFY_MIDI_CHANNEL_COUNT && _midiPlyrDriver)
+				_midiPlyrDriver->musicSetLoop(subop == 7 ? 1 : 0, channel);
+			else
+				error("Unknown script opcode 0x1D subopcode 0x%02X at script PC 0x%08X", subop, pc - 2);
+
+			break;
+		default:
+			error("Unknown script opcode 0x1D subopcode 0x%02X at script PC 0x%08X", subop, pc - 2);
 		}
 
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x1E) {
+	case 0x1E: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		uint16 key = scriptReadWord(pc + 2);
 		byte flags = scriptReadByte(pc + 4);
 		uint32 triggerPc = scriptReadDword(pc + 5);
 		pc += 9;
 		if (!target)
-			return kScriptUnhandled;
+			error("Script opcode 0x1E resolved an invalid actor");
 
 		if (key != 0xFC18)
 			actorWriteU16(*target, kActorTriggerKey, key);
@@ -378,7 +429,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x1F) {
+	case 0x1F: {
 		uint16 bit = scriptReadWord(pc);
 		pc += 2;
 		if ((int16)bit >= 0x32) {
@@ -392,7 +443,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptYield;
 	}
 
-	if (opcode == 0x20) {
+	case 0x20: {
 		uint16 scene = scriptReadWord(pc);
 		pc += 2;
 		if (!_pendingScene || (int16)scene < (int16)_pendingScene)
@@ -403,7 +454,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptYield;
 	}
 
-	if (opcode == 0x21) {
+	case 0x21: {
 		uint16 paletteId = scriptReadStringIndex(pc);
 		uint16 fadeTicks = scriptReadStringIndex(pc + 2);
 		byte brightness = scriptReadByte(pc + 4);
@@ -416,13 +467,13 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x22) {
+	case 0x22: {
 		musicSetEnabled(scriptReadByte(pc));
 		pc++;
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x23) {
+	case 0x23: {
 		uint16 handle = scriptReadWord(pc);
 		int16 delta = scriptReadStringIndex(pc + 2);
 		pc += 4;
@@ -431,18 +482,18 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x24) {
+	case 0x24: {
 		midiSetTimeScale((int16)scriptReadStringIndex(pc));
 		pc += 2;
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x1A) {
+	case 0x1A: {
 		pc = actorPopPc(actor);
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x25) {
+	case 0x25: {
 		uint16 first = scriptReadWord(pc);
 		uint16 last = scriptReadWord(pc + 2);
 		pc += 4;
@@ -455,7 +506,8 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x26 || opcode == 0x2E) {
+	case 0x26:
+	case 0x2E: {
 		uint16 first = scriptReadWord(pc);
 		uint16 second = scriptReadWord(pc + 2);
 		uint16 key = scriptReadWord(pc + 4);
@@ -468,12 +520,13 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x28 || opcode == 0x29) {
+	case 0x28:
+	case 0x29: {
 		pc += 2;
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x2A) {
+	case 0x2A: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		uint32 selector = scriptReadDword(pc + 2);
 		pc += 6;
@@ -483,15 +536,16 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x2B) {
+	case 0x2B: {
 		pc = (uint32)((int32)pc + (int16)(scriptReadWord(pc) * 2));
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x2C) {
+	case 0x2C: {
 		uint16 destination = scriptReadWord(pc);
 		uint16 source = scriptReadWord(pc + 2);
 		pc += 4;
+
 		if (keyBitTest(source))
 			keyBitSet(destination);
 		else
@@ -500,33 +554,44 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x2D) {
+	case 0x2D: {
 		byte subop = scriptReadByte(pc++);
-		if (subop == 1) {
+		switch (subop) {
+		case 1:
 			sceneGoto(scriptReadWord(pc));
 			pc += 2;
-		} else if (subop == 2) {
+			break;
+		case 2:
 			sceneStop();
-		} else if (subop == 3) {
+			break;
+		case 3: {
 			uint16 descriptor = scriptReadWord(pc);
 			uint16 index = scriptReadWord(pc + 2);
 			pc += 4;
 			sceneEntryLoad(descriptor, index);
-		} else if (subop == 4) {
+			break;
+		}
+		case 4: {
 			uint16 channel = scriptReadWord(pc);
 			uint16 frame = scriptReadWord(pc + 2);
 			pc += 4;
 			midiPlaySongAtFrame(channel, frame);
-		} else if (subop == 5) {
+			break;
+		}
+		case 5: {
 			uint16 channel = scriptReadWord(pc);
 			pc += 2;
 			midiStopSong(channel);
+			break;
+		}
+		default:
+			error("Unknown script opcode 0x2D subopcode 0x%02X at script PC 0x%08X", subop, pc - 2);
 		}
 
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x2F) {
+	case 0x2F: {
 		byte command = scriptReadByte(pc);
 		uint16 destination = scriptReadWord(pc + 1);
 		uint16 first = scriptReadWord(pc + 3);
@@ -543,28 +608,52 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x30 && _usesAnimFile) {
+	case 0x30:
+		if (!_usesAnimFile)
+			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
+	{
 		byte subop = scriptReadByte(pc++);
-		if (subop == 0) {
+		switch (subop) {
+		case 0:
 			animFrameShutdown(true);
-		} else if (subop == 1) {
+			break;
+		case 1: {
 			uint16 animIndex = scriptReadWord(pc);
 			uint16 frameKey = scriptReadWord(pc + 2);
 			pc += 4;
 			animFileLoadFrame(animIndex, frameKey, actorReadU16(actor, kActorSceneHandle));
-		} else if (subop == 2) {
+			break;
+		}
+		case 2:
 			animFrameSetReady(true);
-		} else if (subop == 3) {
+			break;
+		case 3:
 			animFrameSetReady(false);
-		} else if (subop == 6) {
+			break;
+		case 6:
 			animFrameInvalidateActorRect();
+			break;
+		default:
+			error("Unknown script opcode 0x30 subopcode 0x%02X at script PC 0x%08X", subop, pc - 2);
 		}
 
 		return kScriptContinue;
 	}
 
-	if (opcode >= 0x31 && opcode <= 0x36 && _usesWcomfy99ScriptOps) {
-		if (opcode == 0x31) {
+	case 0x31:
+	case 0x32:
+	case 0x33:
+	case 0x34:
+	case 0x35:
+	case 0x36:
+		if (!(_usesWcomfy99ScriptOps ||
+			(opcode == 0x31 && (_game->scriptFeatures & COMFY_SCRIPT_OPCODE_31)) ||
+			(opcode == 0x32 && (_game->scriptFeatures & COMFY_SCRIPT_OPCODE_32)) ||
+			(opcode == 0x33 && (_game->scriptFeatures & COMFY_SCRIPT_OPCODE_33))))
+			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
+	{
+		switch (opcode) {
+		case 0x31: {
 			uint16 count = scriptReadStringIndex(pc);
 			pc += 2;
 			_wcomfy99FeatureWordCount = MIN<uint16>(count, ARRAYSIZE(_wcomfy99FeatureWords));
@@ -572,16 +661,22 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 				_wcomfy99FeatureWords[i] = scriptReadWord(pc + i * 2);
 
 			pc += (uint32)count * 2;
-		} else if (opcode == 0x32) {
+
+			break;
+		}
+		case 0x32:
 			_wcomfy99Stub32FirstWord = scriptReadWord(pc);
 			_wcomfy99Stub32SecondWord = scriptReadWord(pc + 2);
 			pc += 4;
-		} else if (opcode == 0x33) {
+			break;
+		case 0x33: {
 			pc += 4;
 			byte inlineBytes = scriptReadByte(pc++);
 			byte tripleCount = scriptReadByte(pc++);
 			pc += inlineBytes + (uint32)tripleCount * 3;
-		} else if (opcode == 0x34) {
+			break;
+		}
+		case 0x34: {
 			byte subop = scriptReadByte(pc++);
 			uint16 value = scriptReadWord(pc);
 			pc += 2;
@@ -591,48 +686,79 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 			key.trim();
 
-			if (subop == 0 && value < _stringTable.size()) {
-				_stringTable[value] = ConfMan.hasKey(key) ? ConfMan.getInt(key) : 0;
-			} else if (subop == 1) {
+			switch (subop) {
+			case 0:
+				if (value < _stringTable.size())
+					_stringTable[value] = ConfMan.hasKey(key) ? ConfMan.getInt(key) : 0;
+
+				break;
+			case 1:
 				ConfMan.setInt(key, value);
 				if (key.equalsIgnoreCase("SENSITIVITY"))
 					_wcomfy99Sensitivity = value;
 
 				ConfMan.flushToDisk();
-			} else if (subop == 4) {
+				break;
+			case 4:
 				if (ConfMan.hasKey(key) && !ConfMan.get(key).equalsIgnoreCase("?????"))
 					keyBitSet(value);
 				else
 					keyBitClear(value);
-			} else if (subop == 5) {
+
+				break;
+			case 5: {
 				Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(Common::Path(key), true));
 				if (stream)
 					keyBitSet(value);
 				else
 					keyBitClear(value);
-			} else if (subop == 6) {
+
+				break;
+			}
+			case 6: {
 				key.trim();
 				byte last = key.empty() ? 0 : key.lastChar();
 				if (value < _stringTable.size())
 					_stringTable[value] = Common::isSpace(last) ? 0x81 : Common::isDigit(last) ? 0x12 :
 						(Common::isAlpha(last) ? (Common::isUpper(last) ? 0x04 : 0x08) : 0x40);
+
+				break;
+			}
+			default:
+				error("Unknown script opcode 0x34 subopcode 0x%02X near script PC 0x%08X", subop, pc);
 			}
-		} else if (opcode == 0x35) {
+
+			break;
+		}
+		case 0x35: {
 			byte subop = scriptReadByte(pc++);
-			if (subop == 2)
+			switch (subop) {
+			case 2:
 				_wcomfy99SubsystemWord = 0;
-		} else {
+				break;
+			default:
+				error("Unknown script opcode 0x35 subopcode 0x%02X at script PC 0x%08X", subop, pc - 2);
+			}
+
+			break;
+		}
+		case 0x36: {
 			byte subop = scriptReadByte(pc++);
-			if (subop == 1 || subop == 3)
+			switch (subop) {
+			case 1:
 				_wcomfy99RecordHostEnabled = true;
-			else if (subop == 2)
+				break;
+			case 2:
 				_wcomfy99RecordHostEnabled = false;
-
-			if (subop >= 3 && subop <= 5) {
+				break;
+			case 3:
+			case 4:
+			case 5:
 				_wcomfy99MixedHostFirstWord = scriptReadWord(pc);
 				_wcomfy99MixedHostSecondWord = scriptReadWord(pc + 2);
 				pc += 4;
 				_wcomfy99RecordHostEnabled = true;
+
 				if (subop != 3) {
 					_wcomfy99MixedHostThirdWord = scriptReadWord(pc);
 					pc += 2;
@@ -642,47 +768,85 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 					_wcomfy99MixedHostFourthWord = scriptReadWord(pc);
 					pc += 2;
 				}
+
+				break;
+			default:
+				error("Unknown script opcode 0x36 subopcode 0x%02X at script PC 0x%08X", subop, pc - 2);
 			}
+
+			break;
+		}
+		default:
+			break;
 		}
 
 		return kScriptContinue;
 	}
 
-	if ((opcode == 0x46 || opcode == 0x47) && _usesWcomfy99ScriptOps) {
-		if (opcode == 0x46) {
+	case 0x46:
+	case 0x47:
+		if (!_usesWcomfy99ScriptOps)
+			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
+	{
+		switch (opcode) {
+		case 0x46: {
 			byte subop = scriptReadByte(pc++);
-			if (subop >= 1 && subop <= 8) {
-				uint16 argument = scriptReadWord(pc);
-				pc += 2;
-				uint16 percentage = argument == 0x00FF ? 0x00FF :
-					((int16)argument < 0 ? 0 : MIN<uint16>(argument, 100));
-				if (subop == 1)
-					_wcomfy99HostWordA = argument;
-				else if (subop == 2 && percentage != 0x00FF)
+			if (subop < 1 || subop > 8)
+				error("Unknown script opcode 0x46 subopcode 0x%02X at script PC 0x%08X", subop, pc - 2);
+
+			uint16 argument = scriptReadWord(pc);
+			pc += 2;
+			uint16 percentage = argument == 0x00FF ? 0x00FF : ((int16)argument < 0 ? 0 : MIN<uint16>(argument, 100));
+
+			switch (subop) {
+			case 1:
+				_wcomfy99HostWordA = argument;
+				break;
+			case 2:
+				if (percentage != 0x00FF)
 					_wcomfy99WaveVolumePercent = percentage;
-				else if (subop == 3 && percentage != 0x00FF)
+				break;
+			case 3:
+				if (percentage != 0x00FF)
 					_wcomfy99WaveLeftPercent = percentage;
-				else if (subop == 4 && percentage != 0x00FF)
+				break;
+			case 4:
+				if (percentage != 0x00FF)
 					_wcomfy99WaveRightPercent = percentage;
-				else if ((subop == 5 || subop == 6) && percentage != 0x00FF)
+				break;
+			case 5:
+			case 6:
+				if (percentage != 0x00FF)
 					_wcomfy99MixerVolumePercent = percentage;
-				else if (subop == 7 && percentage != 0x00FF)
+				break;
+			case 7:
+				if (percentage != 0x00FF)
 					_wcomfy99MixerAltPercent = percentage;
-				else if (subop == 8)
-					_wcomfy99HostWordB = argument;
+				break;
+			case 8:
+				_wcomfy99HostWordB = argument;
+				break;
+			default:
+				break;
 			}
-		} else {
+
+			break;
+		}
+		case 0x47:
 			_wcomfy99RangeHostStart = scriptReadWord(pc);
 			_wcomfy99RangeHostEnd = scriptReadWord(pc + 2);
 			_wcomfy99RangeHostCount = _wcomfy99RangeHostEnd >= _wcomfy99RangeHostStart ?
 				_wcomfy99RangeHostEnd - _wcomfy99RangeHostStart + 1 : 0;
 			pc += 4;
+			break;
+		default:
+			break;
 		}
 
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x50) {
+	case 0x50: {
 		uint16 lhsIndex = scriptReadWord(pc);
 		uint16 rhsIndex = scriptReadWord(pc + 2);
 		uint16 key = scriptReadWord(pc + 4);
@@ -699,7 +863,10 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x51 || opcode == 0x52 || opcode == 0x70 || opcode == 0x71) {
+	case 0x51:
+	case 0x52:
+	case 0x70:
+	case 0x71: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		pc += 2;
 		int16 x = scriptReadStringIndex(pc);
@@ -712,14 +879,17 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		byte blocking = scriptReadByte(pc++);
 		uint16 completionKey = scriptReadWord(pc);
 		pc += 2;
-		if (!target || !duration)
-			return kScriptUnhandled;
+		if (!target)
+			error("Script opcode 0x%02X resolved an invalid actor", opcode);
+
+		if (!duration)
+			error("Script opcode 0x%02X has a zero movement duration", opcode);
 
 		bool moveTo = opcode == 0x52 || opcode == 0x71;
 		if ((moveTo && x == (int16)0xF830) || (!moveTo && x == (int16)0x8AD0)) {
 			Actor *other = actorResolve((uint16)y, _currentActor);
 			if (!other)
-				return kScriptUnhandled;
+				error("Script opcode 0x%02X resolved an invalid reference actor", opcode);
 
 			if (moveTo) {
 				x = (int16)((int32)actorReadU32(*other, kActorXFixed) >> 12);
@@ -765,7 +935,11 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return blocking && target == &actor ? kScriptYield : kScriptContinue;
 	}
 
-	if ((opcode == 0x48 || opcode == 0x49) && _usesWcomfy99ScriptOps) {
+	case 0x48:
+	case 0x49:
+		if (!_usesWcomfy99ScriptOps)
+			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
+	{
 		uint16 key = scriptReadWord(pc);
 		uint32 targetPc = scriptReadDword(pc + 2);
 		bool jumpWhenSet = opcode == 0x49;
@@ -773,15 +947,32 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if ((opcode == 0x54 || opcode == 0x55) && _usesWcomfy99ScriptOps) {
+	case 0x53: {
+		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
+		uint16 frame = scriptReadStringIndex(pc + 2);
 		pc += 4;
+		if (!target)
+			error("Script opcode 0x53 resolved an invalid actor");
+
+		actorWriteU32(*target, kActorSpriteSelector, (uint32)(int32)(int16)frame);
+		actorWriteU32(*target, kActorMoveDx, 0);
+		actorWriteU32(*target, kActorMoveDy, 0);
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x6E)
+	case 0x54:
+	case 0x55:
+		if (_engineVersion < 2)
+			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
+	{
+		pc += 4;
+		return kScriptContinue;
+	}
+
+	case 0x6E:
 		return kScriptYield;
 
-	if (opcode == 0x6F) {
+	case 0x6F: {
 		uint16 id = scriptReadWord(pc);
 		int16 delta = scriptReadStringIndex(pc + 2);
 		pc += 4;
@@ -789,7 +980,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x72) {
+	case 0x72: {
 		uint16 requested = scriptReadStringIndex(pc);
 		pc += 2;
 		uint16 balance = actorReadU16(actor, kActorWaitAccum);
@@ -806,12 +997,12 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptYield;
 	}
 
-	if (opcode == 0x73) {
+	case 0x73: {
 		_waveOutputActive = false;
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x74) {
+	case 0x74: {
 		uint16 key = scriptReadWord(pc);
 		if (keyBitTest(key)) {
 			pc--;
@@ -822,7 +1013,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x75) {
+	case 0x75: {
 		byte kind = scriptReadByte(pc++);
 		uint16 key = scriptReadWord(pc);
 		pc += 2;
@@ -830,11 +1021,14 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		if (_usesWcomfy99ScriptOps) {
 			uint16 argument = scriptReadWord(pc);
 			pc += 2;
-			if (kind == 1)
+			switch (kind) {
+			case 1:
 				condition = sceneGetHandle(argument) != 0;
-			else if (kind == 2)
+				break;
+			case 2:
 				condition = _inputDeviceMode == 1;
-			else if (kind == 14) {
+				break;
+			case 14:
 				if (argument <= 4) {
 					condition = _inputDeviceMode == argument;
 				} else if (argument == 20) {
@@ -843,11 +1037,21 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 					Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(Common::Path("comfy.htm"), true));
 					condition = (bool)stream;
 				}
+				break;
+			default:
+				error("Unknown script opcode 0x75 subopcode 0x%02X at script PC 0x%08X", kind, pc - 6);
+			}
+		} else {
+			switch (kind) {
+			case 1: {
+				uint16 scene = scriptReadWord(pc);
+				condition = sceneGetHandle(scene) != 0;
+				pc += 2;
+				break;
+			}
+			default:
+				error("Unknown script opcode 0x75 subopcode 0x%02X at script PC 0x%08X", kind, pc - 4);
 			}
-		} else if (kind == 1) {
-			uint16 scene = scriptReadWord(pc);
-			condition = sceneGetHandle(scene) != 0;
-			pc += 2;
 		}
 
 		if (condition)
@@ -858,33 +1062,32 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x76 || opcode == 0x77) {
+	case 0x76:
+	case 0x77: {
 		uint16 index = scriptReadWord(pc);
 		pc += 2;
 		if (opcode == 0x77) {
-			if (_stringTable.size() <= 1) {
-				_scriptFault = true;
-				return kScriptUnhandled;
-			}
+			if (_stringTable.size() <= 1)
+				error("Script opcode 0x77 requires string table entry 1");
 
 			index += _stringTable[1];
 		}
 
 		uint16 value = scriptEvalExpr(pc, _currentActor);
-		if (index >= _stringTable.size()) {
-			_scriptFault = true;
-			return kScriptUnhandled;
-		}
+		if (index >= _stringTable.size())
+			error("Script opcode 0x%02X references invalid string table entry %u", opcode, (uint)index);
 
 		_stringTable[index] = value;
 		return kScriptContinue;
 	}
 
-	if (opcode == 0x7F)
+	case 0x7F:
 		return kScriptContinue;
 
-	if (!opcode || opcode > 0x7F || opcode == 0x27 || (opcode >= 0x30 && opcode <= 0x4F) ||
-	    (opcode >= 0x53 && opcode <= 0x6D) || (opcode >= 0x78 && opcode <= 0x7E)) {
+	default:
+		if (opcode)
+			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
+
 		Actor *root = actorGetPtr(0);
 		if (root)
 			actorWriteU8(*root, kActorActive, 0);
@@ -892,17 +1095,18 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptDeactivatedRoot;
 	}
 
-	_scriptFault = true;
-	return kScriptUnhandled;
+	error("Script opcode 0x%02X left the dispatch switch without returning", opcode);
+	return kScriptDeactivatedRoot;
 }
 
 ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptStep(Actor &actor, uint32 &pc) {
 	uint32 originalPc = pc;
 	byte opcode = scriptReadByte(pc++);
 	ScriptDispatchStatus status = scriptDispatch(actor, opcode, pc);
-	if (status == kScriptUnhandled)
-		pc = originalPc;
-	else if (status == kScriptYield)
+	if (_scriptFault)
+		error("Script fault while executing opcode 0x%02X at script PC 0x%08X", opcode, originalPc);
+
+	if (status == kScriptYield)
 		actorWriteU32(actor, kActorCurrentPc, pc);
 
 	return status;


Commit: 76328a715b3ceb69f064d90f8b2ef05dd19b874f
    https://github.com/scummvm/scummvm/commit/76328a715b3ceb69f064d90f8b2ef05dd19b874f
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: COLORS: Fix italian sound decoding

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/script_vm.cpp
    engines/comfy/sound.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 71eef16f494..db991375caa 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -24,6 +24,7 @@
 #include "comfy/console.h"
 #include "common/scummsys.h"
 #include "common/config-manager.h"
+#include "common/debug.h"
 #include "common/debug-channels.h"
 #include "common/events.h"
 #include "common/system.h"
@@ -505,6 +506,7 @@ void ComfyEngine::sceneTickEvent() {
 	if (_engineVersion == 3) {
 		VocQueueEntry1999 &entry = _vocQueue1999[_soundEventIndex];
 		bool started = false;
+		uint16 currentSubIndex = _soundEventSubIndex;
 		if (entry.state == 0xFFFF && (entry.soundId != 0xFFFF || !animFrameIsReady())) {
 			entry.state = 0;
 			_soundEventSubIndex = 0xFFFF;
@@ -514,11 +516,12 @@ void ComfyEngine::sceneTickEvent() {
 			keyBitClear(2);
 			keyBitClear(3);
 			started = true;
+			currentSubIndex = 0xFFFF;
 		}
 
-		if (!started && _soundEventSubIndex != 0xFFFF &&
-				_soundEventSubIndex != _soundEventPreviousSubIndex) {
-			if (!_soundEventSubIndex) {
+		if (!started && currentSubIndex != 0xFFFF &&
+				currentSubIndex != _soundEventPreviousSubIndex) {
+			if (!currentSubIndex) {
 				if (entry.argumentCount)
 					keyBitSet(entry.arguments[0]);
 
@@ -532,27 +535,28 @@ void ComfyEngine::sceneTickEvent() {
 					keyBitSet(3);
 					keyBitSet(2);
 				}
-			} else if (_soundEventSubIndex == 1) {
+			} else if (currentSubIndex == 1) {
 				keyBitSet(3);
 				keyBitClear(4);
-			} else if (_soundEventSubIndex == 2) {
+			} else if (currentSubIndex == 2) {
 				keyBitSet(4);
 				keyBitClear(3);
-			} else if (_soundEventSubIndex - 2 < entry.argumentCount) {
+			} else if (currentSubIndex - 2 < entry.argumentCount) {
 				if (entry.clearArgumentKeys) {
 					for (uint i = 0; i < entry.argumentCount; i++)
 						keyBitClear(entry.arguments[i]);
 				}
 
-				keyBitSet(entry.arguments[_soundEventSubIndex - 2]);
+				keyBitSet(entry.arguments[currentSubIndex - 2]);
 			}
 		}
 
-		_soundEventPreviousSubIndex = _soundEventSubIndex;
+		_soundEventPreviousSubIndex = currentSubIndex;
 		return;
 	}
 
 	VocQueueEntry &entry = _vocQueue[_soundEventIndex % COMFY_VOC_QUEUE_CAPACITY];
+	uint16 currentSubIndex = _soundEventSubIndex;
 	if (entry.state == 0xFFFF) {
 		entry.state = 0;
 		_soundEventSubIndex = 0xFFFF;
@@ -561,8 +565,9 @@ void ComfyEngine::sceneTickEvent() {
 		keyBitSet(4);
 		keyBitClear(2);
 		keyBitClear(3);
-	} else if (_soundEventSubIndex != 0xFFFF && _soundEventSubIndex != _soundEventPreviousSubIndex) {
-		if (!_soundEventSubIndex) {
+		currentSubIndex = 0xFFFF;
+	} else if (currentSubIndex != 0xFFFF && currentSubIndex != _soundEventPreviousSubIndex) {
+		if (!currentSubIndex) {
 			if (entry.argumentCount)
 				keyBitSet(entry.arguments[0]);
 
@@ -573,18 +578,18 @@ void ComfyEngine::sceneTickEvent() {
 				keyBitSet(2);
 				keyBitSet(3);
 			}
-		} else if (_soundEventSubIndex == 1) {
+		} else if (currentSubIndex == 1) {
 			keyBitSet(3);
 			keyBitClear(4);
-		} else if (_soundEventSubIndex == 2) {
+		} else if (currentSubIndex == 2) {
 			keyBitSet(4);
 			keyBitClear(3);
-		} else if (_soundEventSubIndex - 2 < entry.argumentCount) {
-			keyBitSet(entry.arguments[_soundEventSubIndex - 2]);
+		} else if (currentSubIndex - 2 < entry.argumentCount) {
+			keyBitSet(entry.arguments[currentSubIndex - 2]);
 		}
 	}
 
-	_soundEventPreviousSubIndex = _soundEventSubIndex;
+	_soundEventPreviousSubIndex = currentSubIndex;
 }
 
 void ComfyEngine::midiPollChannels(uint16 ticks) {
@@ -628,8 +633,14 @@ void ComfyEngine::midiPollChannels(uint16 ticks) {
 
 bool ComfyEngine::vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc) {
 	uint16 next = (_soundEventMaximum + 1) % COMFY_VOC_QUEUE_CAPACITY;
-	if (next == _soundEventIndex)
+	if (next == _soundEventIndex) {
+		debug(5, "COMFY VOC: queue full; rejected id=%u args=%u index=%u maximum=%u",
+			soundId, argumentCount, _soundEventIndex, _soundEventMaximum);
 		return false;
+	}
+
+	debug(5, "COMFY VOC: queue id=%u args=%u slot=%u next=%u version=%u",
+		soundId, argumentCount, _soundEventMaximum, next, _engineVersion);
 
 	if (_engineVersion == 3) {
 		VocQueueEntry1999 &entry = _vocQueue1999[_soundEventMaximum];
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 300633d515e..ce75c51bfd1 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -156,13 +156,17 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		if (!parentSlot)
 			parentSlot = actorReadU16(actor, kActorSceneHandle);
 
-		actorInit(sceneSlot, parentSlot, flags & 1, flags & 2, newPc, x, y, sprite, flags & 4);
+		actorInit(sceneSlot, parentSlot, (flags & 1) != 0, (flags & 2) != 0,
+			newPc, x, y, sprite, (flags & 4) != 0);
 		return kScriptContinue;
 	}
 
 	case 0x09: {
 		actorSetFrame((int16)scriptReadWord(pc));
 		pc += 2;
+		if (_videoMode == 2 || _videoMode == 4)
+			videoSetResolution();
+
 		return kScriptContinue;
 	}
 
@@ -882,7 +886,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		if (!target)
 			error("Script opcode 0x%02X resolved an invalid actor", opcode);
 
-		if (!duration)
+		if (!duration && (opcode == 0x51 || opcode == 0x52))
 			error("Script opcode 0x%02X has a zero movement duration", opcode);
 
 		bool moveTo = opcode == 0x52 || opcode == 0x71;
diff --git a/engines/comfy/sound.cpp b/engines/comfy/sound.cpp
index d5f53198235..58d740e48f4 100644
--- a/engines/comfy/sound.cpp
+++ b/engines/comfy/sound.cpp
@@ -24,6 +24,7 @@
 
 #include "audio/decoders/raw.h"
 #include "audio/audiostream.h"
+#include "common/debug.h"
 #include "common/endian.h"
 
 namespace Comfy {
@@ -123,11 +124,19 @@ bool ComfyEngine::soundDecodeEntry(uint16 index) {
 	soundHdrReadFromXms(header, index, sizeof(header));
 	uint32 dataSize = READ_LE_UINT32(header);
 	uint32 dataOffset = READ_LE_UINT32(header + 4);
-	if (dataOffset > _vocFileData.size() || dataSize > _vocFileData.size() - dataOffset)
+	debug(5, "COMFY VOC: decode id=%u offset=%u size=%u compressed=%u fileSize=%u",
+		index, dataOffset, dataSize, _soundCompressed ? 1 : 0, (uint)_vocFileData.size());
+	if (dataOffset > _vocFileData.size() || dataSize > _vocFileData.size() - dataOffset) {
+		debug(5, "COMFY VOC: decode id=%u rejected invalid range", index);
 		return false;
+	}
 
-	if (_soundCompressed)
-		return soundDecodeCompressedEntry(dataOffset, dataSize);
+	if (_soundCompressed) {
+		bool decoded = soundDecodeCompressedEntry(dataOffset, dataSize);
+		debug(5, "COMFY VOC: decode id=%u result=%u pcm=%u rate=%u cues=%u",
+			index, decoded ? 1 : 0, (uint)_soundPcm.size(), _soundSampleRate, (uint)_soundCues.size());
+		return decoded;
+	}
 
 	uint32 pc = dataOffset;
 	uint32 end = dataOffset + dataSize;
@@ -217,7 +226,10 @@ bool ComfyEngine::soundDecodeEntry(uint16 index) {
 		}
 	}
 
-	return !_soundPcm.empty();
+	bool decoded = !_soundPcm.empty();
+	debug(5, "COMFY VOC: decode id=%u result=%u pcm=%u rate=%u cues=%u",
+		index, decoded ? 1 : 0, (uint)_soundPcm.size(), _soundSampleRate, (uint)_soundCues.size());
+	return decoded;
 }
 
 bool ComfyEngine::soundDecodeCompressedEntry(uint32 dataOffset, uint32 dataSize) {
@@ -335,8 +347,10 @@ bool ComfyEngine::soundDecodeCompressedEntry(uint32 dataOffset, uint32 dataSize)
 }
 
 void ComfyEngine::soundPlayEntry(uint16 index) {
+	debug(5, "COMFY VOC: play id=%u", index);
 	_mixer->stopHandle(_soundHandle);
 	if (!soundDecodeEntry(index)) {
+		debug(5, "COMFY VOC: play id=%u decode failed", index);
 		_soundEventSubIndex = 0;
 		return;
 	}
@@ -344,6 +358,7 @@ void ComfyEngine::soundPlayEntry(uint16 index) {
 	Audio::AudioStream *stream = Audio::makeRawStream(&_soundPcm[0], _soundPcm.size(), _soundSampleRate,
 		Audio::FLAG_UNSIGNED, DisposeAfterUse::NO);
 	if (!stream) {
+		debug(5, "COMFY VOC: play id=%u raw stream creation failed", index);
 		_soundPcm.clear();
 		_soundEventSubIndex = 0;
 		return;
@@ -351,6 +366,9 @@ void ComfyEngine::soundPlayEntry(uint16 index) {
 
 	_mixer->playStream(Audio::Mixer::kSpeechSoundType, &_soundHandle, stream, -1,
 		Audio::Mixer::kMaxChannelVolume, 0, DisposeAfterUse::YES);
+	debug(5, "COMFY VOC: play id=%u submitted active=%u pcm=%u rate=%u cues=%u",
+		index, _mixer->isSoundHandleActive(_soundHandle) ? 1 : 0,
+		(uint)_soundPcm.size(), _soundSampleRate, (uint)_soundCues.size());
 	_soundPaused = false;
 	_soundEventSubIndex = 0xFFFF;
 	if (_midiPlyrDriver) {
@@ -365,8 +383,10 @@ void ComfyEngine::soundAdvanceTick() {
 		return;
 
 	if (!_mixer->isSoundHandleActive(_soundHandle)) {
-		if (!_soundPcm.empty())
+		if (!_soundPcm.empty() && _soundEventSubIndex != 0) {
+			debug(5, "COMFY VOC: mixer became inactive; marking entry complete");
 			_soundEventSubIndex = 0;
+		}
 
 		return;
 	}
@@ -379,6 +399,9 @@ void ComfyEngine::soundAdvanceTick() {
 			(_soundCues[_soundNextCue].value == 1 || _soundCues[_soundNextCue].value == 2)) {
 		phaseCueSeen = true;
 		_soundEventSubIndex = _soundCues[_soundNextCue].value;
+		debug(5, "COMFY VOC: cue=%u threshold=%u counter=%u index=%u/%u",
+			_soundEventSubIndex, _soundCues[_soundNextCue].counterThreshold, counter,
+			_soundNextCue, (uint)_soundCues.size());
 		_soundNextCue++;
 	}
 
@@ -387,6 +410,9 @@ void ComfyEngine::soundAdvanceTick() {
 		return;
 
 	_soundEventSubIndex = _soundCues[_soundNextCue].value;
+	debug(5, "COMFY VOC: cue=%u threshold=%u counter=%u index=%u/%u",
+		_soundEventSubIndex, _soundCues[_soundNextCue].counterThreshold, counter,
+		_soundNextCue, (uint)_soundCues.size());
 	_soundNextCue++;
 	if (!_soundEventSubIndex) {
 		_mixer->stopHandle(_soundHandle);


Commit: 4d98e7e3d905284123fbfac8ced4fd897921198b
    https://github.com/scummvm/scummvm/commit/4d98e7e3d905284123fbfac8ced4fd897921198b
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: PANTHER: Lots of fixes to make the game bootable

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/anim_file.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/game.cpp
    engines/comfy/scene.cpp
    engines/comfy/script_vm.cpp
    engines/comfy/sound.cpp
    engines/comfy/video.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index 9d67b514d06..ec5d6fddec8 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -235,11 +235,11 @@ void ComfyEngine::scenePoolReserveSlot(uint32 size) {
 }
 
 void ComfyEngine::spriteCache(int16 spriteId) {
+	soundServiceWaveBuffers();
+
 	if (!spriteId)
 		return;
 
-	soundUnprepareHeader();
-
 	if (spriteId < 0) {
 		uint16 frameId = (uint16)-spriteId;
 		uint32 fileOffset = (uint32)(frameId - 1) * COMFY_TILE_SIZE;
@@ -379,8 +379,43 @@ ComfyEngine::SpriteResource *ComfyEngine::spriteGetPtr(int16 spriteId) {
 	return _frameSpriteResource.loaded && _frameSpriteResource.id == frameId ? &_frameSpriteResource : nullptr;
 }
 
-void ComfyEngine::spriteBlitRle(const byte *source, uint32 sourceSize) {
-	if (!_framebufPtr || !source)
+void ComfyEngine::spriteGetConvPtr(int16 spriteId) {
+	soundServiceWaveBuffers();
+
+	if (spriteId <= 0 || (uint16)spriteId >= _objectCacheEntries.size())
+		return;
+
+	if (_spriteConversionLoads.count < COMFY_RESOURCE_LIST_CAPACITY)
+		_spriteConversionLoads.ids[_spriteConversionLoads.count++] = (uint16)spriteId;
+
+	SpriteCacheEntry &entry = _objectCacheEntries[spriteId];
+	byte *payload = nullptr;
+	uint16 width = 0;
+	if (entry.slotSize != 0xFFFF) {
+		if (entry.poolOffset <= _scenePoolData.size() && entry.slotSize >= 0x0C &&
+				0x0C <= _scenePoolData.size() - entry.poolOffset) {
+			byte *entryData = &_scenePoolData[entry.poolOffset];
+			width = READ_LE_UINT16(entryData + 4);
+			payload = entryData + 0x0C;
+		}
+	} else {
+		SpriteObjectHeader header;
+		objHdrRead(header, (uint16)spriteId);
+		width = header.width;
+		if (header.fileOffset <= _picFileData.size() &&
+				header.dataSize <= _picFileData.size() - header.fileOffset)
+			payload = &_picFileData[header.fileOffset];
+	}
+
+	if (!payload || width != 0xFFFF)
+		return;
+
+	// The original uploads the sound-cache tile named by the first payload
+	// word to XMS. ScummVM already keeps the complete source resident.
+}
+
+void ComfyEngine::spriteBlitRle(byte *destination, const byte *source, uint32 sourceSize) {
+	if (!destination || !source)
 		return;
 
 	uint32 sourcePos = 0;
@@ -394,22 +429,76 @@ void ComfyEngine::spriteBlitRle(const byte *source, uint32 sourceSize) {
 			if (sourcePos + count > sourceSize)
 				return;
 
-			memcpy(_framebufPtr + outputPos, source + sourcePos, count);
+			memcpy(destination + outputPos, source + sourcePos, count);
 			sourcePos += count;
 		} else if ((op & 0xC0) == 0xC0) {
-			memset(_framebufPtr + outputPos, previousFill, count);
+			memset(destination + outputPos, previousFill, count);
 		} else {
 			if (sourcePos >= sourceSize)
 				return;
 
 			previousFill = source[sourcePos++];
-			memset(_framebufPtr + outputPos, previousFill, count);
+			memset(destination + outputPos, previousFill, count);
 		}
 
 		outputPos += count;
 	}
 }
 
+void ComfyEngine::backgroundTransitionFrames(uint16 frame, uint16 previousFrame) {
+	if (_isPanther) {
+		if (frame == previousFrame || !frame || _backgroundFramebuf.empty())
+			return;
+
+		SpriteResource *background = spriteGetPtr((int16)frame);
+		if (!background)
+			return;
+
+		if (background->header.width == _logicalScreenWidth &&
+				background->header.height == _logicalScreenHeight && !background->pixels.empty()) {
+			spriteBlitRle(&_backgroundFramebuf[0], &background->pixels[0], background->pixels.size());
+		} else {
+			uint16 color = background->pixels.size() > 3 ? background->pixels[3] : 0;
+			framebufClear(&_backgroundFramebuf[0], color);
+		}
+
+		renderInvalidateFullFrame();
+		return;
+	}
+
+	SpriteResource *background = spriteGetPtr((int16)frame);
+	if (!background)
+		return;
+
+	if (background->header.width == _logicalScreenWidth &&
+			background->header.height == _logicalScreenHeight && !background->pixels.empty()) {
+		spriteBlitRle(_framebufPtr, &background->pixels[0], background->pixels.size());
+	} else {
+		uint16 color = background->pixels.size() > 3 ? background->pixels[3] : 0;
+		framebufClear(_framebufPtr, color);
+	}
+
+	videoSetResolution();
+}
+
+void ComfyEngine::backgroundRestoreDirtyRects() {
+	if (_backgroundFramebuf.empty() || !_framebufPtr)
+		return;
+
+	for (uint i = 0; i < _resolutionChangeCount; i++) {
+		VideoRectRecord &rect = _resolutionChanges[i];
+		int16 width = rect.right - rect.left;
+		int16 height = rect.bottom - rect.top;
+		if (width <= 0 || height <= 0)
+			continue;
+
+		for (int16 y = rect.top; y < rect.bottom; y++) {
+			uint32 offset = (uint32)y * _logicalScreenWidth + rect.left;
+			memcpy(_framebufPtr + offset, &_backgroundFramebuf[offset], width);
+		}
+	}
+}
+
 void ComfyEngine::spriteBlitClipped(int16 spriteId, int16 x, int16 y) {
 	SpriteResource *loadedSprite = spriteGetPtr(spriteId);
 	if (!loadedSprite)
@@ -417,7 +506,7 @@ void ComfyEngine::spriteBlitClipped(int16 spriteId, int16 x, int16 y) {
 
 	SpriteResource &sprite = *loadedSprite;
 	if (sprite.header.width == _logicalScreenWidth && sprite.header.height == _logicalScreenHeight) {
-		spriteBlitRle(&sprite.pixels[0], sprite.pixels.size());
+		spriteBlitRle(_framebufPtr, &sprite.pixels[0], sprite.pixels.size());
 		renderSetDirty();
 		return;
 	}
@@ -464,38 +553,38 @@ void ComfyEngine::spriteBlitClipped(int16 spriteId, int16 x, int16 y) {
 }
 
 uint32 ComfyEngine::actorReadU32(Actor &actor, uint offset) {
-	if (offset + 4 > COMFY_ACTOR_SIZE)
+	if (offset + 4 > _actorSize)
 		return 0;
 
 	return READ_LE_UINT32(actor.raw + offset);
 }
 
 uint16 ComfyEngine::actorReadU16(Actor &actor, uint offset) {
-	if (offset + 2 > COMFY_ACTOR_SIZE)
+	if (offset + 2 > _actorSize)
 		return 0;
 
 	return READ_LE_UINT16(actor.raw + offset);
 }
 
 byte ComfyEngine::actorReadU8(Actor &actor, uint offset) {
-	if (offset >= COMFY_ACTOR_SIZE)
+	if (offset >= _actorSize)
 		return 0;
 
 	return actor.raw[offset];
 }
 
 void ComfyEngine::actorWriteU32(Actor &actor, uint offset, uint32 value) {
-	if (offset + 4 <= COMFY_ACTOR_SIZE)
+	if (offset + 4 <= _actorSize)
 		WRITE_LE_UINT32(actor.raw + offset, value);
 }
 
 void ComfyEngine::actorWriteU16(Actor &actor, uint offset, uint16 value) {
-	if (offset + 2 <= COMFY_ACTOR_SIZE)
+	if (offset + 2 <= _actorSize)
 		WRITE_LE_UINT16(actor.raw + offset, value);
 }
 
 void ComfyEngine::actorWriteU8(Actor &actor, uint offset, byte value) {
-	if (offset < COMFY_ACTOR_SIZE)
+	if (offset < _actorSize)
 		actor.raw[offset] = value;
 }
 
@@ -518,6 +607,27 @@ uint16 ComfyEngine::actorGetFrame() {
 	return root ? (uint16)actorReadU32(*root, kActorSpriteSelector) : 0;
 }
 
+void ComfyEngine::actorSetPos(uint16 mode, int16 value) {
+	Actor *root = rootActor();
+	if (!root)
+		return;
+
+	switch (mode) {
+	case 1:
+		actorWriteU32(*root, kActorXFixed, (uint32)(int32)value);
+		actorWriteU32(*root, kActorYFixed, 0);
+		break;
+
+	case 2:
+		actorWriteU32(*root, kActorYFixed,
+			(actorReadU32(*root, kActorYFixed) + (int32)value) & 0xFF);
+		break;
+
+	default:
+		break;
+	}
+}
+
 ComfyEngine::Actor *ComfyEngine::actorResolve(uint16 sceneOrActor, uint16 fallbackActor) {
 	if (!sceneOrActor)
 		return actorGetPtr(fallbackActor);
@@ -617,7 +727,7 @@ uint16 ComfyEngine::actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible,
 		uint32 pc, int16 x, int16 y, int16 sprite, byte insertAsChild) {
 	uint16 actorIndex = actorAlloc(sceneSlot);
 	Actor *actor = actorGetPtr(actorIndex);
-	if (!actor)
+	if (!actorIndex || !actor)
 		return 8;
 
 	actorWriteU16(*actor, kActorSceneHandle, sceneSlot);
@@ -637,11 +747,11 @@ uint16 ComfyEngine::actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible,
 	actorWriteU16(*actor, kActorWaitTarget, 0);
 	actorWriteU16(*actor, kActorWaitAccum, 0);
 	actorWriteU8(*actor, kActorDirty, 1);
-	if (_videoMode == 2) {
+	if (_videoMode == 2 || _videoMode == 4) {
 		VideoRectRecord empty;
 		actorWriteCachedRect(*actor, empty);
-		actorWriteU32(*actor, kActorCachedSprite, 0);
-		actorWriteU8(*actor, kActorCachedVisible, 0);
+		actorWriteU32(*actor, _actorCachedSpriteOffset, 0);
+		actorWriteU8(*actor, _actorCachedVisibleOffset, 0);
 	}
 
 	if (parentSlot) {
@@ -722,10 +832,8 @@ void ComfyEngine::actorFreeTreePc(uint16 actorIndex) {
 	if (!actor)
 		return;
 
-	if (_videoMode == 2) {
-		VideoRectRecord rect = actorReadCachedRect(*actor);
-		videoFindBestMode(rect);
-	}
+	if (!_usesAnimFile && _videoMode == 2)
+		videoFindBestMode(actorReadCachedRect(*actor));
 
 	actorFreePcChain(*actor);
 
@@ -745,8 +853,19 @@ void ComfyEngine::actorFreeTreePc(uint16 actorIndex) {
 		child = next;
 	}
 
-	if (_usesAnimFile && actorReadU32(*actor, kActorSpriteSelector) == 0x00FFFFFF)
-		animFrameShutdown(true);
+	if (_usesAnimFile) {
+		uint32 selector = actorReadU32(*actor, kActorSpriteSelector);
+		if (_videoMode == 2 || _videoMode == 4) {
+			if (selector & 0xFF000000) {
+				renderInvalidateFullFrame();
+			} else if (selector != 0x00FFFFFF) {
+				videoFindBestMode(actorReadCachedRect(*actor));
+			}
+		}
+
+		if (selector == 0x00FFFFFF)
+			animFrameShutdown(true);
+	}
 
 	uint16 sceneSlot = actorReadU16(*actor, kActorSceneHandle);
 	actorFreeSlot(sceneSlot);
@@ -848,11 +967,6 @@ bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
 
 		actorWriteU16(*actor, kActorMoveTicks, moveTicks);
 		if (moveTicks && actorReadU8(*actor, kActorBlockingMove)) {
-			if (_stringTable.size() > 3) {
-				actorWriteU16(*actor, kActorStringRef, _stringTable[2]);
-				actorWriteU16(*actor, kActorStringRef + 2, _stringTable[3]);
-			}
-
 			descendChildren = true;
 			return false;
 		}
@@ -887,7 +1001,7 @@ bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
 		}
 
 		descendChildren = status == kScriptYield && !_actorDestroyedCurrent;
-		return status == kScriptDeactivatedRoot || _actorDestroyedCurrent;
+		return _actorDestroyedCurrent;
 	}
 }
 
@@ -937,14 +1051,69 @@ bool ComfyEngine::actorTickTree(uint16 actorIndex) {
 	return false;
 }
 
-void ComfyEngine::actorDrawList(uint16 actorIndex, int16 x, int16 y) {
+void ComfyEngine::actorDrawList(uint16 actorIndex, int16 x, int16 y, bool visible) {
 	while (actorIndex) {
-		actorDraw(actorIndex, x, y);
+		if (_usesAnimFile)
+			actorDrawInternal(actorIndex, x, y, visible);
+		else
+			actorDraw(actorIndex, x, y);
+
 		Actor *actor = actorGetPtr(actorIndex);
 		actorIndex = actor ? actorReadU16(*actor, kActorNextLink) : 0;
 	}
 }
 
+void ComfyEngine::renderQueueDrawCommand(int16 x, int16 y, uint32 selector, byte mode) {
+	if (!selector)
+		return;
+
+	if (_drawCommandCount >= COMFY_DRAW_COMMAND_CAPACITY)
+		error("Too many actor draw commands");
+
+	DrawCommand &command = _drawCommands[_drawCommandCount++];
+	command.x = x;
+	command.y = y;
+	command.selector = selector;
+	command.mode = mode;
+	if (_drawCommandCount >= COMFY_DRAW_COMMAND_CAPACITY)
+		error("Too many actor draw commands");
+}
+
+void ComfyEngine::renderFlushDrawCommands() {
+	if (_isPanther && actorGetFrame())
+		backgroundRestoreDirtyRects();
+
+	for (uint i = 0; i < _drawCommandCount; i++) {
+		DrawCommand &command = _drawCommands[i];
+		if (command.mode == 2) {
+			animFrameBlitAt(command.x, command.y);
+			continue;
+		}
+
+		SpriteResource *sprite = spriteGetPtr((int16)command.selector);
+		if (!sprite)
+			continue;
+
+		spriteBlitClipped((int16)command.selector, command.x, command.y);
+		if (command.mode == 0) {
+			VideoRectRecord dirtyRect;
+			dirtyRect.left = command.x;
+			dirtyRect.top = command.y;
+			dirtyRect.right = command.x + sprite->header.width;
+			dirtyRect.bottom = command.y + sprite->header.height;
+			dirtyRect.area = (uint32)sprite->header.width * sprite->header.height;
+			videoFindBestMode(dirtyRect);
+		}
+	}
+
+	_drawCommandCount = 0;
+}
+
+void ComfyEngine::renderFlushCachedDirtyRects() {
+	for (uint i = 0; i < _animFrameDirtyRectCount; i++)
+		videoFindBestMode(_animFrameDirtyRects[i]);
+}
+
 uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &maskRecord,
 		VideoRectRecord *rects, int16 baseX, int16 baseY) {
 	if (mode == 1) {
@@ -1026,7 +1195,7 @@ uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &m
 
 		int16 left = _keymaskX - sprite->header.hotspotX;
 		int16 top = _keymaskY - sprite->header.hotspotY;
-		if (mode == 1)
+		if (mode == 1 && !_usesAnimFile)
 			spriteBlitClipped((int16)spriteId, left, top);
 
 		if (rect) {
@@ -1034,7 +1203,8 @@ uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &m
 			rect->top = top;
 			rect->right = left + sprite->header.width;
 			rect->bottom = top + sprite->header.height;
-			rect->area = sprite->header.width * sprite->header.height;
+			rect->area = _usesAnimFile ? spriteId :
+				(uint32)sprite->header.width * sprite->header.height;
 		}
 	}
 
@@ -1047,23 +1217,29 @@ void ComfyEngine::actorEvalFrameSelection(uint16 actorIndex, int16 x, int16 y) {
 	if (!actor)
 		return;
 
-	uint32 selector = actorReadU32(*actor, kActorCachedSprite);
+	uint32 selector = actorReadU32(*actor, _actorCachedSpriteOffset);
 	VideoRectRecord rect = actorReadCachedRect(*actor);
-	if (selector & 0xFF000000) {
+	if (selector == 0x00FFFFFF) {
+		animFrameInvalidateRects(rect.left, rect.top, 0);
+	} else if (selector & 0xFF000000) {
 		uint16 last = scriptEvalKeyMask(selector & 0x00FFFFFF, 0, rect, _keymaskInvalidationRects,
 			rect.left, rect.top);
 		if (last != 0xFFFF && last >= COMFY_RESOLUTION_CHANGE_CAPACITY)
 			last = COMFY_RESOLUTION_CHANGE_CAPACITY - 1;
 
 		if (last != 0xFFFF) {
-			for (uint i = 0; i <= last; i++)
-				videoFindBestMode(_keymaskInvalidationRects[i]);
+			for (uint i = 0; i <= last; i++) {
+				VideoRectRecord dirtyRect = _keymaskInvalidationRects[i];
+				dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) *
+					(dirtyRect.bottom - dirtyRect.top);
+				videoFindBestMode(dirtyRect);
+			}
 		}
 	} else {
 		videoFindBestMode(rect);
 	}
 
-	actorWriteU32(*actor, kActorCachedSprite, 0);
+	actorWriteU32(*actor, _actorCachedSpriteOffset, 0);
 	uint16 child = actorReadU16(*actor, kActorSiblingHead);
 	while (child) {
 		actorEvalFrameSelection(child, x, y);
@@ -1085,7 +1261,8 @@ ComfyEngine::VideoRectRecord ComfyEngine::actorReadCachedRect(Actor &actor) {
 	rect.top = actorReadU16(actor, kActorCachedRect + 2);
 	rect.right = actorReadU16(actor, kActorCachedRect + 4);
 	rect.bottom = actorReadU16(actor, kActorCachedRect + 6);
-	rect.area = actorReadU16(actor, kActorCachedRect + 8);
+	rect.area = _actorCachedAreaIs32Bit ? actorReadU32(actor, kActorCachedRect + 8) :
+		actorReadU16(actor, kActorCachedRect + 8);
 	return rect;
 }
 
@@ -1094,7 +1271,10 @@ void ComfyEngine::actorWriteCachedRect(Actor &actor, VideoRectRecord rect) {
 	actorWriteU16(actor, kActorCachedRect + 2, rect.top);
 	actorWriteU16(actor, kActorCachedRect + 4, rect.right);
 	actorWriteU16(actor, kActorCachedRect + 6, rect.bottom);
-	actorWriteU16(actor, kActorCachedRect + 8, rect.area);
+	if (_actorCachedAreaIs32Bit)
+		actorWriteU32(actor, kActorCachedRect + 8, rect.area);
+	else
+		actorWriteU16(actor, kActorCachedRect + 8, rect.area);
 }
 
 bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
@@ -1102,33 +1282,268 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 	if (!actor)
 		return true;
 
-	if (!animFrameShouldDraw(1))
+	if (!animFrameShouldDraw(1)) {
+		if (_usesAnimFile)
+			animFrameInvalidateRects(x, y, 0);
+
 		return false;
+	}
 
-	int16 drawX = (int16)((int32)actorReadU32(*actor, kActorXFixed) >> 12) + x;
-	int16 drawY = (int16)((int32)actorReadU32(*actor, kActorYFixed) >> 12) + y;
-	byte oldVisible = actorReadU8(*actor, kActorCachedVisible);
-	uint32 oldSelector = actorReadU32(*actor, kActorCachedSprite);
-	VideoRectRecord oldRect = actorReadCachedRect(*actor);
-	if (!actorReadU8(*actor, kActorVisible)) {
-		if (_videoMode == 2 && actorReadU8(*actor, kActorVisible) != oldVisible) {
+	if (!_usesAnimFile && !actorReadU8(*actor, kActorVisible)) {
+		if ((_videoMode == 2 || _videoMode == 4) &&
+				actorReadU8(*actor, kActorVisible) != actorReadU8(*actor, _actorCachedVisibleOffset)) {
+			int16 drawX = (int16)((int32)actorReadU32(*actor, kActorXFixed) >> 12) + x;
+			int16 drawY = (int16)((int32)actorReadU32(*actor, kActorYFixed) >> 12) + y;
 			actorEvalFrameSelection(actorIndex, drawX, drawY);
-			actorWriteU8(*actor, kActorCachedVisible, actorReadU8(*actor, kActorVisible));
+			actorWriteU8(*actor, _actorCachedVisibleOffset, actorReadU8(*actor, kActorVisible));
 		}
 
 		return true;
 	}
 
 	animFrameRecordVocCounter(1);
-	actorDrawList(actorReadU16(*actor, kActorSiblingHead), drawX, drawY);
+	if (_isPanther && _videoMode != 2 && _videoMode != 4)
+		actorDrawLegacyInternal(actorIndex, x, y);
+	else
+		actorDrawInternal(actorIndex, x, y, true);
+
+	if (_usesAnimFile) {
+		if (_isPanther && (_videoMode == 2 || _videoMode == 4))
+			renderFlushDrawCommands();
+
+		animFrameRecordVocCounter(2);
+	}
+
+	return animFrameShouldDraw(2);
+}
+
+bool ComfyEngine::actorDrawLegacyInternal(uint16 actorIndex, int16 x, int16 y) {
+	Actor *actor = actorGetPtr(actorIndex);
+	if (!actor || !actorReadU8(*actor, kActorVisible))
+		return true;
+
+	int16 drawX = (int16)((int32)actorReadU32(*actor, kActorXFixed) >> 12) + x;
+	int16 drawY = (int16)((int32)actorReadU32(*actor, kActorYFixed) >> 12) + y;
+	bool drawResult = true;
+	uint16 linkedActor = actorReadU16(*actor, kActorSiblingHead);
+	while (linkedActor && drawResult) {
+		drawResult = actorDrawLegacyInternal(linkedActor, drawX, drawY);
+		Actor *linked = actorGetPtr(linkedActor);
+		linkedActor = linked ? actorReadU16(*linked, kActorNextLink) : 0;
+	}
+
+	if (!drawResult)
+		return false;
+
+	uint32 selector = actorReadU32(*actor, kActorSpriteSelector);
+	if (selector == 0x00FFFFFF) {
+		drawResult = animFrameBlitAt(drawX, drawY);
+	} else if (selector & 0xFF000000) {
+		uint32 pc = selector & 0x00FFFFFF;
+		int16 wordsLeft = (int16)(scriptReadWord(pc) - 1);
+		pc += 2;
+		while (wordsLeft > 0 && !_scriptFault) {
+			uint16 spriteId = scriptReadWord(pc);
+			int16 dx = scriptReadWord(pc + 2);
+			int16 dy = scriptReadWord(pc + 4);
+			pc += 6;
+			wordsLeft -= 3;
+			if (spriteId & 0x8000) {
+				wordsLeft -= 2;
+				uint16 key = scriptReadWord(pc);
+				pc += 2;
+				if (keyBitTest(key))
+					spriteId &= 0x7FFF;
+				else
+					spriteId = scriptReadWord(pc);
+
+				pc += 2;
+			}
+
+			if (spriteId) {
+				int16 spriteX = drawX + dx;
+				int16 spriteY = drawY + dy;
+				SpriteResource *sprite = spriteLookup(spriteId, spriteX, spriteY);
+				if (sprite)
+					spriteBlitClipped((int16)spriteId, spriteX - sprite->header.hotspotX,
+						spriteY - sprite->header.hotspotY);
+			}
+		}
+	} else if (selector) {
+		SpriteResource *sprite = spriteLookup((uint16)selector, drawX, drawY);
+		if (sprite)
+			spriteBlitClipped((int16)selector, drawX - sprite->header.hotspotX,
+				drawY - sprite->header.hotspotY);
+	}
+
+	if (!drawResult)
+		return false;
+
+	linkedActor = actorReadU16(*actor, kActorChildHead);
+	while (linkedActor && drawResult) {
+		drawResult = actorDrawLegacyInternal(linkedActor, drawX, drawY);
+		Actor *linked = actorGetPtr(linkedActor);
+		linkedActor = linked ? actorReadU16(*linked, kActorNextLink) : 0;
+	}
+
+	return drawResult;
+}
+
+void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool visible) {
+	Actor *actor = actorGetPtr(actorIndex);
+	if (!actor)
+		return;
+
+	int16 drawX = (int16)((int32)actorReadU32(*actor, kActorXFixed) >> 12) + x;
+	int16 drawY = (int16)((int32)actorReadU32(*actor, kActorYFixed) >> 12) + y;
+	visible = visible && actorReadU8(*actor, kActorVisible);
+	byte oldVisible = actorReadU8(*actor, _actorCachedVisibleOffset);
+	uint32 oldSelector = actorReadU32(*actor, _actorCachedSpriteOffset);
+	VideoRectRecord oldRect = actorReadCachedRect(*actor);
+	actorDrawList(actorReadU16(*actor, kActorSiblingHead), drawX, drawY, visible);
 	uint32 selector = actorReadU32(*actor, kActorSpriteSelector);
+	if (_isPanther) {
+		VideoRectRecord newRect;
+		if (selector == 0x00FFFFFF) {
+			bool changed = false;
+			if (oldVisible != (visible ? 1 : 0) && actorReadU8(*actor, kActorVisible) && oldVisible == 1)
+				changed = true;
+
+			if (oldRect.left != drawX || oldRect.top != drawY)
+				changed = true;
+
+			if (changed) {
+				renderFlushCachedDirtyRects();
+				animFrameInvalidateRects(drawX, drawY, 1);
+				newRect.left = drawX;
+				newRect.top = drawY;
+				actorWriteU8(*actor, _actorCachedVisibleOffset, visible ? 1 : 0);
+				actorWriteCachedRect(*actor, newRect);
+				renderQueueDrawCommand(drawX, drawY, selector, 2);
+			} else if (visible && actorReadU8(*actor, kActorVisible)) {
+				animFrameInvalidateRects(drawX, drawY, 0);
+				renderQueueDrawCommand(drawX, drawY, selector, 2);
+			}
+
+			actorDrawList(actorReadU16(*actor, kActorChildHead), drawX, drawY, visible);
+			return;
+		}
+
+		bool scripted = (selector & 0xFF000000) != 0;
+		uint16 currentLastRect = 0xFFFF;
+		if (scripted) {
+			_keymaskCurrentRecord.left = drawX;
+			_keymaskCurrentRecord.top = drawY;
+			_keymaskCurrentRecord.right = 0;
+			_keymaskCurrentRecord.bottom = 0;
+			_keymaskCurrentRecord.area = 0;
+			currentLastRect = scriptEvalKeyMask(selector & 0x00FFFFFF, 1,
+				_keymaskCurrentRecord, _keymaskRects, drawX, drawY);
+			if (currentLastRect != 0xFFFF && currentLastRect >= COMFY_RESOLUTION_CHANGE_CAPACITY)
+				currentLastRect = COMFY_RESOLUTION_CHANGE_CAPACITY - 1;
+
+			newRect = _keymaskCurrentRecord;
+		} else if (selector) {
+			SpriteResource *sprite = spriteLookup((uint16)selector, drawX, drawY);
+			if (sprite) {
+				newRect.left = drawX - sprite->header.hotspotX;
+				newRect.top = drawY - sprite->header.hotspotY;
+				newRect.right = newRect.left + sprite->header.width;
+				newRect.bottom = newRect.top + sprite->header.height;
+				newRect.area = selector;
+			}
+		}
+
+		if (scripted && oldSelector == selector && oldRect.left == newRect.left &&
+				oldRect.top == newRect.top && oldVisible == 1 && visible) {
+			VideoRectRecord oldMaskRecord = oldRect;
+			uint16 oldLastRect = scriptEvalKeyMask(oldSelector & 0x00FFFFFF, 0,
+				oldMaskRecord, _keymaskOldRects, oldRect.left, oldRect.top);
+			if (oldLastRect != 0xFFFF && oldLastRect >= COMFY_RESOLUTION_CHANGE_CAPACITY)
+				oldLastRect = COMFY_RESOLUTION_CHANGE_CAPACITY - 1;
+
+			if (oldLastRect != 0xFFFF) {
+				for (uint i = 0; i <= oldLastRect; i++) {
+					VideoRectRecord &currentRect = _keymaskRects[i];
+					VideoRectRecord &previousRect = _keymaskOldRects[i];
+					bool equal = currentRect.left == previousRect.left &&
+						currentRect.top == previousRect.top &&
+						currentRect.right == previousRect.right &&
+						currentRect.bottom == previousRect.bottom &&
+						currentRect.area == previousRect.area;
+					if (!equal)
+						videoFindBestMode(previousRect);
+
+					renderQueueDrawCommand(currentRect.left, currentRect.top,
+						currentRect.area, equal ? 1 : 0);
+				}
+			}
+
+			actorWriteCachedRect(*actor, newRect);
+			actorDrawList(actorReadU16(*actor, kActorChildHead), drawX, drawY, visible);
+			return;
+		}
+
+		bool changed = oldSelector != selector || oldRect.left != newRect.left ||
+			oldRect.top != newRect.top || oldRect.right != newRect.right ||
+			oldRect.bottom != newRect.bottom || oldRect.area != newRect.area ||
+			oldVisible != (visible ? 1 : 0);
+		if (changed) {
+			if (visible && selector) {
+				if (scripted && currentLastRect != 0xFFFF) {
+					for (uint i = 0; i <= currentLastRect; i++) {
+						VideoRectRecord &rect = _keymaskRects[i];
+						renderQueueDrawCommand(rect.left, rect.top, rect.area, 0);
+					}
+				} else if (!scripted) {
+					renderQueueDrawCommand(newRect.left, newRect.top, newRect.area, 0);
+				}
+			}
+
+			if (oldVisible) {
+				if (oldSelector == 0x00FFFFFF) {
+					renderFlushCachedDirtyRects();
+				} else if (oldSelector & 0xFF000000) {
+					VideoRectRecord oldMaskRecord = oldRect;
+					uint16 oldLastRect = scriptEvalKeyMask(oldSelector & 0x00FFFFFF, 0,
+						oldMaskRecord, _keymaskOldRects, oldRect.left, oldRect.top);
+					if (oldLastRect != 0xFFFF && oldLastRect >= COMFY_RESOLUTION_CHANGE_CAPACITY)
+						oldLastRect = COMFY_RESOLUTION_CHANGE_CAPACITY - 1;
+
+					if (oldLastRect != 0xFFFF) {
+						for (uint i = 0; i <= oldLastRect; i++)
+							videoFindBestMode(_keymaskOldRects[i]);
+					}
+				} else {
+					videoFindBestMode(oldRect);
+				}
+			}
+
+			actorWriteU8(*actor, _actorCachedVisibleOffset, visible ? 1 : 0);
+			actorWriteCachedRect(*actor, newRect);
+			actorWriteU32(*actor, _actorCachedSpriteOffset, selector);
+		} else if (visible) {
+			if (scripted && currentLastRect != 0xFFFF) {
+				for (uint i = 0; i <= currentLastRect; i++) {
+					VideoRectRecord &rect = _keymaskRects[i];
+					renderQueueDrawCommand(rect.left, rect.top, rect.area, 1);
+				}
+			} else if (!scripted) {
+				renderQueueDrawCommand(newRect.left, newRect.top, newRect.area, 1);
+			}
+		}
+
+		actorDrawList(actorReadU16(*actor, kActorChildHead), drawX, drawY, visible);
+		return;
+	}
+
 	bool oldScripted = (oldSelector & 0xFF000000) != 0;
 	bool newScripted = (selector & 0xFF000000) != 0;
 	VideoRectRecord newRect;
 	uint16 scriptedLastRect = 0xFFFF;
 	if (newScripted) {
 		uint32 pc = selector & 0x00FFFFFF;
-		if (_videoMode == 2) {
+		if (_videoMode == 2 || _videoMode == 4) {
 			_keymaskCurrentRecord.left = drawX;
 			_keymaskCurrentRecord.top = drawY;
 			_keymaskCurrentRecord.right = 0;
@@ -1137,6 +1552,18 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 			scriptedLastRect = scriptEvalKeyMask(pc, 1, _keymaskCurrentRecord, _keymaskRects, drawX, drawY);
 			if (scriptedLastRect != 0xFFFF && scriptedLastRect >= COMFY_RESOLUTION_CHANGE_CAPACITY)
 				scriptedLastRect = COMFY_RESOLUTION_CHANGE_CAPACITY - 1;
+
+			if (_usesAnimFile && visible && scriptedLastRect != 0xFFFF) {
+				for (uint i = 0; i <= scriptedLastRect; i++) {
+					VideoRectRecord &drawRecord = _keymaskRects[i];
+					if (drawRecord.area) {
+						if (_isPanther)
+							renderQueueDrawCommand(drawRecord.left, drawRecord.top, drawRecord.area, 1);
+						else
+							spriteBlitClipped((int16)drawRecord.area, drawRecord.left, drawRecord.top);
+					}
+				}
+			}
 		} else {
 			int16 wordsLeft = (int16)(scriptReadWord(pc) - 1);
 			pc += 2;
@@ -1158,16 +1585,21 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 					pc += 2;
 				}
 
-				if (spriteId) {
+				if (visible && spriteId) {
 					SpriteResource *sprite = spriteGetPtr((int16)spriteId);
-					if (sprite)
-						spriteBlitClipped((int16)spriteId, drawX + dx - sprite->header.hotspotX,
-							drawY + dy - sprite->header.hotspotY);
+					if (sprite) {
+						int16 spriteX = drawX + dx - sprite->header.hotspotX;
+						int16 spriteY = drawY + dy - sprite->header.hotspotY;
+						if (_isPanther && (_videoMode == 2 || _videoMode == 4))
+							renderQueueDrawCommand(spriteX, spriteY, spriteId, 1);
+						else
+							spriteBlitClipped((int16)spriteId, spriteX, spriteY);
+					}
 				}
 			}
 		}
 
-		if (_videoMode == 2 && scriptedLastRect != 0xFFFF) {
+		if ((_videoMode == 2 || _videoMode == 4) && scriptedLastRect != 0xFFFF) {
 			newRect = _keymaskCurrentRecord;
 		}
 	} else if (selector == 0x00FFFFFF) {
@@ -1179,7 +1611,12 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 		newRect.right = drawX + frameWidth;
 		newRect.bottom = drawY + frameHeight;
 		newRect.area = frameWidth * frameHeight;
-		animFrameBlitAt(drawX, drawY);
+		if (visible) {
+			if (_isPanther && (_videoMode == 2 || _videoMode == 4))
+				renderQueueDrawCommand(drawX, drawY, selector, 2);
+			else
+				animFrameBlitAt(drawX, drawY);
+		}
 	} else if (selector) {
 		SpriteResource *sprite = spriteLookup((uint16)selector, drawX, drawY);
 		if (sprite) {
@@ -1188,13 +1625,18 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 			newRect.right = newRect.left + sprite->header.width;
 			newRect.bottom = newRect.top + sprite->header.height;
 			newRect.area = sprite->header.width * sprite->header.height;
-			spriteBlitClipped((int16)selector, drawX - sprite->header.hotspotX, drawY - sprite->header.hotspotY);
+			if (visible) {
+				int16 spriteX = drawX - sprite->header.hotspotX;
+				int16 spriteY = drawY - sprite->header.hotspotY;
+				if (_isPanther && (_videoMode == 2 || _videoMode == 4))
+					renderQueueDrawCommand(spriteX, spriteY, selector, 1);
+				else
+					spriteBlitClipped((int16)selector, spriteX, spriteY);
+			}
 		}
 	}
-	animFrameRecordVocCounter(2);
-
-	if (_videoMode == 2) {
-		byte newVisible = actorReadU8(*actor, kActorVisible);
+	if (_videoMode == 2 || _videoMode == 4) {
+		byte newVisible = visible ? 1 : 0;
 		bool changed = oldSelector != selector || oldVisible != newVisible;
 		if (oldRect.left != newRect.left || oldRect.top != newRect.top ||
 				oldRect.right != newRect.right || oldRect.bottom != newRect.bottom || oldRect.area != newRect.area)
@@ -1221,39 +1663,59 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 					bool equal = oldItem && newItem && oldItem->left == newItem->left && oldItem->top == newItem->top &&
 						oldItem->right == newItem->right && oldItem->bottom == newItem->bottom && oldItem->area == newItem->area;
 					if (!equal) {
-						if (oldItem)
-							videoFindBestMode(*oldItem);
-
-						if (newItem)
-							videoFindBestMode(*newItem);
+						if (oldItem) {
+							VideoRectRecord dirtyRect = *oldItem;
+							dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) *
+								(dirtyRect.bottom - dirtyRect.top);
+							videoFindBestMode(dirtyRect);
+						}
+
+						if (newItem) {
+							VideoRectRecord dirtyRect = *newItem;
+							dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) *
+								(dirtyRect.bottom - dirtyRect.top);
+							videoFindBestMode(dirtyRect);
+						}
 					}
 				}
 
 				comparedScriptRects = true;
 			} else if (newScripted && scriptedLastRect != 0xFFFF) {
-				for (uint i = 0; i <= scriptedLastRect; i++)
-					videoFindBestMode(_keymaskRects[i]);
-			} else if (!newScripted) {
+				for (uint i = 0; i <= scriptedLastRect; i++) {
+					VideoRectRecord dirtyRect = _keymaskRects[i];
+					dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) *
+						(dirtyRect.bottom - dirtyRect.top);
+					videoFindBestMode(dirtyRect);
+				}
+			} else if (!newScripted && selector != 0x00FFFFFF) {
 				videoFindBestMode(newRect);
 			}
 
 			if (!comparedScriptRects) {
 				if (oldScripted && oldScriptedLastRect != 0xFFFF) {
-					for (uint i = 0; i <= oldScriptedLastRect; i++)
-						videoFindBestMode(_keymaskOldRects[i]);
+					for (uint i = 0; i <= oldScriptedLastRect; i++) {
+						VideoRectRecord dirtyRect = _keymaskOldRects[i];
+						dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) *
+							(dirtyRect.bottom - dirtyRect.top);
+						videoFindBestMode(dirtyRect);
+					}
+				} else if (oldSelector == 0x00FFFFFF) {
+					animFrameInvalidateRects(oldRect.left, oldRect.top, 0);
 				} else if (!oldScripted) {
 					videoFindBestMode(oldRect);
 				}
 			}
 		}
 
-		actorWriteU8(*actor, kActorCachedVisible, newVisible);
-		actorWriteU32(*actor, kActorCachedSprite, selector);
+		actorWriteU8(*actor, _actorCachedVisibleOffset, newVisible);
+		actorWriteU32(*actor, _actorCachedSpriteOffset, selector);
 		actorWriteCachedRect(*actor, newRect);
 	}
 
-	actorDrawList(actorReadU16(*actor, kActorChildHead), drawX, drawY);
-	return animFrameShouldDraw(2);
+	if (!_usesAnimFile)
+		animFrameRecordVocCounter(2);
+
+	actorDrawList(actorReadU16(*actor, kActorChildHead), drawX, drawY, visible);
 }
 
 
diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
index 3138bc9f689..140073eac85 100644
--- a/engines/comfy/anim_file.cpp
+++ b/engines/comfy/anim_file.cpp
@@ -22,6 +22,7 @@
 #include "comfy/comfy.h"
 #include "comfy/midiplyr/midiplyr.h"
 
+#include "common/debug.h"
 #include "common/endian.h"
 
 namespace Comfy {
@@ -125,6 +126,7 @@ void ComfyEngine::animFileShutdown() {
 	_animFileData.clear();
 	_animIndexTable.clear();
 	_animIndexLoaded = false;
+	_animPantherFormat = false;
 }
 
 void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 actorSceneHandle) {
@@ -139,10 +141,11 @@ void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 ac
 
 	memcpy(_animFrameHeader, &_animFileData[offset], sizeof(_animFrameHeader));
 	uint16 magic = READ_LE_UINT16(_animFrameHeader);
-	if (magic != COMFY_ANMFRAME_MAGIC && magic != COMFY_ANMFRAME_PANTHER_MAGIC)
+	uint16 expectedMagic = _animPantherFormat ? COMFY_ANMFRAME_PANTHER_MAGIC : COMFY_ANMFRAME_MAGIC;
+	if (magic != expectedMagic)
 		error("Invalid frame header in ANMFILE.DAT for animation %u", (uint)animIndex);
 
-	_animFrameBuffer.resize(COMFY_ANMFRAME_BYTES);
+	_animFrameBuffer.resize(framebufferBytes());
 	memset(&_animFrameBuffer[0], 0xFF, _animFrameBuffer.size());
 	_animFrameStorage.clear();
 	memset(_animStorageChunkFileOffsets, 0, sizeof(_animStorageChunkFileOffsets));
@@ -153,6 +156,7 @@ void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 ac
 	_animFrameCommandArgument = 0;
 	_animFrameCommandFlag = false;
 	_animPosition = offset + COMFY_ANMFILE_HEADER_BYTES;
+	_animSoundDataPosition = 0;
 	_animCurrentIndex = animIndex;
 	_animCurrentActorSceneHandle = actorSceneHandle;
 	_animCurrentFrameKey = frameKey;
@@ -163,6 +167,9 @@ void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 ac
 	_animVocDeltaA = 0;
 	_animActive = true;
 	_animFrameReady = false;
+	debug(5, "COMFY ANM: load index=%u offset=%u size=%u width=%u height=%u vocClock=%u",
+		animIndex, offset, (uint)_animFileData.size(), READ_LE_UINT16(_animFrameHeader + 10),
+		READ_LE_UINT16(_animFrameHeader + 12), _animVocClockHz);
 
 	if (actorSceneHandle < _sceneHandles.size()) {
 		Actor *actor = actorGetPtr(sceneGetHandle(actorSceneHandle));
@@ -258,7 +265,7 @@ uint32 ComfyEngine::animDecodePanther(const byte *source, uint32 sourceSize) {
 			uint16 runCount = READ_LE_UINT16(source + sourcePosition);
 			sourcePosition += 2;
 			if (runCount & 0x4000) {
-				destinationPosition += (uint32)(uint16)(0 - runCount) * COMFY_SCREEN_WIDTH;
+				destinationPosition += (uint32)(uint16)(0 - runCount) * _logicalScreenWidth;
 				continue;
 			}
 
@@ -282,7 +289,8 @@ uint32 ComfyEngine::animDecodePanther(const byte *source, uint32 sourceSize) {
 						written += 2;
 					}
 				} else {
-					uint16 count = MIN<uint32>(control, sourceSize - sourcePosition);
+					uint16 count = (uint16)control * 2;
+					count = MIN<uint32>(count, sourceSize - sourcePosition);
 					count = MIN<uint32>(count, _animFrameBuffer.size() - destinationPosition);
 					memcpy(&_animFrameBuffer[destinationPosition], source + sourcePosition, count);
 					sourcePosition += count;
@@ -293,7 +301,7 @@ uint32 ComfyEngine::animDecodePanther(const byte *source, uint32 sourceSize) {
 				runCount--;
 			}
 
-			destinationPosition = rowStart + COMFY_SCREEN_WIDTH;
+			destinationPosition = rowStart + _logicalScreenWidth;
 			rows--;
 		}
 
@@ -333,8 +341,8 @@ uint32 ComfyEngine::animDecodePanther(const byte *source, uint32 sourceSize) {
 			remaining -= count;
 		}
 
-		if (width < COMFY_SCREEN_WIDTH)
-			destinationPosition += COMFY_SCREEN_WIDTH - width;
+		if (width < _logicalScreenWidth)
+			destinationPosition += _logicalScreenWidth - width;
 	}
 
 	return written;
@@ -372,6 +380,9 @@ void ComfyEngine::animFileTickCommands() {
 		uint16 command = READ_LE_UINT16(header);
 		uint32 rawCommandSize = _animPantherFormat ? READ_LE_UINT32(header + 2) : READ_LE_UINT16(header + 2);
 		uint32 commandSize = _animPantherFormat ? rawCommandSize & 0xFFFF : rawCommandSize;
+		debug(5, "COMFY ANM: index=%u position=%u command=0x%04X size=%u argument=%u",
+			_animCurrentIndex, _animPosition, command, commandSize,
+			_animPantherFormat ? READ_LE_UINT16(header + 6) : 0);
 		if (commandSize < headerSize || commandSize > _animFileData.size() - _animPosition)
 			error("Invalid animation command size in ANMFILE.DAT");
 
@@ -387,10 +398,13 @@ void ComfyEngine::animFileTickCommands() {
 			_animFrameStorage.resize(oldSize + payloadSize);
 			if (payloadSize)
 				memcpy(&_animFrameStorage[oldSize], payload, payloadSize);
+
+			if (_animPantherFormat)
+				_animSoundDataPosition += payloadSize;
 		} else if (command == kAnimCommandDirtyRect) {
 			_animFrameCommandDataSize = payloadSize;
-			_animFrameCommandFlag = _animPantherFormat && (rawCommandSize & 0x80000000) != 0;
-			_animFrameCommandArgument = _animPantherFormat ? (rawCommandSize >> 16) & 0x7FF : payloadSize;
+			_animFrameCommandFlag = false;
+			_animFrameCommandArgument = _animPantherFormat ? READ_LE_UINT16(header + 6) : payloadSize;
 			memset(_animFrameCommandData, 0, sizeof(_animFrameCommandData));
 			memcpy(_animFrameCommandData, payload, MIN<uint32>(payloadSize, sizeof(_animFrameCommandData)));
 		} else if (command == kAnimCommandFrame) {
@@ -492,16 +506,21 @@ void ComfyEngine::animFrameSetReady(bool ready) {
 bool ComfyEngine::animFrameBlitAt(int16 x, int16 y) {
 	if (_animFrameBuffer.empty() || !_framebufPtr)
 		return false;
+	if (!_isPanther)
+		animFrameInvalidateRects(x, y, 1);
 
-	uint16 rectCount = MIN<uint16>(_animFrameCommandDataSize / 4,
-		sizeof(_animFrameCommandData) / 4);
+	uint16 frameWidth = 0;
+	uint16 frameHeight = 0;
+	if (!animFrameGetDimensions(frameWidth, frameHeight))
+		return false;
+
+	uint16 rectCount = _resolutionChangeCount;
 	for (uint i = 0; i < rectCount; i++) {
-		uint16 start = READ_LE_UINT16(_animFrameCommandData + i * 4);
-		uint16 end = READ_LE_UINT16(_animFrameCommandData + i * 4 + 2);
-		int16 left = x + (start % (COMFY_SCREEN_WIDTH / 4)) * 4;
-		int16 top = y + (start / (COMFY_SCREEN_WIDTH / 4)) * 4;
-		int16 right = x + ((end % (COMFY_SCREEN_WIDTH / 4)) + 1) * 4;
-		int16 bottom = y + ((end / (COMFY_SCREEN_WIDTH / 4)) + 1) * 4;
+		VideoRectRecord &dirtyRect = _resolutionChanges[i];
+		int16 left = MAX<int16>(dirtyRect.left, x);
+		int16 top = MAX<int16>(dirtyRect.top, y);
+		int16 right = MIN<int16>(dirtyRect.right, x + frameWidth);
+		int16 bottom = MIN<int16>(dirtyRect.bottom, y + frameHeight);
 
 		int16 clippedLeft = MAX<int16>(left, 0);
 		int16 clippedTop = MAX<int16>(top, 0);
@@ -511,14 +530,27 @@ bool ComfyEngine::animFrameBlitAt(int16 x, int16 y) {
 			continue;
 
 		for (int16 row = clippedTop; row < clippedBottom; row++) {
-			uint32 sourceOffset = (uint32)(row - y) * COMFY_SCREEN_WIDTH + clippedLeft - x;
+			uint32 sourceOffset = (uint32)(row - y) * _logicalScreenWidth + clippedLeft - x;
 			uint32 destinationOffset = (uint32)row * _logicalScreenWidth + clippedLeft;
 			uint32 width = clippedRight - clippedLeft;
 			if (sourceOffset >= _animFrameBuffer.size())
 				break;
 
 			width = MIN<uint32>(width, _animFrameBuffer.size() - sourceOffset);
-			memcpy(_framebufPtr + destinationOffset, &_animFrameBuffer[sourceOffset], width);
+			uint32 column = 0;
+			while (column < width) {
+				while (column < width && _animFrameBuffer[sourceOffset + column] == 0xFF)
+					column++;
+
+				uint32 spanStart = column;
+				while (column < width && _animFrameBuffer[sourceOffset + column] != 0xFF)
+					column++;
+
+				if (column != spanStart) {
+					memcpy(_framebufPtr + destinationOffset + spanStart,
+						&_animFrameBuffer[sourceOffset + spanStart], column - spanStart);
+				}
+			}
 		}
 	}
 
@@ -526,13 +558,46 @@ bool ComfyEngine::animFrameBlitAt(int16 x, int16 y) {
 	return true;
 }
 
-void ComfyEngine::animFrameInvalidateRects(int16, int16, byte) {
+void ComfyEngine::animFrameInvalidateRects(int16 x, int16 y, byte mode) {
 	if (_animFrameBuffer.empty())
 		return;
 
-	// The original feeds these rectangles to its partial-update compositor.
-	// ScummVM presents the engine framebuffer as one dirty surface.
-	renderSetDirty();
+	uint16 rectCount = MIN<uint16>(_animFrameCommandDataSize / 4,
+		sizeof(_animFrameCommandData) / 4);
+	uint16 splitIndex = _animFrameCommandArgument / 4;
+	_animFrameDirtyRectCount = 0;
+	for (uint i = 0; i < rectCount; i++) {
+		uint16 start = READ_LE_UINT16(_animFrameCommandData + i * 4);
+		uint16 end = READ_LE_UINT16(_animFrameCommandData + i * 4 + 2);
+		VideoRectRecord rect;
+		rect.left = x + (start % (_logicalScreenWidth / 4)) * 4;
+		rect.top = y + (start / (_logicalScreenWidth / 4)) * 4;
+		rect.right = x + ((end % (_logicalScreenWidth / 4)) + 1) * 4;
+		rect.bottom = y + ((end / (_logicalScreenWidth / 4)) + 1) * 4;
+		rect.area = (uint32)(rect.right - rect.left) * (rect.bottom - rect.top);
+
+		if (i < splitIndex) {
+			if (!mode)
+				videoFindBestMode(rect);
+
+			continue;
+		}
+
+		if (_animFrameDirtyRectCount < COMFY_ANIM_DIRTY_RECT_CAPACITY) {
+			_animFrameDirtyRects[_animFrameDirtyRectCount] = rect;
+			_animFrameDirtyRectCount++;
+		} else {
+			_animFrameDirtyRectCount = 1;
+			_animFrameDirtyRects[0].left = 0;
+			_animFrameDirtyRects[0].top = 0;
+			_animFrameDirtyRects[0].right = _logicalScreenWidth;
+			_animFrameDirtyRects[0].bottom = _logicalScreenHeight;
+			_animFrameDirtyRects[0].area = framebufferBytes();
+		}
+
+		if (mode)
+			videoFindBestMode(rect);
+	}
 }
 
 bool ComfyEngine::animFrameGetDimensions(uint16 &width, uint16 &height) {
@@ -552,24 +617,35 @@ bool ComfyEngine::animFrameGetDimensions(uint16 &width, uint16 &height) {
 
 void ComfyEngine::animFrameClear() {
 	if (!_animFrameBuffer.empty())
-		memset(&_animFrameBuffer[0], 0xFF, COMFY_ANMFRAME_BYTES);
+		memset(&_animFrameBuffer[0], 0xFF, _animFrameBuffer.size());
 }
 
 void ComfyEngine::animFilePackState(byte *state) {
-	memset(state, 0, COMFY_ANM_STATE_BYTES);
+	memset(state, 0, _animPantherFormat ? COMFY_PANTHER_ANM_STATE_BYTES : COMFY_ANM_STATE_BYTES);
 	memcpy(state, _animFrameHeader, sizeof(_animFrameHeader));
 	WRITE_LE_UINT16(state + 0x10, _animCurrentIndex);
 	WRITE_LE_UINT16(state + 0x12, _animVocTargetCounter);
 	state[0x14] = _animActive;
-	state[0x15] = !_animFrameBuffer.empty();
-	state[0x16] = _animFrameReady;
-	WRITE_LE_UINT16(state + 0x17, _animCurrentFrameKey);
-	state[0x19] = _animUsesWaveVocCounter;
-	WRITE_LE_UINT16(state + 0x1A, _animCurrentActorSceneHandle);
-	WRITE_LE_UINT16(state + 0x1C, _animVocDeltaA);
-	WRITE_LE_UINT16(state + 0x1E, _animVocDeltaB);
-	WRITE_LE_UINT32(state + 0x20, _midiPlyrDriver ? _midiPlyrDriver->getVocCounter() : 0);
-	WRITE_LE_UINT32(state + 0x24, _animFrameStorage.size());
+	if (_animPantherFormat) {
+		state[0x15] = _animFrameReady;
+		WRITE_LE_UINT16(state + 0x16, _animCurrentFrameKey);
+		state[0x18] = _animUsesWaveVocCounter;
+		WRITE_LE_UINT16(state + 0x19, _animCurrentActorSceneHandle);
+		WRITE_LE_UINT16(state + 0x1B, _animVocDeltaA);
+		WRITE_LE_UINT16(state + 0x1D, _animVocDeltaB);
+		WRITE_LE_UINT32(state + 0x1F, _midiPlyrDriver ? _midiPlyrDriver->getVocCounter() : 0);
+		WRITE_LE_UINT32(state + 0x23, _animSoundDataPosition);
+	} else {
+		state[0x15] = !_animFrameBuffer.empty();
+		state[0x16] = _animFrameReady;
+		WRITE_LE_UINT16(state + 0x17, _animCurrentFrameKey);
+		state[0x19] = _animUsesWaveVocCounter;
+		WRITE_LE_UINT16(state + 0x1A, _animCurrentActorSceneHandle);
+		WRITE_LE_UINT16(state + 0x1C, _animVocDeltaA);
+		WRITE_LE_UINT16(state + 0x1E, _animVocDeltaB);
+		WRITE_LE_UINT32(state + 0x20, _midiPlyrDriver ? _midiPlyrDriver->getVocCounter() : 0);
+		WRITE_LE_UINT32(state + 0x24, _animFrameStorage.size());
+	}
 
 	uint32 streamPosition = 0;
 	if (_animCurrentIndex < _animIndexTable.size()) {
@@ -578,9 +654,11 @@ void ComfyEngine::animFilePackState(byte *state) {
 			streamPosition = _animPosition - frameStart;
 	}
 
-	WRITE_LE_UINT32(state + 0x28, streamPosition);
+	uint32 streamPositionOffset = _animPantherFormat ? 0x27 : 0x28;
+	uint32 chunkTableOffset = _animPantherFormat ? 0x2B : 0x2C;
+	WRITE_LE_UINT32(state + streamPositionOffset, streamPosition);
 	for (uint i = 0; i < 6; i++) {
-		byte *chunk = state + 0x2C + i * 0x0A;
+		byte *chunk = state + chunkTableOffset + i * 0x0A;
 		WRITE_LE_UINT32(chunk, _animStorageChunkFileOffsets[i]);
 		WRITE_LE_UINT32(chunk + 4, _animStorageChunkOffsets[i]);
 		WRITE_LE_UINT16(chunk + 8, _animStorageChunkSizes[i]);
@@ -592,7 +670,7 @@ void ComfyEngine::animFileRestoreStreamPosition(const byte *state) {
 		return;
 
 	uint32 frameStart = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
-	uint32 streamPosition = READ_LE_UINT32(state + 0x28);
+	uint32 streamPosition = READ_LE_UINT32(state + (_animPantherFormat ? 0x27 : 0x28));
 	if (frameStart > _animFileData.size() || streamPosition > _animFileData.size() - frameStart)
 		error("Invalid restored stream position in ANMFILE.DAT");
 
@@ -636,8 +714,8 @@ void ComfyEngine::animFileRebuildStorage(uint32 targetSize) {
 				memcpy(&_animFrameStorage[oldSize], payload, copySize);
 		} else if (command == kAnimCommandDirtyRect) {
 			_animFrameCommandDataSize = payloadSize;
-			_animFrameCommandFlag = _animPantherFormat && (rawCommandSize & 0x80000000) != 0;
-			_animFrameCommandArgument = _animPantherFormat ? (rawCommandSize >> 16) & 0x7FF : payloadSize;
+			_animFrameCommandFlag = false;
+			_animFrameCommandArgument = _animPantherFormat ? READ_LE_UINT16(header + 6) : payloadSize;
 			memset(_animFrameCommandData, 0, sizeof(_animFrameCommandData));
 			memcpy(_animFrameCommandData, payload, MIN<uint32>(payloadSize, sizeof(_animFrameCommandData)));
 		}
@@ -652,16 +730,38 @@ void ComfyEngine::animFileUnpackState(const byte *state) {
 	_animCurrentIndex = READ_LE_UINT16(state + 0x10);
 	_animVocTargetCounter = READ_LE_UINT16(state + 0x12);
 	_animActive = state[0x14] != 0;
-	_animFrameReady = state[0x16] != 0;
-	_animCurrentFrameKey = READ_LE_UINT16(state + 0x17);
-	_animUsesWaveVocCounter = state[0x19] != 0;
-	_animCurrentActorSceneHandle = READ_LE_UINT16(state + 0x1A);
-	_animVocDeltaA = READ_LE_UINT16(state + 0x1C);
-	_animVocDeltaB = READ_LE_UINT16(state + 0x1E);
+	uint32 chunkTableOffset = 0;
+	uint32 vocCounterOffset = 0;
+	if (_animPantherFormat) {
+		_animFrameReady = state[0x15] != 0;
+		_animCurrentFrameKey = READ_LE_UINT16(state + 0x16);
+		_animUsesWaveVocCounter = state[0x18] != 0;
+		_animCurrentActorSceneHandle = READ_LE_UINT16(state + 0x19);
+		_animVocDeltaA = READ_LE_UINT16(state + 0x1B);
+		_animVocDeltaB = READ_LE_UINT16(state + 0x1D);
+		_animSoundDataPosition = READ_LE_UINT32(state + 0x23);
+		chunkTableOffset = 0x2B;
+		vocCounterOffset = 0x1F;
+	} else {
+		_animSoundDataPosition = 0;
+		_animFrameReady = state[0x16] != 0;
+		_animCurrentFrameKey = READ_LE_UINT16(state + 0x17);
+		_animUsesWaveVocCounter = state[0x19] != 0;
+		_animCurrentActorSceneHandle = READ_LE_UINT16(state + 0x1A);
+		_animVocDeltaA = READ_LE_UINT16(state + 0x1C);
+		_animVocDeltaB = READ_LE_UINT16(state + 0x1E);
+		chunkTableOffset = 0x2C;
+		vocCounterOffset = 0x20;
+	}
+
+	uint32 storageSize = 0;
 	for (uint i = 0; i < 6; i++) {
-		_animStorageChunkFileOffsets[i] = READ_LE_UINT32(state + 0x2C + i * 0x0A);
-		_animStorageChunkOffsets[i] = READ_LE_UINT32(state + 0x30 + i * 0x0A);
-		_animStorageChunkSizes[i] = READ_LE_UINT16(state + 0x34 + i * 0x0A);
+		const byte *chunk = state + chunkTableOffset + i * 0x0A;
+		_animStorageChunkFileOffsets[i] = READ_LE_UINT32(chunk);
+		_animStorageChunkOffsets[i] = READ_LE_UINT32(chunk + 4);
+		_animStorageChunkSizes[i] = READ_LE_UINT16(chunk + 8);
+		storageSize = MAX<uint32>(storageSize,
+			_animStorageChunkOffsets[i] + _animStorageChunkSizes[i]);
 	}
 
 	if (_animCurrentActorSceneHandle == 0)
@@ -673,14 +773,14 @@ void ComfyEngine::animFileUnpackState(const byte *state) {
 			actorWriteU32(*actor, kActorSpriteSelector, 0x00FFFFFF);
 	}
 
-	_animFrameBuffer.resize(COMFY_ANMFRAME_BYTES);
+	_animFrameBuffer.resize(framebufferBytes());
 	animFrameClear();
 	if (!_animActive)
 		return;
 
 	animFileRestoreStreamPosition(state);
-	animFileRebuildStorage(READ_LE_UINT32(state + 0x24));
-	animFrameSetVocCounter(READ_LE_UINT32(state + 0x20));
+	animFileRebuildStorage(_animPantherFormat ? storageSize : READ_LE_UINT32(state + 0x24));
+	animFrameSetVocCounter(READ_LE_UINT32(state + vocCounterOffset));
 }
 
 void ComfyEngine::animFrameInvalidateActorRect() {
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index db991375caa..6ffbf1667e3 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -48,12 +48,27 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ComfyGameDescription *gameDesc) :
 	memset(_selectorPoolEntries, 0, sizeof(_selectorPoolEntries));
 	memset(_sceneEntryVolumes, 0, sizeof(_sceneEntryVolumes));
 	memset(_sceneEntryCompletionKeys, 0, sizeof(_sceneEntryCompletionKeys));
-	memset(_wcomfy99FeatureWords, 0, sizeof(_wcomfy99FeatureWords));
 	memset(_animFrameHeader, 0, sizeof(_animFrameHeader));
 	memset(_animFrameCommandData, 0, sizeof(_animFrameCommandData));
 	memset(_animStorageChunkFileOffsets, 0, sizeof(_animStorageChunkFileOffsets));
 	memset(_animStorageChunkOffsets, 0, sizeof(_animStorageChunkOffsets));
 	memset(_animStorageChunkSizes, 0, sizeof(_animStorageChunkSizes));
+	if (_engineVersion == 3) {
+		_actorSize = COMFY_ACTOR_SIZE_V3;
+		_actorCachedVisibleOffset = 0x51;
+		_actorCachedSpriteOffset = 0x52;
+		_actorCachedAreaIs32Bit = true;
+	}
+
+	if (!strcmp(gameDesc->desc.gameId, "panther")) {
+		_isPanther = true;
+		_actorSize = COMFY_PANTHER_ACTOR_SIZE;
+		_actorCachedVisibleOffset = 0x51;
+		_actorCachedSpriteOffset = 0x52;
+		_actorCachedAreaIs32Bit = true;
+		_vocQueueCapacity = COMFY_PANTHER_VOC_QUEUE_CAPACITY;
+	}
+
 	g_engine = this;
 }
 
@@ -409,18 +424,10 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 		}
 
 		uint16 frame = actorGetFrame();
-		if (frame) {
-			SpriteResource *background = spriteGetPtr((int16)frame);
-			if (background && background->header.width == _logicalScreenWidth &&
-					background->header.height == _logicalScreenHeight && !background->pixels.empty()) {
-				spriteBlitRle(&background->pixels[0], background->pixels.size());
-				videoSetResolution();
-			} else {
-				uint16 clear = background && background->pixels.size() > 3 ? background->pixels[3] : 0;
-				framebufClear(clear);
-				videoSetResolution();
-			}
-		}
+		if (frame)
+			backgroundTransitionFrames(frame, _backgroundFrame);
+
+		_backgroundFrame = frame;
 
 		if (actorDraw(rootIndex, 0, 0)) {
 			paletteVsyncFlip();
@@ -475,6 +482,9 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 				vocQueuePlayAll();
 
 			keyBitSet(0x42);
+			frame = actorGetFrame();
+			if (frame)
+				backgroundTransitionFrames(frame, _backgroundFrame);
 		} else {
 			actorSetAllVisible();
 		}
@@ -526,7 +536,7 @@ void ComfyEngine::sceneTickEvent() {
 					keyBitSet(entry.arguments[0]);
 
 				_soundEventIndex++;
-				if (_soundEventIndex == COMFY_VOC_QUEUE_CAPACITY)
+				if (_soundEventIndex == _vocQueueCapacity)
 					_soundEventIndex = 0;
 
 				if (_soundEventIndex == _soundEventMaximum) {
@@ -555,9 +565,9 @@ void ComfyEngine::sceneTickEvent() {
 		return;
 	}
 
-	VocQueueEntry &entry = _vocQueue[_soundEventIndex % COMFY_VOC_QUEUE_CAPACITY];
+	VocQueueEntry &entry = _vocQueue[_soundEventIndex % _vocQueueCapacity];
 	uint16 currentSubIndex = _soundEventSubIndex;
-	if (entry.state == 0xFFFF) {
+	if (entry.state == 0xFFFF && (entry.soundId != 0xFFFF || !animFrameIsReady())) {
 		entry.state = 0;
 		_soundEventSubIndex = 0xFFFF;
 		soundPlayEntry(entry.soundId);
@@ -571,7 +581,7 @@ void ComfyEngine::sceneTickEvent() {
 			if (entry.argumentCount)
 				keyBitSet(entry.arguments[0]);
 
-			_soundEventIndex = (_soundEventIndex + 1) % COMFY_VOC_QUEUE_CAPACITY;
+			_soundEventIndex = (_soundEventIndex + 1) % _vocQueueCapacity;
 			if (_soundEventIndex == _soundEventMaximum) {
 				keyBitClear(1);
 				keyBitClear(4);
@@ -632,7 +642,7 @@ void ComfyEngine::midiPollChannels(uint16 ticks) {
 }
 
 bool ComfyEngine::vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc) {
-	uint16 next = (_soundEventMaximum + 1) % COMFY_VOC_QUEUE_CAPACITY;
+	uint16 next = (_soundEventMaximum + 1) % _vocQueueCapacity;
 	if (next == _soundEventIndex) {
 		debug(5, "COMFY VOC: queue full; rejected id=%u args=%u index=%u maximum=%u",
 			soundId, argumentCount, _soundEventIndex, _soundEventMaximum);
@@ -663,7 +673,7 @@ bool ComfyEngine::vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc)
 		return true;
 	}
 
-	VocQueueEntry &entry = _vocQueue[_soundEventMaximum % COMFY_VOC_QUEUE_CAPACITY];
+	VocQueueEntry &entry = _vocQueue[_soundEventMaximum % _vocQueueCapacity];
 	entry.soundId = soundId;
 	entry.argumentCount = MIN<uint16>(argumentCount, COMFY_VOC_ARG_CAPACITY);
 	entry.state = 0xFFFF;
@@ -681,7 +691,12 @@ bool ComfyEngine::vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc)
 
 void ComfyEngine::vocQueuePlayAll() {
 	_mixer->stopHandle(_soundHandle);
+	_soundQueueStream = nullptr;
 	_soundCues.clear();
+	_soundNextCue = 0;
+	if (_midiPlyrDriver)
+		_midiPlyrDriver->vocSrResetBlockNo();
+
 	if (_engineVersion == 3) {
 		uint16 slot = _soundEventIndex;
 		while (slot != _soundEventMaximum) {
@@ -690,7 +705,7 @@ void ComfyEngine::vocQueuePlayAll() {
 				keyBitSet(entry.arguments[i]);
 
 			slot++;
-			if (slot == COMFY_VOC_QUEUE_CAPACITY)
+			if (slot == _vocQueueCapacity)
 				slot = 0;
 		}
 
@@ -709,7 +724,7 @@ void ComfyEngine::vocQueuePlayAll() {
 		for (uint i = 0; i < entry.argumentCount && i < COMFY_VOC_ARG_CAPACITY; i++)
 			keyBitSet(entry.arguments[i]);
 
-		slot = (slot + 1) % COMFY_VOC_QUEUE_CAPACITY;
+		slot = (slot + 1) % _vocQueueCapacity;
 	}
 
 	_soundEventMaximum = _soundEventIndex;
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 25452bb07cb..58cc5ea9042 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -39,6 +39,10 @@
 #include "comfy/detection.h"
 #include "comfy/midiplyr/midiplyr.h"
 
+namespace Audio {
+class QueuingAudioStream;
+}
+
 #define COMFY_SCREEN_WIDTH 320
 #define COMFY_SCREEN_HEIGHT 200
 #define COMFY_PANTHER_SCREEN_WIDTH 640
@@ -46,6 +50,7 @@
 #define COMFY_PIT_INPUT_FREQUENCY 1193182
 #define COMFY_PIT_TIMER_DIVISOR 0x2E9B
 #define COMFY_RESOLUTION_CHANGE_CAPACITY 100
+#define COMFY_DRAW_COMMAND_CAPACITY 200
 #define COMFY_PALETTE_BYTES 0x300
 #define COMFY_INPUT_QUEUE_CAPACITY 20
 #define COMFY_KEYBOARD_CONTACT_COUNT 24
@@ -57,15 +62,22 @@
 #define COMFY_RESOURCE_LIST_CAPACITY 32
 #define COMFY_SCENE_ENTRY_OFFSET_CAPACITY 16
 #define COMFY_SCENE_MIDI_INSTANCE_BYTES 0x18C
+#define COMFY_PANTHER_SOUND_STATE_BYTES 0xBE
 #define COMFY_SCENE_MIDI_VERSION_BYTES_CLASSIC 0x167
 #define COMFY_SCENE_VOC_STATE_BYTES_V3 0x24D
 #define COMFY_SCENE_STATE_BYTES_V3 0x17F
+#define COMFY_PANTHER_ACTOR_SIZE 0x56
 #define COMFY_ACTOR_SIZE_V3 0x57
 #define COMFY_SCENE_ACTOR_PC_BYTES 0x320
 #define COMFY_SCENE_FRAME_BYTES 0x4E20
 #define COMFY_SCENE_FRAME_BYTES_V3 0x7530
 #define COMFY_VOC_ARG_CAPACITY 10
 #define COMFY_VOC_QUEUE_CAPACITY 16
+#define COMFY_PANTHER_VOC_QUEUE_CAPACITY 4
+#define COMFY_SOUND_PCM_BLOCK_BYTES 0x4E20
+#define COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES 0x3E80
+#define COMFY_SOUND_PITCH_COUNT_LIMIT 0x13
+#define COMFY_FRAME_LOADER_DATA_BYTES 0x6000
 #define COMFY_VOC_ARG_CAPACITY_1999 12
 #define COMFY_MIDI_QUEUE_CAPACITY 32
 #define COMFY_MIDI_CHANNEL_COUNT 2
@@ -80,10 +92,13 @@
 #define COMFY_ANMFRAME_BYTES 0xFA00
 #define COMFY_ANMFRAME_COMMAND_DATA_BYTES 0x78
 #define COMFY_ANM_STATE_BYTES 0x68
+#define COMFY_PANTHER_ANM_STATE_BYTES 0x67
+#define COMFY_ANIM_DIRTY_RECT_CAPACITY 0x3C
 
 namespace Comfy {
 
 class MidiPlyrDriver;
+struct SoundDecoderState;
 
 #ifdef USE_IMGUI
 void onImGuiInit();
@@ -93,12 +108,14 @@ void onImGuiCleanup();
 
 class ComfyEngine : public Engine {
 private:
+	friend struct SoundDecoderState;
+
 	struct VideoRectRecord {
 		int16 left;
 		int16 top;
 		int16 right;
 		int16 bottom;
-		uint16 area;
+		uint32 area;
 
 		VideoRectRecord() {
 			left = 0;
@@ -109,6 +126,20 @@ private:
 		}
 	};
 
+	struct DrawCommand {
+		int16 x;
+		int16 y;
+		uint32 selector;
+		byte mode;
+
+		DrawCommand() {
+			x = 0;
+			y = 0;
+			selector = 0;
+			mode = 0;
+		}
+	};
+
 	struct InputQueue {
 		uint16 words[COMFY_INPUT_QUEUE_CAPACITY];
 		uint16 readIndex;
@@ -290,11 +321,12 @@ private:
 
 	struct SoundCue {
 		uint16 value;
+		uint32 streamPosition;
 		uint32 counterThreshold;
 	};
 
 	struct Actor {
-		byte raw[COMFY_ACTOR_SIZE];
+		byte raw[COMFY_ACTOR_SIZE_V3];
 	};
 
 	enum ActorOffset {
@@ -332,12 +364,17 @@ private:
 
 	enum ScriptDispatchStatus {
 		kScriptContinue,
-		kScriptYield,
-		kScriptDeactivatedRoot
+		kScriptYield
 	};
 
 	const ComfyGameDescription *_game;
 	byte _engineVersion;
+	bool _isPanther = false;
+	uint16 _actorSize = COMFY_ACTOR_SIZE;
+	uint16 _actorCachedVisibleOffset = kActorCachedVisible;
+	uint16 _actorCachedSpriteOffset = kActorCachedSprite;
+	bool _actorCachedAreaIs32Bit = false;
+	uint16 _vocQueueCapacity = COMFY_VOC_QUEUE_CAPACITY;
 	Common::Path _gameDirectory;
 	Common::Path _introDirectory;
 	Common::Path _gameDataPath;
@@ -349,6 +386,8 @@ private:
 	Graphics::Screen *_screen = nullptr;
 	byte *_framebufPtr = nullptr;
 	byte *_presentBuffer = nullptr;
+	Common::Array<byte> _backgroundFramebuf;
+	uint16 _backgroundFrame = 0;
 	uint16 _logicalScreenWidth;
 	uint16 _logicalScreenHeight;
 	uint16 _videoMode = 2;
@@ -442,6 +481,7 @@ private:
 	Common::Array<byte> _sceneRunBuffer;
 	byte *_sceneRunPtr = nullptr;
 	Common::Array<byte> _scenePoolData;
+	Common::Array<byte> _frameLoaderData;
 	Common::Array<byte> _environmentData;
 	Common::Array<byte> _headerXmsData;
 	Common::Array<byte> _sceneFrameData;
@@ -466,10 +506,15 @@ private:
 	VideoRectRecord _keymaskRects[COMFY_RESOLUTION_CHANGE_CAPACITY];
 	VideoRectRecord _keymaskOldRects[COMFY_RESOLUTION_CHANGE_CAPACITY];
 	VideoRectRecord _keymaskInvalidationRects[COMFY_RESOLUTION_CHANGE_CAPACITY];
+	VideoRectRecord _animFrameDirtyRects[COMFY_ANIM_DIRTY_RECT_CAPACITY];
+	uint16 _animFrameDirtyRectCount = 0;
+	DrawCommand _drawCommands[COMFY_DRAW_COMMAND_CAPACITY];
+	uint16 _drawCommandCount = 0;
 	uint32 _sceneEntryOffsets[COMFY_SCENE_ENTRY_OFFSET_CAPACITY];
 	uint16 _sceneEntryVolumes[COMFY_SCENE_MUSIC_CHANNEL_COUNT];
 	uint16 _sceneEntryCompletionKeys[COMFY_SCENE_MUSIC_CHANNEL_COUNT];
 	uint32 _sceneMidiInstanceOffset = 0;
+	uint32 _sceneSoundStateOffset = 0;
 	uint32 _sceneEntryListOffset = 0;
 	uint32 _sceneActorPcOffset = 0;
 	uint32 _sceneStringTableOffset = 0;
@@ -527,10 +572,6 @@ private:
 	bool _wcomfy99HostMediaValueAvailable = false;
 	uint16 _wcomfy99HostMediaValue = 0;
 	uint16 _wcomfy99HostMediaProgress = 0;
-	uint16 _wcomfy99FeatureWords[16];
-	byte _wcomfy99FeatureWordCount = 0;
-	uint16 _wcomfy99Stub32FirstWord = 0;
-	uint16 _wcomfy99Stub32SecondWord = 0;
 	uint16 _wcomfy99Sensitivity = 0;
 	bool _wcomfy99RecordHostEnabled = false;
 	uint16 _wcomfy99SubsystemWord = 0;
@@ -563,11 +604,40 @@ private:
 	Common::Array<byte> _vocFileData;
 	Common::Array<byte> _soundPcm;
 	Common::Array<SoundCue> _soundCues;
+	SoundDecoderState *_soundDecoderState = nullptr;
 	Audio::SoundHandle _soundHandle;
+	Audio::QueuingAudioStream *_soundQueueStream = nullptr;
+	uint16 _soundWaveBufferIndex = 0;
+	Common::Array<byte> _soundDecoderData;
+	uint32 _soundStreamPosition = 0;
+	uint32 _soundEventArgument = 0;
+	int32 _soundEventLength = 0;
+	uint32 _soundDataBase = 0;
+	uint32 _soundDataEnd = 0;
+	uint32 _soundPlayPosition = 0;
+	uint32 _soundLoopPosition = 0;
+	uint32 _soundCursor = 0;
+	uint32 _soundBlockBase = 0;
+	uint32 _soundRate = 0;
+	uint16 _soundFillCount = 0;
+	int16 _soundLoopCount = 0;
+	byte _soundSample = 0xA5;
+	byte _soundNextSample = 0;
+	bool _soundStopped = true;
+	bool _soundStarted = false;
+	uint16 _soundBitOffset = 0;
+	uint16 _soundLoopBitOffset = 0;
+	uint16 _soundBlockOffset = 0;
+	uint16 _soundBitAccumulator = 1;
+	byte _soundBitWidth = 4;
+	byte _soundPredictorDistance = 1;
+	bool _soundNeedInit = false;
+	Common::Array<byte> _soundPcmBlocks[2];
 	uint16 _soundEntryCount = 0;
 	uint32 _soundSampleRate = 0x2B11;
 	uint _soundNextCue = 0;
 	bool _soundCompressed = false;
+	bool _soundUsesAnimData = false;
 	bool _soundPaused = false;
 	Common::Array<byte> _animFileData;
 	Common::Array<uint32> _animIndexTable;
@@ -579,6 +649,7 @@ private:
 	byte _animFrameHeader[COMFY_ANMFILE_HEADER_BYTES];
 	byte _animFrameCommandData[COMFY_ANMFRAME_COMMAND_DATA_BYTES];
 	uint32 _animPosition = 0;
+	uint32 _animSoundDataPosition = 0;
 	uint16 _animFrameCommandDataSize = 0;
 	uint16 _animFrameCommandArgument = 0;
 	bool _animFrameCommandFlag = false;
@@ -624,8 +695,11 @@ private:
 	void videoPresentFrame();
 	void renderSetDirty();
 	void renderFlushDirty();
+	void renderInvalidateFullFrame();
 	void framebufCopyAll(byte *destination, byte *source);
-	void framebufClear(uint16 color);
+	void framebufClear(byte *destination, uint16 color);
+	void backgroundTransitionFrames(uint16 frame, uint16 previousFrame);
+	void backgroundRestoreDirtyRects();
 	uint32 framebufferBytes();
 	void colorDatOpen();
 	void colorDatClose();
@@ -695,9 +769,10 @@ private:
 	void scenePoolEvict();
 	void scenePoolReserveSlot(uint32 size);
 	SpriteResource *spriteGetPtr(int16 spriteId);
+	void spriteGetConvPtr(int16 spriteId);
 	bool spriteDecompressTile(SpriteResource &sprite, const byte *source, uint32 sourceSize);
 	void spriteBlitClipped(int16 spriteId, int16 x, int16 y);
-	void spriteBlitRle(const byte *source, uint32 sourceSize);
+	void spriteBlitRle(byte *destination, const byte *source, uint32 sourceSize);
 	bool sceneOpen(uint32 sceneEntryListOffset);
 	void sceneShutdown();
 	void sceneEntryReadFromXms(byte *destination, uint16 row, uint16 size);
@@ -731,6 +806,7 @@ private:
 	Actor *actorGetPtr(uint16 actorIndex);
 	void actorSetFrame(int16 frame);
 	uint16 actorGetFrame();
+	void actorSetPos(uint16 mode, int16 value);
 	Actor *actorResolve(uint16 sceneOrActor, uint16 fallbackActor);
 	uint16 actorAlloc(uint16 sceneSlot);
 	void actorFreeSlot(uint16 sceneSlot);
@@ -748,7 +824,12 @@ private:
 	bool actorRunScript(uint16 actorIndex, bool &descendChildren);
 	bool actorTickTree(uint16 actorIndex);
 	bool actorDraw(uint16 actorIndex, int16 x, int16 y);
-	void actorDrawList(uint16 actorIndex, int16 x, int16 y);
+	void actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool visible);
+	bool actorDrawLegacyInternal(uint16 actorIndex, int16 x, int16 y);
+	void actorDrawList(uint16 actorIndex, int16 x, int16 y, bool visible);
+	void renderQueueDrawCommand(int16 x, int16 y, uint32 selector, byte mode);
+	void renderFlushDrawCommands();
+	void renderFlushCachedDirtyRects();
 	uint16 scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &maskRecord,
 		VideoRectRecord *rects, int16 baseX, int16 baseY);
 	void actorEvalFrameSelection(uint16 actorIndex, int16 x, int16 y);
@@ -833,10 +914,15 @@ private:
 	bool soundInit();
 	void soundShutdown();
 	void soundHdrReadFromXms(byte *destination, uint16 index, uint16 size);
-	void soundUnprepareHeader();
+	void soundServiceWaveBuffers();
 	bool soundDecodeEntry(uint16 index);
 	bool soundDecodeCompressedEntry(uint32 dataOffset, uint32 dataSize);
 	bool soundLoadEntry(uint16 index);
+	bool soundPrepareDecoderState(uint16 index);
+	bool soundDecodePcmBlock(uint16 bufferIndex, byte *&buffer, uint32 &decodedSize);
+	bool soundQueuePcmBlock(uint16 bufferIndex);
+	void soundPackState(byte *state);
+	void soundUnpackState(byte *state);
 	void soundPlayEntry(uint16 index);
 	void soundAdvanceTick();
 
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index 15b1ecc92c7..30916c37948 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -390,7 +390,7 @@ bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16
 
 	uint32 stringBytes = _stringTable.size() * sizeof(uint16);
 	uint32 handleBytes = _sceneHandles.size() * sizeof(uint16);
-	uint32 actorBytes = _actors.size() * (_engineVersion == 3 ? COMFY_ACTOR_SIZE_V3 : COMFY_ACTOR_SIZE);
+	uint32 actorBytes = _actors.size() * _actorSize;
 	uint32 keyBytes = ((uint32)keyBitCount + 1) / 8 + 1;
 	_sceneMidiInstanceOffset = 0;
 	if (_engineVersion == 3) {
@@ -398,6 +398,12 @@ bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16
 				COMFY_ANM_STATE_BYTES;
 		_sceneActorPcOffset = _sceneEntryListOffset + COMFY_SCENE_STATE_BYTES_V3;
 		_sceneStringTableOffset = _sceneActorPcOffset + COMFY_SCENE_ACTOR_PC_BYTES;
+	} else if (_isPanther) {
+		_sceneSoundStateOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES;
+		_sceneAnimStateOffset = _sceneSoundStateOffset + COMFY_PANTHER_SOUND_STATE_BYTES;
+		_sceneEntryListOffset = _sceneAnimStateOffset + COMFY_PANTHER_ANM_STATE_BYTES;
+		_sceneActorPcOffset = _sceneEntryListOffset + COMFY_SCENE_STATE_BYTES_V3;
+		_sceneStringTableOffset = _sceneActorPcOffset + COMFY_SCENE_ACTOR_PC_BYTES;
 	} else {
 		_sceneEntryListOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES;
 		_sceneActorPcOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES + midiGetVersion();
@@ -407,8 +413,10 @@ bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16
 	_sceneHandlesOffset = _sceneStringTableOffset + stringBytes;
 	_sceneActorsOffset = _sceneHandlesOffset + handleBytes;
 	_sceneKeyBitsOffset = _sceneActorsOffset + actorBytes;
-	_sceneAnimStateOffset = _engineVersion == 3 ?
-			COMFY_SCENE_MIDI_INSTANCE_BYTES + COMFY_SCENE_VOC_STATE_BYTES_V3 : _sceneKeyBitsOffset + keyBytes;
+	if (_engineVersion == 3)
+		_sceneAnimStateOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES + COMFY_SCENE_VOC_STATE_BYTES_V3;
+	else if (!_isPanther)
+		_sceneAnimStateOffset = _sceneKeyBitsOffset + keyBytes;
 	uint32 sceneBytes = assetsAlignEven32(_sceneKeyBitsOffset + keyBytes);
 	_sceneMemoryBlock.resize(sceneBytes);
 	memset(&_sceneMemoryBlock[0], 0, sceneBytes);
@@ -498,7 +506,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 		return false;
 
 	if (_usesAnimFile) {
-		_animFrameBuffer.resize(COMFY_ANMFRAME_BYTES);
+		_animFrameBuffer.resize(framebufferBytes());
 		memset(&_animFrameBuffer[0], 0, _animFrameBuffer.size());
 	}
 
@@ -647,6 +655,7 @@ void ComfyEngine::assetsUnload(byte freeAudio) {
 	_sceneEntryCount = 0;
 	_sceneEntryFrameSize = 0;
 	_sceneMidiInstanceOffset = 0;
+	_sceneSoundStateOffset = 0;
 	_sceneEntryListOffset = 0;
 	_sceneActorPcOffset = 0;
 	_sceneStringTableOffset = 0;
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index a271ac3ea5d..615d2d5ff7b 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -71,6 +71,21 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 
 		WRITE_LE_UINT16(vocState + 0x1F7, _soundEventIndex);
 		WRITE_LE_UINT16(vocState + 0x1F9, _soundEventMaximum);
+	} else if (_isPanther) {
+		byte *soundState = &_sceneMemoryBlock[_sceneSoundStateOffset];
+		for (uint i = 0; i < COMFY_PANTHER_VOC_QUEUE_CAPACITY; i++) {
+			byte *packedEntry = soundState + i * 0x1A;
+			VocQueueEntry &entry = _vocQueue[i];
+			WRITE_LE_UINT16(packedEntry, entry.soundId);
+			WRITE_LE_UINT16(packedEntry + 2, entry.argumentCount);
+			WRITE_LE_UINT16(packedEntry + 4, entry.state);
+			for (uint argument = 0; argument < COMFY_VOC_ARG_CAPACITY; argument++)
+				WRITE_LE_UINT16(packedEntry + 6 + argument * 2, entry.arguments[argument]);
+		}
+
+		WRITE_LE_UINT16(soundState + 0x68, _soundEventIndex);
+		WRITE_LE_UINT16(soundState + 0x6A, _soundEventMaximum);
+		soundPackState(soundState + 0x6C);
 	}
 
 	byte *sceneEntries = &_sceneMemoryBlock[_sceneEntryListOffset];
@@ -80,14 +95,14 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 	for (uint i = 0; i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
 		WRITE_LE_UINT16(sceneEntries + 5 + i * 2, (uint16)_sceneEntryOffsets[i]);
 
-	if (_engineVersion == 3) {
+	if (_engineVersion == 3 || _isPanther) {
 		for (uint channel = 0; channel < COMFY_SCENE_MUSIC_CHANNEL_COUNT; channel++) {
 			WRITE_LE_UINT16(sceneEntries + 0x25 + channel * 2, _sceneEntryVolumes[channel]);
 			WRITE_LE_UINT16(sceneEntries + 0x31 + channel * 2, _sceneEntryCompletionKeys[channel]);
 		}
 	}
 
-	uint32 channelTableOffset = _engineVersion == 3 ? 0x3D : 0x25;
+	uint32 channelTableOffset = _engineVersion == 3 || _isPanther ? 0x3D : 0x25;
 	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
 		MidiChannelState &state = _midiChannels[channel];
 		byte *packed = sceneEntries + channelTableOffset + channel * 0xA1;
@@ -122,14 +137,14 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 	if (!_sceneHandles.empty())
 		memcpy(&_sceneMemoryBlock[_sceneHandlesOffset], &_sceneHandles[0], _sceneHandles.size() * sizeof(uint16));
 
-	uint32 actorStride = _engineVersion == 3 ? COMFY_ACTOR_SIZE_V3 : sizeof(Actor);
+	uint32 actorStride = _actorSize;
 	for (uint i = 0; i < _actors.size(); i++)
-		memcpy(&_sceneMemoryBlock[_sceneActorsOffset + i * actorStride], &_actors[i], sizeof(Actor));
+		memcpy(&_sceneMemoryBlock[_sceneActorsOffset + i * actorStride], &_actors[i], actorStride);
 
 	if (_keyBits && _keyBitsSize)
 		memcpy(&_sceneMemoryBlock[_sceneKeyBitsOffset], _keyBits, _keyBitsSize);
 
-	if (_engineVersion == 3 && _usesAnimFile)
+	if ((_engineVersion == 3 || _isPanther) && _usesAnimFile)
 		animFilePackState(&_sceneMemoryBlock[_sceneAnimStateOffset]);
 }
 
@@ -200,6 +215,21 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 
 		_soundEventIndex = READ_LE_UINT16(vocState + 0x1F7) % COMFY_VOC_QUEUE_CAPACITY;
 		_soundEventMaximum = READ_LE_UINT16(vocState + 0x1F9) % COMFY_VOC_QUEUE_CAPACITY;
+	} else if (_isPanther) {
+		byte *soundState = &_sceneMemoryBlock[_sceneSoundStateOffset];
+		for (uint i = 0; i < COMFY_PANTHER_VOC_QUEUE_CAPACITY; i++) {
+			byte *packedEntry = soundState + i * 0x1A;
+			VocQueueEntry &entry = _vocQueue[i];
+			entry.soundId = READ_LE_UINT16(packedEntry);
+			entry.argumentCount = MIN<uint16>(READ_LE_UINT16(packedEntry + 2), COMFY_VOC_ARG_CAPACITY);
+			entry.state = READ_LE_UINT16(packedEntry + 4);
+			for (uint argument = 0; argument < COMFY_VOC_ARG_CAPACITY; argument++)
+				entry.arguments[argument] = READ_LE_UINT16(packedEntry + 6 + argument * 2);
+		}
+
+		_soundEventIndex = READ_LE_UINT16(soundState + 0x68) % COMFY_PANTHER_VOC_QUEUE_CAPACITY;
+		_soundEventMaximum = READ_LE_UINT16(soundState + 0x6A) % COMFY_PANTHER_VOC_QUEUE_CAPACITY;
+		soundUnpackState(soundState + 0x6C);
 	}
 
 	byte *sceneEntries = &_sceneMemoryBlock[_sceneEntryListOffset];
@@ -209,14 +239,14 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 	for (uint i = 0; i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
 		_sceneEntryOffsets[i] = READ_LE_UINT16(sceneEntries + 5 + i * 2);
 
-	if (_engineVersion == 3) {
+	if (_engineVersion == 3 || _isPanther) {
 		for (uint channel = 0; channel < COMFY_SCENE_MUSIC_CHANNEL_COUNT; channel++) {
 			_sceneEntryVolumes[channel] = READ_LE_UINT16(sceneEntries + 0x25 + channel * 2);
 			_sceneEntryCompletionKeys[channel] = READ_LE_UINT16(sceneEntries + 0x31 + channel * 2);
 		}
 	}
 
-	uint32 channelTableOffset = _engineVersion == 3 ? 0x3D : 0x25;
+	uint32 channelTableOffset = _engineVersion == 3 || _isPanther ? 0x3D : 0x25;
 	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
 		MidiChannelState &state = _midiChannels[channel];
 		byte *packed = sceneEntries + channelTableOffset + channel * 0xA1;
@@ -246,13 +276,13 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 	memcpy(_actorPcTable, &_sceneMemoryBlock[_sceneActorPcOffset], sizeof(_actorPcTable));
 	memcpy(&_stringTable[0], &_sceneMemoryBlock[_sceneStringTableOffset], _stringTable.size() * sizeof(uint16));
 	memcpy(&_sceneHandles[0], &_sceneMemoryBlock[_sceneHandlesOffset], _sceneHandles.size() * sizeof(uint16));
-	uint32 actorStride = _engineVersion == 3 ? COMFY_ACTOR_SIZE_V3 : sizeof(Actor);
+	uint32 actorStride = _actorSize;
 	for (uint i = 0; i < _actors.size(); i++)
-		memcpy(&_actors[i], &_sceneMemoryBlock[_sceneActorsOffset + i * actorStride], sizeof(Actor));
+		memcpy(&_actors[i], &_sceneMemoryBlock[_sceneActorsOffset + i * actorStride], actorStride);
 	if (_keyBits && _keyBitsSize)
 		memcpy(_keyBits, &_sceneMemoryBlock[_sceneKeyBitsOffset], _keyBitsSize);
 
-	if (_engineVersion == 3 && _usesAnimFile)
+	if ((_engineVersion == 3 || _isPanther) && _usesAnimFile)
 		animFileUnpackState(&_sceneMemoryBlock[_sceneAnimStateOffset]);
 
 }
@@ -268,7 +298,7 @@ void ComfyEngine::sceneGoto(uint16 count) {
 	for (uint i = 0; i < count && i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
 		_sceneEntryOffsets[i] = 0xFFFF;
 
-	if (_engineVersion == 3) {
+	if (_engineVersion == 3 || _isPanther) {
 		for (uint channel = 0; channel < COMFY_SCENE_MUSIC_CHANNEL_COUNT; channel++) {
 			_sceneEntryVolumes[channel] = 100;
 			_sceneEntryCompletionKeys[channel] = 0;
@@ -384,7 +414,7 @@ void ComfyEngine::midiPlaySongAtFrame(uint16 channel, uint16 frame) {
 		return;
 
 	_midiPlyrDriver->musicPlaySong(song, size, channel);
-	if (_engineVersion == 3) {
+	if (_engineVersion == 3 || _isPanther) {
 		_midiPlyrDriver->musicSetVolume(_sceneEntryVolumes[channel], channel);
 		_sceneEntryCompletionKeys[channel] = 0;
 	} else {
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index ce75c51bfd1..2bc62cfe938 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -56,10 +56,10 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			y = (int16)(-(int32)actorReadU32(*target, kActorYFixed) >> 12);
 
 		if (randomize) {
-			if (x != (int16)0xFC18)
+			if (opcode == 0x02 || x != (int16)0xFC18)
 				x = (int16)(((int32)getRandomNumber(0x7FFF) * x) / 0x8000);
 
-			if (y != (int16)0xFC18)
+			if (opcode == 0x02 || y != (int16)0xFC18)
 				y = (int16)(((int32)getRandomNumber(0x7FFF) * y) / 0x8000);
 		}
 
@@ -164,7 +164,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	case 0x09: {
 		actorSetFrame((int16)scriptReadWord(pc));
 		pc += 2;
-		if (_videoMode == 2 || _videoMode == 4)
+		if (!_usesAnimFile && _videoMode == 2)
 			videoSetResolution();
 
 		return kScriptContinue;
@@ -279,6 +279,11 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		else
 			actorInsertSibling(targetIndex, oldParent);
 
+		if (_usesAnimFile && (_videoMode == 2 || _videoMode == 4))
+			renderInvalidateFullFrame();
+		else if (!_usesAnimFile && _videoMode == 2)
+			videoSetResolution();
+
 		return kScriptContinue;
 	}
 
@@ -290,9 +295,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			pc += 2;
 			switch (opcode) {
 			case 0x15:
-				spriteGetPtr((int16)id);
-				if (_spriteConversionLoads.count < COMFY_RESOURCE_LIST_CAPACITY)
-					_spriteConversionLoads.ids[_spriteConversionLoads.count++] = id;
+				spriteGetConvPtr((int16)id);
 				break;
 			case 0x16:
 				soundLoadEntry(id);
@@ -345,6 +348,11 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
+	case 0x1A: {
+		pc = actorPopPc(actor);
+		return kScriptContinue;
+	}
+
 	case 0x1B: {
 		vocQueuePlayAll();
 		return kScriptContinue;
@@ -400,8 +408,6 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		case 8:
 			if (_engineVersion == 3 && channel < COMFY_MIDI_CHANNEL_COUNT && _midiPlyrDriver)
 				_midiPlyrDriver->musicSetLoop(subop == 7 ? 1 : 0, channel);
-			else
-				error("Unknown script opcode 0x1D subopcode 0x%02X at script PC 0x%08X", subop, pc - 2);
 
 			break;
 		default:
@@ -441,8 +447,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			_musicEventFlag = 1;
 		}
 
-		if (bit < 16)
-			_musicEventMask |= 1 << bit;
+		_musicEventMask |= (uint16)(1U << (bit & 0x1F));
 
 		return kScriptYield;
 	}
@@ -453,7 +458,8 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		if (!_pendingScene || (int16)scene < (int16)_pendingScene)
 			_pendingScene = scene;
 
-		renderSetDirty();
+		if (_videoMode == 2 || (_usesAnimFile && _videoMode == 4))
+			renderSetDirty();
 
 		return kScriptYield;
 	}
@@ -463,10 +469,13 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint16 fadeTicks = scriptReadStringIndex(pc + 2);
 		byte brightness = scriptReadByte(pc + 4);
 		pc += 5;
-		if (!brightness)
+		if (!brightness) {
+			actorSetPos(1, (int16)paletteId);
 			paletteLoadWithFade(paletteId, fadeTicks);
-		else
+		} else {
+			actorSetPos(2, (int16)brightness);
 			paletteApplyBrightness(brightness);
+		}
 
 		return kScriptContinue;
 	}
@@ -492,11 +501,6 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x1A: {
-		pc = actorPopPc(actor);
-		return kScriptContinue;
-	}
-
 	case 0x25: {
 		uint16 first = scriptReadWord(pc);
 		uint16 last = scriptReadWord(pc + 2);
@@ -516,8 +520,8 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint16 second = scriptReadWord(pc + 2);
 		uint16 key = scriptReadWord(pc + 4);
 		pc += 6;
-		int16 lhs = first < _midiHandles.size() ? _midiHandles[first] : 0;
-		int16 rhs = opcode == 0x26 ? (int16)second : (second < _midiHandles.size() ? (int16)_midiHandles[second] : 0);
+		int16 lhs = (int16)midiGetHandle(first);
+		int16 rhs = opcode == 0x26 ? (int16)second : (int16)midiGetHandle(second);
 		if (lhs >= rhs)
 			keyBitSet(key);
 
@@ -588,6 +592,15 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			midiStopSong(channel);
 			break;
 		}
+		case 6:
+			if (_engineVersion >= 2) {
+				uint16 channel = scriptReadStringIndex(pc);
+				uint16 volume = scriptReadStringIndex(pc + 2);
+				pc += 6;
+				sceneEntrySetVolume(channel, volume);
+			}
+
+			break;
 		default:
 			error("Unknown script opcode 0x2D subopcode 0x%02X at script PC 0x%08X", subop, pc - 2);
 		}
@@ -601,13 +614,11 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint16 first = scriptReadWord(pc + 3);
 		uint16 second = scriptReadWord(pc + 5);
 		pc += 7;
-		if (destination < _midiHandles.size() && first < _midiHandles.size()) {
-			if (command == '=')
-				midiHandleCopy(destination, first);
-			else if (command == 'm' && second < _midiHandles.size())
-				midiHandleCopy(destination,
-					(int16)midiGetHandle(second) <= (int16)midiGetHandle(first) ? first : second);
-		}
+		if (command == '=')
+			midiHandleCopy(destination, first);
+		else if (command == 'm')
+			midiHandleCopy(destination,
+				(int16)midiGetHandle(second) <= (int16)midiGetHandle(first) ? first : second);
 
 		return kScriptContinue;
 	}
@@ -634,8 +645,13 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		case 3:
 			animFrameSetReady(false);
 			break;
+		case 4:
+		case 5:
+			break;
 		case 6:
-			animFrameInvalidateActorRect();
+			if (_engineVersion == 3)
+				animFrameInvalidateActorRect();
+
 			break;
 		default:
 			error("Unknown script opcode 0x30 subopcode 0x%02X at script PC 0x%08X", subop, pc - 2);
@@ -660,17 +676,28 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		case 0x31: {
 			uint16 count = scriptReadStringIndex(pc);
 			pc += 2;
-			_wcomfy99FeatureWordCount = MIN<uint16>(count, ARRAYSIZE(_wcomfy99FeatureWords));
-			for (uint i = 0; i < _wcomfy99FeatureWordCount; i++)
-				_wcomfy99FeatureWords[i] = scriptReadWord(pc + i * 2);
+			if (_animUsesWaveVocCounter) {
+				uint16 slot = _soundEventMaximum ? _soundEventMaximum - 1 : _vocQueueCapacity - 1;
+				if (_engineVersion == 3) {
+					VocQueueEntry1999 &entry = _vocQueue1999[slot];
+					entry.argumentCount = MIN<uint16>(count, COMFY_VOC_ARG_CAPACITY_1999);
+					for (uint i = 0; i < entry.argumentCount; i++)
+						entry.arguments[i] = scriptReadWord(pc + i * 2);
+				} else {
+					VocQueueEntry &entry = _vocQueue[slot];
+					entry.argumentCount = MIN<uint16>(count, COMFY_VOC_ARG_CAPACITY);
+					for (uint i = 0; i < entry.argumentCount; i++)
+						entry.arguments[i] = scriptReadWord(pc + i * 2);
+				}
+			}
 
 			pc += (uint32)count * 2;
 
 			break;
 		}
 		case 0x32:
-			_wcomfy99Stub32FirstWord = scriptReadWord(pc);
-			_wcomfy99Stub32SecondWord = scriptReadWord(pc + 2);
+			scriptReadStringIndex(pc);
+			scriptReadStringIndex(pc + 2);
 			pc += 4;
 			break;
 		case 0x33: {
@@ -964,12 +991,37 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x54:
-	case 0x55:
+	case 0x54: {
 		if (_engineVersion < 2)
 			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
-	{
+
+		uint32 endPc = scriptReadDword(pc);
 		pc += 4;
+		uint32 size = endPc >= pc ? endPc - pc : 0;
+		size = MIN<uint32>(size, COMFY_FRAME_LOADER_DATA_BYTES);
+		if (pc <= _comfyObjData.size() && size <= _comfyObjData.size() - pc) {
+			_frameLoaderData.resize(COMFY_FRAME_LOADER_DATA_BYTES);
+			if (size)
+				memcpy(&_frameLoaderData[0], &_comfyObjData[pc], size);
+		} else {
+			error("Script opcode 0x54 references data outside COMFY.OBJ");
+		}
+
+		return kScriptContinue;
+	}
+
+	case 0x55: {
+		if (_engineVersion < 2)
+			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
+
+		uint16 source = scriptReadStringIndex(pc);
+		uint16 destination = scriptReadStringIndex(pc + 2);
+		pc += 4;
+		if (source < 256 && destination < 256)
+			memcpy(&_paletteDisplay[destination * 3], &_paletteDisplay[source * 3], 3);
+
+		_paletteFading = false;
+		vsyncSetPalettePtr(_paletteDisplay);
 		return kScriptContinue;
 	}
 
@@ -1096,11 +1148,11 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		if (root)
 			actorWriteU8(*root, kActorActive, 0);
 
-		return kScriptDeactivatedRoot;
+		return kScriptContinue;
 	}
 
 	error("Script opcode 0x%02X left the dispatch switch without returning", opcode);
-	return kScriptDeactivatedRoot;
+	return kScriptContinue;
 }
 
 ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptStep(Actor &actor, uint32 &pc) {
@@ -1110,9 +1162,6 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptStep(Actor &actor, uint32 &
 	if (_scriptFault)
 		error("Script fault while executing opcode 0x%02X at script PC 0x%08X", opcode, originalPc);
 
-	if (status == kScriptYield)
-		actorWriteU32(actor, kActorCurrentPc, pc);
-
 	return status;
 }
 
diff --git a/engines/comfy/sound.cpp b/engines/comfy/sound.cpp
index 58d740e48f4..f4ac73483cd 100644
--- a/engines/comfy/sound.cpp
+++ b/engines/comfy/sound.cpp
@@ -60,6 +60,496 @@ private:
 	bool _fault;
 };
 
+struct SoundDecoderState {
+public:
+	SoundDecoderState(const byte *data, uint32 size, bool compressed) {
+		_data.resize(size);
+		if (size)
+			memcpy(&_data[0], data, size);
+
+		_compressed = compressed;
+		_end = size;
+		if (_compressed) {
+			if (size < 5) {
+				_fault = true;
+				return;
+			}
+
+			setSample(_data[4]);
+			_position = 5;
+		} else if (size >= 6 && _data[0] == 1) {
+			setSample(_data[4]);
+		} else {
+			setSample(_sample);
+		}
+	}
+
+	uint32 decode(byte *buffer, uint32 size) {
+		uint32 written = 0;
+		while (written < size && !_fault && !_finished) {
+			byte sample = 0x80;
+			if (!readSample(sample))
+				break;
+
+			buffer[written++] = sample;
+		}
+
+		return written;
+	}
+
+	uint32 getRate() { return _sampleRate; }
+	bool finished() { return _finished; }
+
+	void copyCues(Common::Array<ComfyEngine::SoundCue> &cues) {
+		cues = _cues;
+	}
+
+	bool fault() {
+		return _fault;
+	}
+
+	void saveBufferState(uint16 bufferIndex) {
+		if (bufferIndex >= 2)
+			return;
+
+		BufferState &state = _bufferStates[bufferIndex];
+		state.streamPosition = _streamPosition;
+		state.position = _position;
+		state.loopPosition = _loopPosition;
+		state.eventRemaining = _eventRemaining;
+		state.fillRemaining = _fillRemaining;
+		state.loopCount = _loopCount;
+		state.started = _started;
+	}
+
+	uint32 getBufferStreamPosition(uint16 bufferIndex) {
+		return bufferIndex < 2 ? _bufferStates[bufferIndex].streamPosition : 0;
+	}
+
+	void packState(byte *packedState, uint16 bufferIndex, uint32 playbackPosition, uint32 vocCounter,
+			bool stopped, bool usesAnimData, Common::Array<ComfyEngine::SoundCue> &cues, uint nextCue) {
+		memset(packedState, 0, 0x52);
+		packedState[0x3F] = stopped;
+		if (stopped || bufferIndex >= 2)
+			return;
+
+		BufferState &state = _bufferStates[bufferIndex];
+		WRITE_LE_UINT32(packedState, state.streamPosition);
+		packedState[4] = state.started;
+		WRITE_LE_UINT16(packedState + 5, (uint16)state.fillRemaining);
+		WRITE_LE_UINT32(packedState + 7, state.eventRemaining);
+		WRITE_LE_UINT16(packedState + 0x0B, (uint16)state.loopCount);
+		WRITE_LE_UINT32(packedState + 0x0D, playbackPosition);
+		WRITE_LE_UINT32(packedState + 0x11, vocCounter);
+		uint16 packedCueCount = 0;
+		while (nextCue < cues.size() && packedCueCount < 4 &&
+				cues[nextCue].streamPosition < playbackPosition) {
+			WRITE_LE_UINT16(packedState + 0x15 + packedCueCount * 2, cues[nextCue].value);
+			WRITE_LE_UINT32(packedState + 0x1D + packedCueCount * 4, cues[nextCue].streamPosition);
+			WRITE_LE_UINT32(packedState + 0x2D + packedCueCount * 4, cues[nextCue].counterThreshold);
+			packedCueCount++;
+			nextCue++;
+		}
+
+		WRITE_LE_UINT16(packedState + 0x3D, packedCueCount);
+		packedState[0x40] = _sample;
+		WRITE_LE_UINT32(packedState + 0x41, state.position);
+		WRITE_LE_UINT32(packedState + 0x45, state.loopPosition);
+		WRITE_LE_UINT32(packedState + 0x49, _end);
+		WRITE_LE_UINT32(packedState + 0x4D, 0);
+		packedState[0x51] = usesAnimData;
+	}
+
+	bool unpackState(byte *packedState, Common::Array<ComfyEngine::SoundCue> &cues,
+			uint32 &vocCounter) {
+		if (packedState[0x3F])
+			return false;
+
+		_streamPosition = READ_LE_UINT32(packedState);
+		_started = packedState[4] != 0;
+		_fillRemaining = READ_LE_UINT16(packedState + 5);
+		_eventRemaining = READ_LE_UINT32(packedState + 7);
+		_loopCount = (int16)READ_LE_UINT16(packedState + 0x0B);
+		uint32 playbackPosition = READ_LE_UINT32(packedState + 0x0D);
+		vocCounter = READ_LE_UINT32(packedState + 0x11);
+		setSample(packedState[0x40]);
+		_position = READ_LE_UINT32(packedState + 0x41);
+		_loopPosition = READ_LE_UINT32(packedState + 0x45);
+		uint32 packedEnd = READ_LE_UINT32(packedState + 0x49);
+		if (_position > _data.size() || _loopPosition > _data.size() || packedEnd > _data.size())
+			return false;
+
+		_end = packedEnd;
+		_bitOffset = 0;
+		_loopBitOffset = 0;
+		_blockOffset = 0;
+		_fault = false;
+		_finished = false;
+		_cues.clear();
+		uint16 advanceSize = (uint16)(playbackPosition - _streamPosition);
+		if (advanceSize > COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES)
+			advanceSize = COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES;
+
+		if (advanceSize) {
+			Common::Array<byte> discardedPcm;
+			discardedPcm.resize(advanceSize);
+			if (decode(&discardedPcm[0], advanceSize) != advanceSize)
+				return false;
+		}
+
+		_cues.clear();
+		cues.clear();
+		uint16 cueCount = MIN<uint16>(READ_LE_UINT16(packedState + 0x3D), 4);
+		for (uint16 i = 0; i < cueCount; i++) {
+			ComfyEngine::SoundCue cue;
+			cue.value = READ_LE_UINT16(packedState + 0x15 + i * 2);
+			cue.streamPosition = READ_LE_UINT32(packedState + 0x1D + i * 4);
+			cue.counterThreshold = READ_LE_UINT32(packedState + 0x2D + i * 4);
+			_cues.push_back(cue);
+			cues.push_back(cue);
+		}
+
+		return true;
+	}
+
+private:
+	struct BufferState {
+		uint32 streamPosition = 0;
+		uint32 position = 0;
+		uint32 loopPosition = 0;
+		uint32 eventRemaining = 0;
+		uint32 fillRemaining = 0;
+		int16 loopCount = 0;
+		bool started = false;
+	};
+
+	static uint32 calcSampleRate(byte sample) {
+		uint32 denominator = 0x100 - sample;
+		uint32 rate = denominator ? 0x0F4240 / denominator : 0x2B11;
+		if (rate > 0x2710 && rate < 0x2EE0)
+			return 0x2B11;
+
+		if (rate > 0x4E20 && rate < 0x5DC0)
+			return 0x5622;
+
+		return rate;
+	}
+
+	void setSample(byte sample) {
+		_sample = sample;
+		_sampleRate = calcSampleRate(sample);
+		if (_sampleRate == 0x2B11)
+			_sample = 0xA5;
+		else if (_sampleRate == 0x5622)
+			_sample = 0xD3;
+	}
+
+	bool readSample(byte &sample) {
+		for (;;) {
+			if (_started) {
+				_streamPosition++;
+				sample = 0x80;
+				return true;
+			}
+
+			if (_fillRemaining) {
+				_fillRemaining--;
+				_streamPosition++;
+				sample = 0x80;
+				return true;
+			}
+
+			if (_eventRemaining) {
+				if (!copySample(sample))
+					return false;
+
+				_eventRemaining--;
+				_streamPosition++;
+				return true;
+			}
+
+			uint16 command = parseCommand();
+			if (_fault)
+				return false;
+
+			switch (command) {
+			case 0:
+				pushCue(0);
+				_started = true;
+				break;
+
+			case 1:
+				beginEvent(false);
+				break;
+
+			case 2:
+				beginEvent(true);
+				break;
+
+			case 3:
+				readFillCommand();
+				break;
+
+			case 4:
+				pushCue(readParam());
+				break;
+
+			case 6:
+				_loopCount = (int16)readWord();
+				_loopPosition = _position;
+				_loopBitOffset = _bitOffset;
+				break;
+
+			case 7:
+				if (_loopCount > 0) {
+					_loopCount--;
+					// The original reloads the loop position twice.
+					seekToLoop();
+					seekToLoop();
+				}
+				break;
+
+			case 99:
+				setSample((byte)readBits(8));
+				break;
+
+			default:
+				break;
+			}
+		}
+	}
+
+	void seekToLoop() {
+		_position = _loopPosition;
+		_bitOffset = _loopBitOffset;
+	}
+
+	uint16 parseCommand() {
+		_eventArgument = 0;
+		if (!_compressed) {
+			if (_position >= _end) {
+				_fault = true;
+				return 0;
+			}
+
+			uint16 command = _data[_position++];
+			if (command) {
+				if (_end - _position < 3) {
+					_fault = true;
+					return 0;
+				}
+
+				_eventArgument = (uint32)_data[_position] | ((uint32)_data[_position + 1] << 8) |
+					((uint32)_data[_position + 2] << 16);
+				_position += 3;
+			}
+
+			return command;
+		}
+
+		uint16 command = (uint16)readBits(2);
+		if (!command) {
+			uint16 subcommand = (uint16)readBits(2);
+			if (!subcommand)
+				return 0;
+
+			if (subcommand == 1) {
+				command = (uint16)readBits(8);
+				_eventArgument = readBits(20);
+				return command;
+			}
+
+			return subcommand == 2 ? 7 : 99;
+		}
+
+		if (command == 1) {
+			_eventArgument = readBits(20);
+			return 1;
+		}
+
+		return command == 2 ? 3 : 4;
+	}
+
+	void beginEvent(bool loop) {
+		_eventRemaining = _eventArgument;
+		if (_compressed) {
+			_needInit = true;
+			return;
+		}
+
+		if (loop)
+			return;
+
+		if (_eventRemaining < 2 || _end - _position < 2) {
+			_fault = true;
+			return;
+		}
+
+		_eventRemaining -= 2;
+		setSample(_data[_position]);
+		_position += 2;
+	}
+
+	void readFillCommand() {
+		uint16 count = readWord();
+		byte nextSample = _compressed ? _sample : readByte();
+		if (_fault)
+			return;
+
+		_fillRemaining = count;
+		if (nextSample != _sample) {
+			uint32 oldRate = calcSampleRate(_sample);
+			uint32 newRate = calcSampleRate(nextSample);
+			if (newRate)
+				_fillRemaining = ((uint32)_fillRemaining * oldRate) / newRate;
+		}
+	}
+
+	bool copySample(byte &sample) {
+		if (!_compressed) {
+			if (_position >= _end) {
+				_fault = true;
+				return false;
+			}
+
+			sample = _data[_position++];
+			_history.push_back(sample);
+			return true;
+		}
+
+		if (_needInit) {
+			_needInit = false;
+			_bitWidth = 4;
+			_predictorDistance = 1;
+			sample = (byte)readBits(8);
+			_blockOffset = 1;
+		} else {
+			if (_blockOffset == 0 || _blockOffset >= 0x20) {
+				if (readBits(1))
+					_bitWidth = (byte)readBits(3);
+
+				if (_bitWidth && readBits(1))
+					_predictorDistance = (byte)readBits(7);
+				_blockOffset = 0;
+			}
+
+			if (!_bitWidth) {
+				sample = (byte)readBits(8);
+			} else {
+				uint16 delta = (uint16)readBits(_bitWidth);
+				if (!delta) {
+					sample = (byte)readBits(8);
+				} else {
+					byte predictor = _history.size() >= _predictorDistance ?
+						_history[_history.size() - _predictorDistance] : 0x80;
+					sample = predictor + (byte)(delta - (1 << (_bitWidth - 1)));
+				}
+			}
+
+			_blockOffset++;
+		}
+
+		_history.push_back(sample);
+		return !_fault;
+	}
+
+	uint32 readBits(uint bits) {
+		uint32 value = 0;
+		for (uint bit = 0; bit < bits; bit++) {
+			if (_position >= _end) {
+				_fault = true;
+				return value;
+			}
+
+			value |= (uint32)((_data[_position] >> _bitOffset) & 1) << bit;
+			_bitOffset++;
+			if (_bitOffset == 8) {
+				_bitOffset = 0;
+				_position++;
+			}
+		}
+
+		return value;
+	}
+
+	uint16 readParam() {
+		if (!_compressed)
+			return readWord();
+
+		switch (readBits(2)) {
+		case 0:
+			return 1;
+		case 1:
+			return 2;
+		case 2:
+			return (uint16)readBits(8);
+		case 3:
+			return (uint16)readBits(16);
+		default:
+			return 0;
+		}
+	}
+
+	uint16 readWord() {
+		if (_compressed)
+			return (uint16)readBits(16);
+
+		if (_end - _position < 2) {
+			_fault = true;
+			return 0;
+		}
+
+		uint16 value = READ_LE_UINT16(&_data[_position]);
+		_position += 2;
+		return value;
+	}
+
+	byte readByte() {
+		if (_position >= _end) {
+			_fault = true;
+			return 0;
+		}
+
+		return _data[_position++];
+	}
+
+	void pushCue(uint16 value) {
+		if (_cues.size() >= COMFY_SOUND_PITCH_COUNT_LIMIT)
+			return;
+
+		ComfyEngine::SoundCue cue;
+		cue.value = value;
+		cue.streamPosition = _streamPosition;
+		cue.counterThreshold = _sampleRate ? (_streamPosition * 100) / _sampleRate : 0;
+		_cues.push_back(cue);
+	}
+
+	Common::Array<byte> _data;
+	Common::Array<byte> _history;
+	Common::Array<ComfyEngine::SoundCue> _cues;
+	uint32 _end = 0;
+	uint32 _position = 0;
+	uint32 _streamPosition = 0;
+	uint32 _eventArgument = 0;
+	uint32 _eventRemaining = 0;
+	uint32 _fillRemaining = 0;
+	uint32 _loopPosition = 0;
+	uint32 _sampleRate = 0x2B11;
+	int16 _loopCount = 0;
+	byte _sample = 0xA5;
+	byte _bitOffset = 0;
+	byte _loopBitOffset = 0;
+	byte _bitWidth = 4;
+	byte _predictorDistance = 1;
+	byte _blockOffset = 0;
+	bool _compressed = false;
+	bool _needInit = false;
+	bool _started = false;
+	bool _finished = false;
+	bool _fault = false;
+	BufferState _bufferStates[2];
+};
+
 bool ComfyEngine::soundInit() {
 	if (!readAssetFile(Common::Path("VOCFILE.DAT"), _vocFileData) || _vocFileData.size() < 4)
 		return false;
@@ -68,6 +558,7 @@ bool ComfyEngine::soundInit() {
 		return false;
 
 	_soundCompressed = _vocFileData[1] == 'W';
+	_soundUsesAnimData = false;
 	_soundEntryCount = assetsReadLe16At(_vocFileData, 2);
 	_soundEventIndex = 0;
 	_soundEventMaximum = 0;
@@ -88,12 +579,16 @@ bool ComfyEngine::soundInit() {
 
 void ComfyEngine::soundShutdown() {
 	_mixer->stopHandle(_soundHandle);
+	_soundQueueStream = nullptr;
+	delete _soundDecoderState;
+	_soundDecoderState = nullptr;
 	_soundPcm.clear();
 	_soundCues.clear();
 	_vocFileData.clear();
 	_soundEntryCount = 0;
 	_soundNextCue = 0;
 	_soundPaused = false;
+	_soundUsesAnimData = false;
 	if (_midiPlyrDriver)
 		_midiPlyrDriver->setIncreaseVocCounter(0);
 }
@@ -102,8 +597,22 @@ void ComfyEngine::soundHdrReadFromXms(byte *destination, uint16 index, uint16 si
 	objHdrReadFromXms(destination, _headerXmsSoundHeadersBase, size, index);
 }
 
-void ComfyEngine::soundUnprepareHeader() {
-	soundAdvanceTick();
+void ComfyEngine::soundServiceWaveBuffers() {
+	if (!_soundQueueStream || !_mixer->isSoundHandleActive(_soundHandle))
+		return;
+
+	uint32 queuedBlocks = _soundQueueStream->numQueuedStreams();
+	if (_midiPlyrDriver) {
+		for (uint32 i = queuedBlocks; i < 2; i++)
+			_midiPlyrDriver->vocSrUpdateCounters();
+	}
+
+	while (_soundQueueStream->numQueuedStreams() < 2) {
+		if (!soundQueuePcmBlock(_soundWaveBufferIndex))
+			return;
+
+		_soundWaveBufferIndex = 1 - _soundWaveBufferIndex;
+	}
 }
 
 bool ComfyEngine::soundLoadEntry(uint16 index) {
@@ -115,23 +624,205 @@ bool ComfyEngine::soundLoadEntry(uint16 index) {
 	return offset <= _vocFileData.size() && size <= _vocFileData.size() - offset;
 }
 
+bool ComfyEngine::soundPrepareDecoderState(uint16 index) {
+	Common::Array<byte> animationSoundData;
+	byte *data = nullptr;
+	uint32 fileSize = 0;
+	uint32 dataSize = 0;
+	uint32 dataOffset = 0;
+	bool compressed = _soundCompressed;
+	if (index == 0xFFFF) {
+		uint32 storedSize = READ_LE_UINT32(_animFrameHeader + 4);
+		if (!storedSize || storedSize > _animFrameStorage.size())
+			return false;
+
+		animationSoundData.resize(storedSize);
+		if (storedSize)
+			memcpy(&animationSoundData[0], &_animFrameStorage[0], storedSize);
+
+		data = &animationSoundData[0];
+		fileSize = animationSoundData.size();
+		dataSize = fileSize;
+		compressed = false;
+		_soundUsesAnimData = true;
+	} else {
+		byte header[8];
+		memset(header, 0, sizeof(header));
+		soundHdrReadFromXms(header, index, sizeof(header));
+		dataSize = READ_LE_UINT32(header);
+		dataOffset = READ_LE_UINT32(header + 4);
+		data = &_vocFileData[0];
+		fileSize = _vocFileData.size();
+		_soundUsesAnimData = false;
+	}
+
+	if (dataOffset > fileSize || dataSize > fileSize - dataOffset)
+		return false;
+
+	delete _soundDecoderState;
+	_soundDecoderState = new SoundDecoderState(data + dataOffset, dataSize, compressed);
+	if (_soundDecoderState->fault()) {
+		delete _soundDecoderState;
+		_soundDecoderState = nullptr;
+		return false;
+	}
+
+	_soundSampleRate = _soundDecoderState->getRate();
+	_soundCues.clear();
+	_soundNextCue = 0;
+	return true;
+}
+
+bool ComfyEngine::soundDecodePcmBlock(uint16 bufferIndex, byte *&buffer, uint32 &decodedSize) {
+	buffer = nullptr;
+	decodedSize = 0;
+	if (!_soundDecoderState)
+		return false;
+
+	_soundDecoderState->saveBufferState(bufferIndex);
+	uint32 blockSize = _isPanther ? COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES : COMFY_SOUND_PCM_BLOCK_BYTES;
+	buffer = (byte *)malloc(blockSize);
+	if (!buffer)
+		return false;
+
+	decodedSize = _soundDecoderState->decode(buffer, blockSize);
+	_soundDecoderState->copyCues(_soundCues);
+	if (!decodedSize) {
+		free(buffer);
+		buffer = nullptr;
+		return false;
+	}
+
+	return true;
+}
+
+bool ComfyEngine::soundQueuePcmBlock(uint16 bufferIndex) {
+	if (!_soundQueueStream)
+		return false;
+
+	byte *buffer = nullptr;
+	uint32 decodedSize = 0;
+	if (!soundDecodePcmBlock(bufferIndex, buffer, decodedSize))
+		return false;
+
+	_soundQueueStream->queueBuffer(buffer, decodedSize, DisposeAfterUse::YES, Audio::FLAG_UNSIGNED);
+	return true;
+}
+
+void ComfyEngine::soundPackState(byte *state) {
+	bool stopped = !_soundDecoderState || !_mixer->isSoundHandleActive(_soundHandle);
+	if (stopped) {
+		memset(state, 0, 0x52);
+		state[0x3F] = 1;
+		return;
+	}
+
+	uint32 vocCounter = _midiPlyrDriver ? _midiPlyrDriver->getVocCounter() :
+		(uint32)((_mixer->getSoundElapsedTime(_soundHandle) + 9) / 10);
+	uint32 playbackPosition = (vocCounter * _soundSampleRate) / 100;
+	uint16 bufferIndex = _soundWaveBufferIndex;
+	if ((int32)(_soundDecoderState->getBufferStreamPosition(bufferIndex) -
+			COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES) < (int32)playbackPosition)
+		bufferIndex = 1 - bufferIndex;
+
+	_soundDecoderState->packState(state, bufferIndex, playbackPosition, vocCounter,
+		stopped, _soundUsesAnimData, _soundCues, _soundNextCue);
+}
+
+void ComfyEngine::soundUnpackState(byte *state) {
+	_mixer->stopHandle(_soundHandle);
+	_soundQueueStream = nullptr;
+	if (state[0x3F] || !_soundDecoderState) {
+		if (_midiPlyrDriver) {
+			_midiPlyrDriver->setIncreaseVocCounter(0);
+			_midiPlyrDriver->vocSrResetBlockNo();
+		}
+
+		return;
+	}
+
+	uint32 vocCounter = 0;
+	if (!_soundDecoderState->unpackState(state, _soundCues, vocCounter)) {
+		_soundEventSubIndex = 0;
+		return;
+	}
+
+	_soundUsesAnimData = state[0x51] != 0;
+	_soundNextCue = 0;
+	byte *buffers[2] = {nullptr, nullptr};
+	uint32 decodedSizes[2] = {0, 0};
+	if (!soundDecodePcmBlock(0, buffers[0], decodedSizes[0]) ||
+			!soundDecodePcmBlock(1, buffers[1], decodedSizes[1])) {
+		free(buffers[0]);
+		free(buffers[1]);
+		_soundEventSubIndex = 0;
+		return;
+	}
+
+	_soundSampleRate = _soundDecoderState->getRate();
+	_soundQueueStream = Audio::makeQueuingAudioStream(_soundSampleRate, false);
+	if (!_soundQueueStream) {
+		free(buffers[0]);
+		free(buffers[1]);
+		_soundEventSubIndex = 0;
+		return;
+	}
+
+	_soundQueueStream->queueBuffer(buffers[0], decodedSizes[0], DisposeAfterUse::YES, Audio::FLAG_UNSIGNED);
+	_soundQueueStream->queueBuffer(buffers[1], decodedSizes[1], DisposeAfterUse::YES, Audio::FLAG_UNSIGNED);
+
+	_soundWaveBufferIndex = 0;
+	_soundEventSubIndex = 0xFFFF;
+	if (_midiPlyrDriver) {
+		_midiPlyrDriver->setVocCounter(vocCounter);
+		_midiPlyrDriver->setIncreaseVocCounter(1);
+		_midiPlyrDriver->vocSrResetCounters();
+	}
+
+	_mixer->playStream(Audio::Mixer::kSpeechSoundType, &_soundHandle, _soundQueueStream, -1,
+		Audio::Mixer::kMaxChannelVolume, 0, DisposeAfterUse::YES);
+}
+
 bool ComfyEngine::soundDecodeEntry(uint16 index) {
 	_soundPcm.clear();
 	_soundCues.clear();
 	_soundNextCue = 0;
-	byte header[8];
-	memset(header, 0, sizeof(header));
-	soundHdrReadFromXms(header, index, sizeof(header));
-	uint32 dataSize = READ_LE_UINT32(header);
-	uint32 dataOffset = READ_LE_UINT32(header + 4);
+	Common::Array<byte> animationSoundData;
+	byte *data = nullptr;
+	uint32 fileSize = 0;
+	uint32 dataSize = 0;
+	uint32 dataOffset = 0;
+	bool compressed = _soundCompressed;
+	if (index == 0xFFFF) {
+		uint32 storedSize = READ_LE_UINT32(_animFrameHeader + 4);
+		if (_animFrameStorage.size() < 2 || storedSize > _animFrameStorage.size() - 1)
+			return false;
+
+		animationSoundData.resize(storedSize + 1);
+		animationSoundData[0] = 1;
+		memcpy(&animationSoundData[1], &_animFrameStorage[1], storedSize);
+		data = &animationSoundData[0];
+		fileSize = animationSoundData.size();
+		dataSize = fileSize;
+		compressed = false;
+	} else {
+		byte header[8];
+		memset(header, 0, sizeof(header));
+		soundHdrReadFromXms(header, index, sizeof(header));
+		dataSize = READ_LE_UINT32(header);
+		dataOffset = READ_LE_UINT32(header + 4);
+		data = &_vocFileData[0];
+		fileSize = _vocFileData.size();
+	}
+
 	debug(5, "COMFY VOC: decode id=%u offset=%u size=%u compressed=%u fileSize=%u",
-		index, dataOffset, dataSize, _soundCompressed ? 1 : 0, (uint)_vocFileData.size());
-	if (dataOffset > _vocFileData.size() || dataSize > _vocFileData.size() - dataOffset) {
+		index, dataOffset, dataSize, compressed ? 1 : 0, fileSize);
+	if (dataOffset > fileSize || dataSize > fileSize - dataOffset) {
 		debug(5, "COMFY VOC: decode id=%u rejected invalid range", index);
 		return false;
 	}
 
-	if (_soundCompressed) {
+	if (compressed) {
 		bool decoded = soundDecodeCompressedEntry(dataOffset, dataSize);
 		debug(5, "COMFY VOC: decode id=%u result=%u pcm=%u rate=%u cues=%u",
 			index, decoded ? 1 : 0, (uint)_soundPcm.size(), _soundSampleRate, (uint)_soundCues.size());
@@ -146,9 +837,9 @@ bool ComfyEngine::soundDecodeEntry(uint16 index) {
 	int16 loopCount = 0;
 	uint32 commandCount = 0;
 	while (pc < end && commandCount++ < dataSize) {
-		byte command = _vocFileData[pc++];
+		byte command = data[pc++];
 		if (!command) {
-			SoundCue cue = {0, (uint32)((_soundPcm.size() * 100) / _soundSampleRate)};
+			SoundCue cue = {0, (uint32)_soundPcm.size(), (uint32)((_soundPcm.size() * 100) / _soundSampleRate)};
 			_soundCues.push_back(cue);
 			break;
 		}
@@ -156,8 +847,8 @@ bool ComfyEngine::soundDecodeEntry(uint16 index) {
 		if (3 > end - pc)
 			return false;
 
-		uint32 argument = (uint32)_vocFileData[pc] | ((uint32)_vocFileData[pc + 1] << 8) |
-			((uint32)_vocFileData[pc + 2] << 16);
+		uint32 argument = (uint32)data[pc] | ((uint32)data[pc + 1] << 8) |
+			((uint32)data[pc + 2] << 16);
 		pc += 3;
 		if (command == 1 || command == 2) {
 			uint32 length = argument;
@@ -165,15 +856,18 @@ bool ComfyEngine::soundDecodeEntry(uint16 index) {
 				if (length < 2 || 2 > end - pc)
 					return false;
 
-				sample = _vocFileData[pc];
+				sample = data[pc];
 				pc += 2;
 				length -= 2;
 				uint32 denominator = 0x100 - sample;
 				_soundSampleRate = denominator ? 0x0F4240 / denominator : 0x2B11;
-				if (_soundSampleRate > 0x2710 && _soundSampleRate < 0x2EE0)
+				if (_soundSampleRate > 0x2710 && _soundSampleRate < 0x2EE0) {
 					_soundSampleRate = 0x2B11;
-				else if (_soundSampleRate > 0x4E20 && _soundSampleRate < 0x5DC0)
+					sample = 0xA5;
+				} else if (_soundSampleRate > 0x4E20 && _soundSampleRate < 0x5DC0) {
 					_soundSampleRate = 0x5622;
+					sample = 0xD3;
+				}
 			}
 
 			if (length > end - pc)
@@ -181,14 +875,14 @@ bool ComfyEngine::soundDecodeEntry(uint16 index) {
 
 			uint32 oldSize = _soundPcm.size();
 			_soundPcm.resize(oldSize + length);
-			memcpy(&_soundPcm[oldSize], &_vocFileData[pc], length);
+			memcpy(&_soundPcm[oldSize], data + pc, length);
 			pc += length;
 		} else if (command == 3) {
 			if (3 > end - pc)
 				return false;
 
-			uint16 fill = READ_LE_UINT16(&_vocFileData[pc]);
-			byte nextSample = _vocFileData[pc + 2];
+			uint16 fill = READ_LE_UINT16(data + pc);
+			byte nextSample = data[pc + 2];
 			pc += 3;
 			if (nextSample != sample) {
 				uint32 oldRate = _soundSampleRate;
@@ -203,14 +897,15 @@ bool ComfyEngine::soundDecodeEntry(uint16 index) {
 			if (2 > end - pc)
 				return false;
 
-			SoundCue cue = {READ_LE_UINT16(&_vocFileData[pc]), (uint32)((_soundPcm.size() * 100) / _soundSampleRate)};
+			SoundCue cue = {READ_LE_UINT16(data + pc), (uint32)_soundPcm.size(),
+				(uint32)((_soundPcm.size() * 100) / _soundSampleRate)};
 			_soundCues.push_back(cue);
 			pc += 2;
 		} else if (command == 6) {
 			if (2 > end - pc)
 				return false;
 
-			loopCount = READ_LE_UINT16(&_vocFileData[pc]);
+			loopCount = READ_LE_UINT16(data + pc);
 			pc += 2;
 			loopPc = pc;
 		} else if (command == 7) {
@@ -222,7 +917,7 @@ bool ComfyEngine::soundDecodeEntry(uint16 index) {
 			if (pc >= end)
 				return false;
 
-			sample = _vocFileData[pc++];
+			sample = data[pc++];
 		}
 	}
 
@@ -239,10 +934,13 @@ bool ComfyEngine::soundDecodeCompressedEntry(uint32 dataOffset, uint32 dataSize)
 	byte sample = _vocFileData[dataOffset + 4];
 	uint32 denominator = 0x100 - sample;
 	_soundSampleRate = denominator ? 0x0F4240 / denominator : 0x2B11;
-	if (_soundSampleRate > 0x2710 && _soundSampleRate < 0x2EE0)
+	if (_soundSampleRate > 0x2710 && _soundSampleRate < 0x2EE0) {
 		_soundSampleRate = 0x2B11;
-	else if (_soundSampleRate > 0x4E20 && _soundSampleRate < 0x5DC0)
+		sample = 0xA5;
+	} else if (_soundSampleRate > 0x4E20 && _soundSampleRate < 0x5DC0) {
 		_soundSampleRate = 0x5622;
+		sample = 0xD3;
+	}
 
 	SoundBitReader bits(&_vocFileData[dataOffset + 5], dataSize - 5);
 	uint32 loopPosition = 0;
@@ -274,7 +972,7 @@ bool ComfyEngine::soundDecodeCompressedEntry(uint32 dataOffset, uint32 dataSize)
 		}
 
 		if (command == 0) {
-			SoundCue cue = {0, (uint32)((_soundPcm.size() * 100) / _soundSampleRate)};
+			SoundCue cue = {0, (uint32)_soundPcm.size(), (uint32)((_soundPcm.size() * 100) / _soundSampleRate)};
 			_soundCues.push_back(cue);
 			break;
 		} else if (command == 1 || command == 2) {
@@ -328,7 +1026,8 @@ bool ComfyEngine::soundDecodeCompressedEntry(uint32 dataOffset, uint32 dataSize)
 		} else if (command == 4) {
 			uint16 mode = bits.read(2);
 			uint16 value = mode == 0 ? 1 : mode == 1 ? 2 : mode == 2 ? bits.read(8) : bits.read(16);
-			SoundCue cue = {value, (uint32)((_soundPcm.size() * 100) / _soundSampleRate)};
+			SoundCue cue = {value, (uint32)_soundPcm.size(),
+				(uint32)((_soundPcm.size() * 100) / _soundSampleRate)};
 			_soundCues.push_back(cue);
 		} else if (command == 6) {
 			loopCount = bits.read(16);
@@ -349,27 +1048,48 @@ bool ComfyEngine::soundDecodeCompressedEntry(uint32 dataOffset, uint32 dataSize)
 void ComfyEngine::soundPlayEntry(uint16 index) {
 	debug(5, "COMFY VOC: play id=%u", index);
 	_mixer->stopHandle(_soundHandle);
-	if (!soundDecodeEntry(index)) {
+	_soundQueueStream = nullptr;
+	if (!soundPrepareDecoderState(index)) {
 		debug(5, "COMFY VOC: play id=%u decode failed", index);
 		_soundEventSubIndex = 0;
 		return;
 	}
 
-	Audio::AudioStream *stream = Audio::makeRawStream(&_soundPcm[0], _soundPcm.size(), _soundSampleRate,
-		Audio::FLAG_UNSIGNED, DisposeAfterUse::NO);
-	if (!stream) {
-		debug(5, "COMFY VOC: play id=%u raw stream creation failed", index);
-		_soundPcm.clear();
+	byte *buffers[2] = {nullptr, nullptr};
+	uint32 decodedSizes[2] = {0, 0};
+	if (!soundDecodePcmBlock(0, buffers[0], decodedSizes[0]) ||
+			!soundDecodePcmBlock(1, buffers[1], decodedSizes[1])) {
+		free(buffers[0]);
+		free(buffers[1]);
+		delete _soundDecoderState;
+		_soundDecoderState = nullptr;
+		debug(5, "COMFY VOC: play id=%u initial buffer fill failed", index);
 		_soundEventSubIndex = 0;
 		return;
 	}
 
-	_mixer->playStream(Audio::Mixer::kSpeechSoundType, &_soundHandle, stream, -1,
+	_soundSampleRate = _soundDecoderState->getRate();
+	_soundQueueStream = Audio::makeQueuingAudioStream(_soundSampleRate, false);
+	if (!_soundQueueStream) {
+		free(buffers[0]);
+		free(buffers[1]);
+		delete _soundDecoderState;
+		_soundDecoderState = nullptr;
+		debug(5, "COMFY VOC: play id=%u queue creation failed", index);
+		_soundEventSubIndex = 0;
+		return;
+	}
+
+	_soundQueueStream->queueBuffer(buffers[0], decodedSizes[0], DisposeAfterUse::YES, Audio::FLAG_UNSIGNED);
+	_soundQueueStream->queueBuffer(buffers[1], decodedSizes[1], DisposeAfterUse::YES, Audio::FLAG_UNSIGNED);
+
+	_mixer->playStream(Audio::Mixer::kSpeechSoundType, &_soundHandle, _soundQueueStream, -1,
 		Audio::Mixer::kMaxChannelVolume, 0, DisposeAfterUse::YES);
-	debug(5, "COMFY VOC: play id=%u submitted active=%u pcm=%u rate=%u cues=%u",
+	debug(5, "COMFY VOC: play id=%u submitted active=%u rate=%u cues=%u",
 		index, _mixer->isSoundHandleActive(_soundHandle) ? 1 : 0,
-		(uint)_soundPcm.size(), _soundSampleRate, (uint)_soundCues.size());
+		_soundSampleRate, (uint)_soundCues.size());
 	_soundPaused = false;
+	_soundWaveBufferIndex = 0;
 	_soundEventSubIndex = 0xFFFF;
 	if (_midiPlyrDriver) {
 		_midiPlyrDriver->vocSrResetCounters();
@@ -383,7 +1103,8 @@ void ComfyEngine::soundAdvanceTick() {
 		return;
 
 	if (!_mixer->isSoundHandleActive(_soundHandle)) {
-		if (!_soundPcm.empty() && _soundEventSubIndex != 0) {
+		_soundQueueStream = nullptr;
+		if (_soundDecoderState && _soundEventSubIndex != 0) {
 			debug(5, "COMFY VOC: mixer became inactive; marking entry complete");
 			_soundEventSubIndex = 0;
 		}
@@ -393,9 +1114,11 @@ void ComfyEngine::soundAdvanceTick() {
 
 	uint32 counter = _midiPlyrDriver ? _midiPlyrDriver->getVocCounter() :
 		(uint32)((_mixer->getSoundElapsedTime(_soundHandle) + 9) / 10);
-	uint32 compareCounter = counter >= 2 ? counter - 2 : 0;
+	soundServiceWaveBuffers();
+
+	int32 compareCounter = (int32)(counter - 2);
 	bool phaseCueSeen = false;
-	while (_soundNextCue < _soundCues.size() && compareCounter > _soundCues[_soundNextCue].counterThreshold &&
+	while (_soundNextCue < _soundCues.size() && compareCounter > (int32)_soundCues[_soundNextCue].counterThreshold &&
 			(_soundCues[_soundNextCue].value == 1 || _soundCues[_soundNextCue].value == 2)) {
 		phaseCueSeen = true;
 		_soundEventSubIndex = _soundCues[_soundNextCue].value;
@@ -406,7 +1129,7 @@ void ComfyEngine::soundAdvanceTick() {
 	}
 
 	if (phaseCueSeen || _soundNextCue == _soundCues.size() ||
-			compareCounter <= _soundCues[_soundNextCue].counterThreshold)
+			compareCounter <= (int32)_soundCues[_soundNextCue].counterThreshold)
 		return;
 
 	_soundEventSubIndex = _soundCues[_soundNextCue].value;
@@ -416,8 +1139,12 @@ void ComfyEngine::soundAdvanceTick() {
 	_soundNextCue++;
 	if (!_soundEventSubIndex) {
 		_mixer->stopHandle(_soundHandle);
-		if (_midiPlyrDriver)
-			_midiPlyrDriver->setIncreaseVocCounter(0);
+		_soundQueueStream = nullptr;
+		_soundCues.clear();
+		_soundNextCue = 0;
+		if (_midiPlyrDriver) {
+			_midiPlyrDriver->vocSrResetBlockNo();
+		}
 	}
 }
 
diff --git a/engines/comfy/video.cpp b/engines/comfy/video.cpp
index 525636f96dd..54d4559e91e 100644
--- a/engines/comfy/video.cpp
+++ b/engines/comfy/video.cpp
@@ -45,6 +45,10 @@ void ComfyEngine::videoInit() {
 	_screen = new Graphics::Screen(_logicalScreenWidth, _logicalScreenHeight);
 	_framebufPtr = new byte[framebufferBytes()]();
 	_presentBuffer = new byte[framebufferBytes()]();
+	if (_isPanther)
+		_backgroundFramebuf.resize(framebufferBytes());
+
+	_backgroundFrame = 0;
 	_resolutionChangeCount = 0;
 	_renderDirtyCount = 0;
 	videoSetResolution();
@@ -61,6 +65,8 @@ void ComfyEngine::videoShutdown(byte restorePalette) {
 	_presentBuffer = nullptr;
 	delete[] _framebufPtr;
 	_framebufPtr = nullptr;
+	_backgroundFramebuf.clear();
+	_backgroundFrame = 0;
 	delete _screen;
 	_screen = nullptr;
 	_resolutionChangeCount = 0;
@@ -90,6 +96,11 @@ void ComfyEngine::renderFlushDirty() {
 	}
 }
 
+void ComfyEngine::renderInvalidateFullFrame() {
+	renderFlushDirty();
+	videoSetResolution();
+}
+
 void ComfyEngine::videoFindBestMode(VideoRectRecord record) {
 	record.left = CLIP<int16>(record.left, 0, _logicalScreenWidth);
 	record.top = CLIP<int16>(record.top, 0, _logicalScreenHeight);
@@ -113,7 +124,7 @@ void ComfyEngine::videoFindBestMode(VideoRectRecord record) {
 		merged.right = (MAX(existing.right, record.right) + 1) / 2 * 2;
 		merged.top = MIN(existing.top, record.top) / 2 * 2;
 		merged.bottom = (MAX(existing.bottom, record.bottom) + 1) / 2 * 2;
-		merged.area = (uint16)((merged.right - merged.left) * (merged.bottom - merged.top));
+		merged.area = (uint32)(merged.right - merged.left) * (merged.bottom - merged.top);
 
 		if ((uint32)existing.area + record.area >= merged.area) {
 			existing = merged;
@@ -129,8 +140,9 @@ void ComfyEngine::framebufCopyAll(byte *destination, byte *source) {
 	memcpy(destination, source, framebufferBytes());
 }
 
-void ComfyEngine::framebufClear(uint16 color) {
-	memset(_framebufPtr, (byte)color, framebufferBytes());
+void ComfyEngine::framebufClear(byte *destination, uint16 color) {
+	if (destination)
+		memset(destination, (byte)color, framebufferBytes());
 }
 
 void ComfyEngine::videoPresentFrame() {


Commit: a8764da4bd01965da2cc53621bb68ac436646d19
    https://github.com/scummvm/scummvm/commit/a8764da4bd01965da2cc53621bb68ac436646d19
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: PANTHER: Fix sound

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/anim_file.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/script_vm.cpp
    engines/comfy/sound.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index ec5d6fddec8..7297a8b1faf 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -1337,6 +1337,7 @@ bool ComfyEngine::actorDrawLegacyInternal(uint16 actorIndex, int16 x, int16 y) {
 
 	uint32 selector = actorReadU32(*actor, kActorSpriteSelector);
 	if (selector == 0x00FFFFFF) {
+		animFrameInvalidateRects(drawX, drawY, 1);
 		drawResult = animFrameBlitAt(drawX, drawY);
 	} else if (selector & 0xFF000000) {
 		uint32 pc = selector & 0x00FFFFFF;
@@ -1612,10 +1613,12 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 		newRect.bottom = drawY + frameHeight;
 		newRect.area = frameWidth * frameHeight;
 		if (visible) {
-			if (_isPanther && (_videoMode == 2 || _videoMode == 4))
+			if (_isPanther && (_videoMode == 2 || _videoMode == 4)) {
 				renderQueueDrawCommand(drawX, drawY, selector, 2);
-			else
+			} else {
+				animFrameInvalidateRects(drawX, drawY, 1);
 				animFrameBlitAt(drawX, drawY);
+			}
 		}
 	} else if (selector) {
 		SpriteResource *sprite = spriteLookup((uint16)selector, drawX, drawY);
diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
index 140073eac85..d5453c8ddf1 100644
--- a/engines/comfy/anim_file.cpp
+++ b/engines/comfy/anim_file.cpp
@@ -161,6 +161,11 @@ void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 ac
 	_animCurrentActorSceneHandle = actorSceneHandle;
 	_animCurrentFrameKey = frameKey;
 	_animUsesWaveVocCounter = READ_LE_UINT32(_animFrameHeader + 4) != 0;
+	if (_animUsesWaveVocCounter) {
+		vocQueuePlayAll();
+		vocQueuePush(0xFFFF, 0, 0);
+	}
+
 	_animVocClockHz = READ_LE_UINT16(_animFrameHeader + 8);
 	_animVocTargetCounter = 0xFFFF;
 	_animVocDeltaB = 0;
@@ -379,7 +384,7 @@ void ComfyEngine::animFileTickCommands() {
 		byte *header = &_animFileData[_animPosition];
 		uint16 command = READ_LE_UINT16(header);
 		uint32 rawCommandSize = _animPantherFormat ? READ_LE_UINT32(header + 2) : READ_LE_UINT16(header + 2);
-		uint32 commandSize = _animPantherFormat ? rawCommandSize & 0xFFFF : rawCommandSize;
+		uint32 commandSize = rawCommandSize;
 		debug(5, "COMFY ANM: index=%u position=%u command=0x%04X size=%u argument=%u",
 			_animCurrentIndex, _animPosition, command, commandSize,
 			_animPantherFormat ? READ_LE_UINT16(header + 6) : 0);
@@ -506,8 +511,6 @@ void ComfyEngine::animFrameSetReady(bool ready) {
 bool ComfyEngine::animFrameBlitAt(int16 x, int16 y) {
 	if (_animFrameBuffer.empty() || !_framebufPtr)
 		return false;
-	if (!_isPanther)
-		animFrameInvalidateRects(x, y, 1);
 
 	uint16 frameWidth = 0;
 	uint16 frameHeight = 0;
@@ -698,7 +701,7 @@ void ComfyEngine::animFileRebuildStorage(uint32 targetSize) {
 		byte *header = &_animFileData[position];
 		uint16 command = READ_LE_UINT16(header);
 		uint32 rawCommandSize = _animPantherFormat ? READ_LE_UINT32(header + 2) : READ_LE_UINT16(header + 2);
-		uint32 commandSize = _animPantherFormat ? rawCommandSize & 0xFFFF : rawCommandSize;
+		uint32 commandSize = rawCommandSize;
 		if (commandSize < headerSize || commandSize > _animFileData.size() - position)
 			error("Invalid command while rebuilding animation storage");
 
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 6ffbf1667e3..c9eaeb638cf 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -710,7 +710,6 @@ void ComfyEngine::vocQueuePlayAll() {
 		}
 
 		_soundEventMaximum = _soundEventIndex;
-		_soundPcm.clear();
 		keyBitClear(1);
 		keyBitClear(4);
 		keyBitSet(3);
@@ -728,7 +727,6 @@ void ComfyEngine::vocQueuePlayAll() {
 	}
 
 	_soundEventMaximum = _soundEventIndex;
-	_soundPcm.clear();
 	keyBitClear(1);
 	keyBitClear(4);
 	keyBitSet(3);
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 58cc5ea9042..084fd5236e6 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -602,7 +602,6 @@ private:
 	MidiChannelState _midiChannels[COMFY_MIDI_CHANNEL_COUNT];
 	uint32 _midiInstanceTrackBase = 1;
 	Common::Array<byte> _vocFileData;
-	Common::Array<byte> _soundPcm;
 	Common::Array<SoundCue> _soundCues;
 	SoundDecoderState *_soundDecoderState = nullptr;
 	Audio::SoundHandle _soundHandle;
@@ -639,6 +638,10 @@ private:
 	bool _soundCompressed = false;
 	bool _soundUsesAnimData = false;
 	bool _soundPaused = false;
+	bool _soundTimingPaused = false;
+	uint16 _soundVocBlockCount = 0;
+	uint32 _soundVocCounterSnapshot = 0;
+	int16 _soundVocTimingDelta = 0;
 	Common::Array<byte> _animFileData;
 	Common::Array<uint32> _animIndexTable;
 	Common::Array<byte> _animFrameBuffer;
@@ -914,9 +917,8 @@ private:
 	bool soundInit();
 	void soundShutdown();
 	void soundHdrReadFromXms(byte *destination, uint16 index, uint16 size);
+	void soundUpdateVocTiming();
 	void soundServiceWaveBuffers();
-	bool soundDecodeEntry(uint16 index);
-	bool soundDecodeCompressedEntry(uint32 dataOffset, uint32 dataSize);
 	bool soundLoadEntry(uint16 index);
 	bool soundPrepareDecoderState(uint16 index);
 	bool soundDecodePcmBlock(uint16 bufferIndex, byte *&buffer, uint32 &decodedSize);
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 2bc62cfe938..3382d57fd54 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -1157,7 +1157,11 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptStep(Actor &actor, uint32 &pc) {
 	uint32 originalPc = pc;
+	_scriptFault = false;
 	byte opcode = scriptReadByte(pc++);
+	if (_scriptFault)
+		error("Script fault while fetching opcode at script PC 0x%08X", originalPc);
+
 	ScriptDispatchStatus status = scriptDispatch(actor, opcode, pc);
 	if (_scriptFault)
 		error("Script fault while executing opcode 0x%02X at script PC 0x%08X", opcode, originalPc);
diff --git a/engines/comfy/sound.cpp b/engines/comfy/sound.cpp
index f4ac73483cd..0552d7acf4e 100644
--- a/engines/comfy/sound.cpp
+++ b/engines/comfy/sound.cpp
@@ -27,38 +27,10 @@
 #include "common/debug.h"
 #include "common/endian.h"
 
-namespace Comfy {
-
-class SoundBitReader {
-public:
-	SoundBitReader(byte *data, uint32 size) : _data(data), _size(size), _bitPosition(0), _fault(false) {}
-
-	uint32 read(uint bits) {
-		uint32 value = 0;
-		for (uint bit = 0; bit < bits; bit++) {
-			uint32 bytePosition = _bitPosition >> 3;
-			if (bytePosition >= _size) {
-				_fault = true;
-				return value;
-			}
-
-			value |= (uint32)((_data[bytePosition] >> (_bitPosition & 7)) & 1) << bit;
-			_bitPosition++;
-		}
-
-		return value;
-	}
-
-	uint32 position() { return _bitPosition; }
-	void setPosition(uint32 position) { _bitPosition = position; }
-	bool fault() { return _fault; }
+#define COMFY_ANM_COMMAND_END 0x2145
+#define COMFY_ANM_COMMAND_STORE_FRAME_BYTES 0x4356
 
-private:
-	byte *_data;
-	uint32 _size;
-	uint32 _bitPosition;
-	bool _fault;
-};
+namespace Comfy {
 
 struct SoundDecoderState {
 public:
@@ -564,6 +536,10 @@ bool ComfyEngine::soundInit() {
 	_soundEventMaximum = 0;
 	_soundEventSubIndex = 0xFFFF;
 	_soundEventPreviousSubIndex = 0xFFFF;
+	_soundTimingPaused = false;
+	_soundVocBlockCount = 0;
+	_soundVocCounterSnapshot = 0;
+	_soundVocTimingDelta = 0;
 	for (uint i = 0; i < COMFY_VOC_QUEUE_CAPACITY; i++) {
 		_vocQueue[i] = VocQueueEntry();
 		_vocQueue1999[i] = VocQueueEntry1999();
@@ -582,13 +558,16 @@ void ComfyEngine::soundShutdown() {
 	_soundQueueStream = nullptr;
 	delete _soundDecoderState;
 	_soundDecoderState = nullptr;
-	_soundPcm.clear();
 	_soundCues.clear();
 	_vocFileData.clear();
 	_soundEntryCount = 0;
 	_soundNextCue = 0;
 	_soundPaused = false;
 	_soundUsesAnimData = false;
+	_soundTimingPaused = false;
+	_soundVocBlockCount = 0;
+	_soundVocCounterSnapshot = 0;
+	_soundVocTimingDelta = 0;
 	if (_midiPlyrDriver)
 		_midiPlyrDriver->setIncreaseVocCounter(0);
 }
@@ -597,6 +576,24 @@ void ComfyEngine::soundHdrReadFromXms(byte *destination, uint16 index, uint16 si
 	objHdrReadFromXms(destination, _headerXmsSoundHeadersBase, size, index);
 }
 
+void ComfyEngine::soundUpdateVocTiming() {
+	if (_soundTimingPaused || !_midiPlyrDriver)
+		return;
+
+	uint32 timeFrac = 0;
+	uint16 blockNo = 0;
+	_midiPlyrDriver->vocSrGetCounters(timeFrac, blockNo);
+	if (!blockNo)
+		return;
+
+	_soundVocBlockCount += blockNo;
+	timeFrac -= _soundVocCounterSnapshot;
+	_midiPlyrDriver->vocSrResetBlockNo();
+	uint32 sampleRate = _soundSampleRate ? _soundSampleRate : 0x2B11;
+	uint32 expected = ((uint32)_soundVocBlockCount * 0x186A00) / sampleRate;
+	_soundVocTimingDelta = (int16)((uint16)expected - (uint16)timeFrac);
+}
+
 void ComfyEngine::soundServiceWaveBuffers() {
 	if (!_soundQueueStream || !_mixer->isSoundHandleActive(_soundHandle))
 		return;
@@ -633,12 +630,49 @@ bool ComfyEngine::soundPrepareDecoderState(uint16 index) {
 	bool compressed = _soundCompressed;
 	if (index == 0xFFFF) {
 		uint32 storedSize = READ_LE_UINT32(_animFrameHeader + 4);
-		if (!storedSize || storedSize > _animFrameStorage.size())
+		if (!storedSize)
 			return false;
 
 		animationSoundData.resize(storedSize);
-		if (storedSize)
+		if (storedSize <= _animFrameStorage.size()) {
 			memcpy(&animationSoundData[0], &_animFrameStorage[0], storedSize);
+		} else {
+			// The original streams embedded ANM sound through the file object while VC
+			// chunks arrive. The host decoder owns its source buffer, so rebuild only
+			// the embedded sound stream without changing the animation command cursor.
+			if (_animCurrentIndex >= _animIndexTable.size())
+				return false;
+
+			uint32 copied = 0;
+			uint32 position = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
+			while (copied < storedSize) {
+				uint32 headerSize = _animPantherFormat ? 8 : 4;
+				if (position > _animFileData.size() || headerSize > _animFileData.size() - position)
+					return false;
+
+				byte *header = &_animFileData[position];
+				uint16 command = READ_LE_UINT16(header);
+				uint32 commandSize = _animPantherFormat ? READ_LE_UINT32(header + 2) : READ_LE_UINT16(header + 2);
+				if (commandSize < headerSize || commandSize > _animFileData.size() - position)
+					return false;
+
+				uint32 payloadSize = commandSize - headerSize;
+				if (command == COMFY_ANM_COMMAND_STORE_FRAME_BYTES) {
+					uint32 copySize = MIN<uint32>(payloadSize, storedSize - copied);
+					if (copySize)
+						memcpy(&animationSoundData[copied], header + headerSize, copySize);
+
+					copied += copySize;
+				} else if (command == COMFY_ANM_COMMAND_END) {
+					break;
+				}
+
+				position += commandSize;
+			}
+
+			if (copied < storedSize)
+				return false;
+		}
 
 		data = &animationSoundData[0];
 		fileSize = animationSoundData.size();
@@ -783,268 +817,6 @@ void ComfyEngine::soundUnpackState(byte *state) {
 		Audio::Mixer::kMaxChannelVolume, 0, DisposeAfterUse::YES);
 }
 
-bool ComfyEngine::soundDecodeEntry(uint16 index) {
-	_soundPcm.clear();
-	_soundCues.clear();
-	_soundNextCue = 0;
-	Common::Array<byte> animationSoundData;
-	byte *data = nullptr;
-	uint32 fileSize = 0;
-	uint32 dataSize = 0;
-	uint32 dataOffset = 0;
-	bool compressed = _soundCompressed;
-	if (index == 0xFFFF) {
-		uint32 storedSize = READ_LE_UINT32(_animFrameHeader + 4);
-		if (_animFrameStorage.size() < 2 || storedSize > _animFrameStorage.size() - 1)
-			return false;
-
-		animationSoundData.resize(storedSize + 1);
-		animationSoundData[0] = 1;
-		memcpy(&animationSoundData[1], &_animFrameStorage[1], storedSize);
-		data = &animationSoundData[0];
-		fileSize = animationSoundData.size();
-		dataSize = fileSize;
-		compressed = false;
-	} else {
-		byte header[8];
-		memset(header, 0, sizeof(header));
-		soundHdrReadFromXms(header, index, sizeof(header));
-		dataSize = READ_LE_UINT32(header);
-		dataOffset = READ_LE_UINT32(header + 4);
-		data = &_vocFileData[0];
-		fileSize = _vocFileData.size();
-	}
-
-	debug(5, "COMFY VOC: decode id=%u offset=%u size=%u compressed=%u fileSize=%u",
-		index, dataOffset, dataSize, compressed ? 1 : 0, fileSize);
-	if (dataOffset > fileSize || dataSize > fileSize - dataOffset) {
-		debug(5, "COMFY VOC: decode id=%u rejected invalid range", index);
-		return false;
-	}
-
-	if (compressed) {
-		bool decoded = soundDecodeCompressedEntry(dataOffset, dataSize);
-		debug(5, "COMFY VOC: decode id=%u result=%u pcm=%u rate=%u cues=%u",
-			index, decoded ? 1 : 0, (uint)_soundPcm.size(), _soundSampleRate, (uint)_soundCues.size());
-		return decoded;
-	}
-
-	uint32 pc = dataOffset;
-	uint32 end = dataOffset + dataSize;
-	byte sample = 0xA5;
-	_soundSampleRate = 0x2B11;
-	uint32 loopPc = 0;
-	int16 loopCount = 0;
-	uint32 commandCount = 0;
-	while (pc < end && commandCount++ < dataSize) {
-		byte command = data[pc++];
-		if (!command) {
-			SoundCue cue = {0, (uint32)_soundPcm.size(), (uint32)((_soundPcm.size() * 100) / _soundSampleRate)};
-			_soundCues.push_back(cue);
-			break;
-		}
-
-		if (3 > end - pc)
-			return false;
-
-		uint32 argument = (uint32)data[pc] | ((uint32)data[pc + 1] << 8) |
-			((uint32)data[pc + 2] << 16);
-		pc += 3;
-		if (command == 1 || command == 2) {
-			uint32 length = argument;
-			if (command == 1) {
-				if (length < 2 || 2 > end - pc)
-					return false;
-
-				sample = data[pc];
-				pc += 2;
-				length -= 2;
-				uint32 denominator = 0x100 - sample;
-				_soundSampleRate = denominator ? 0x0F4240 / denominator : 0x2B11;
-				if (_soundSampleRate > 0x2710 && _soundSampleRate < 0x2EE0) {
-					_soundSampleRate = 0x2B11;
-					sample = 0xA5;
-				} else if (_soundSampleRate > 0x4E20 && _soundSampleRate < 0x5DC0) {
-					_soundSampleRate = 0x5622;
-					sample = 0xD3;
-				}
-			}
-
-			if (length > end - pc)
-				return false;
-
-			uint32 oldSize = _soundPcm.size();
-			_soundPcm.resize(oldSize + length);
-			memcpy(&_soundPcm[oldSize], data + pc, length);
-			pc += length;
-		} else if (command == 3) {
-			if (3 > end - pc)
-				return false;
-
-			uint16 fill = READ_LE_UINT16(data + pc);
-			byte nextSample = data[pc + 2];
-			pc += 3;
-			if (nextSample != sample) {
-				uint32 oldRate = _soundSampleRate;
-				uint32 newRate = 0x0F4240 / (0x100 - nextSample);
-				fill = (uint16)(((uint32)fill * oldRate) / newRate);
-			}
-
-			uint32 oldSize = _soundPcm.size();
-			_soundPcm.resize(oldSize + fill);
-			memset(&_soundPcm[oldSize], 0x80, fill);
-		} else if (command == 4) {
-			if (2 > end - pc)
-				return false;
-
-			SoundCue cue = {READ_LE_UINT16(data + pc), (uint32)_soundPcm.size(),
-				(uint32)((_soundPcm.size() * 100) / _soundSampleRate)};
-			_soundCues.push_back(cue);
-			pc += 2;
-		} else if (command == 6) {
-			if (2 > end - pc)
-				return false;
-
-			loopCount = READ_LE_UINT16(data + pc);
-			pc += 2;
-			loopPc = pc;
-		} else if (command == 7) {
-			if (loopCount > 0 && loopPc) {
-				loopCount--;
-				pc = loopPc;
-			}
-		} else if (command == 99) {
-			if (pc >= end)
-				return false;
-
-			sample = data[pc++];
-		}
-	}
-
-	bool decoded = !_soundPcm.empty();
-	debug(5, "COMFY VOC: decode id=%u result=%u pcm=%u rate=%u cues=%u",
-		index, decoded ? 1 : 0, (uint)_soundPcm.size(), _soundSampleRate, (uint)_soundCues.size());
-	return decoded;
-}
-
-bool ComfyEngine::soundDecodeCompressedEntry(uint32 dataOffset, uint32 dataSize) {
-	if (dataSize < 5)
-		return false;
-
-	byte sample = _vocFileData[dataOffset + 4];
-	uint32 denominator = 0x100 - sample;
-	_soundSampleRate = denominator ? 0x0F4240 / denominator : 0x2B11;
-	if (_soundSampleRate > 0x2710 && _soundSampleRate < 0x2EE0) {
-		_soundSampleRate = 0x2B11;
-		sample = 0xA5;
-	} else if (_soundSampleRate > 0x4E20 && _soundSampleRate < 0x5DC0) {
-		_soundSampleRate = 0x5622;
-		sample = 0xD3;
-	}
-
-	SoundBitReader bits(&_vocFileData[dataOffset + 5], dataSize - 5);
-	uint32 loopPosition = 0;
-	int16 loopCount = 0;
-	byte width = 4;
-	byte predictorDistance = 1;
-	bool needInit = false;
-	uint32 commandCount = 0;
-	while (!bits.fault() && commandCount++ < dataSize * 8) {
-		uint16 command = bits.read(2);
-		uint32 argument = 0;
-		if (!command) {
-			uint16 subcommand = bits.read(2);
-			if (!subcommand)
-				command = 0;
-			else if (subcommand == 1) {
-				command = bits.read(8);
-				argument = bits.read(20);
-			} else if (subcommand == 2)
-				command = 7;
-			else
-				command = 99;
-		} else if (command == 1) {
-			argument = bits.read(20);
-		} else if (command == 2) {
-			command = 3;
-		} else {
-			command = 4;
-		}
-
-		if (command == 0) {
-			SoundCue cue = {0, (uint32)_soundPcm.size(), (uint32)((_soundPcm.size() * 100) / _soundSampleRate)};
-			_soundCues.push_back(cue);
-			break;
-		} else if (command == 1 || command == 2) {
-			uint32 length = argument;
-			if (command == 1)
-				needInit = true;
-
-			uint32 oldSize = _soundPcm.size();
-			_soundPcm.resize(oldSize + length);
-			uint32 output = oldSize;
-			if (needInit && length) {
-				needInit = false;
-				width = 4;
-				predictorDistance = 1;
-				_soundPcm[output++] = bits.read(8);
-				length--;
-			}
-
-			while (length && !bits.fault()) {
-				uint32 chunk = MIN<uint32>(length, 0x20);
-				if (bits.read(1))
-					width = bits.read(3);
-
-				if (width && bits.read(1))
-					predictorDistance = bits.read(7);
-
-				for (uint i = 0; i < chunk; i++) {
-					byte value;
-					if (!width) {
-						value = bits.read(8);
-					} else {
-						uint16 delta = bits.read(width);
-						if (!delta)
-							value = bits.read(8);
-						else {
-							byte predictor = output >= predictorDistance ? _soundPcm[output - predictorDistance] : 0x80;
-							value = predictor + (byte)(delta - (1 << (width - 1)));
-						}
-					}
-
-					_soundPcm[output++] = value;
-				}
-
-				length -= chunk;
-			}
-		} else if (command == 3) {
-			uint16 fill = bits.read(16);
-			uint32 oldSize = _soundPcm.size();
-			_soundPcm.resize(oldSize + fill);
-			memset(&_soundPcm[oldSize], 0x80, fill);
-		} else if (command == 4) {
-			uint16 mode = bits.read(2);
-			uint16 value = mode == 0 ? 1 : mode == 1 ? 2 : mode == 2 ? bits.read(8) : bits.read(16);
-			SoundCue cue = {value, (uint32)_soundPcm.size(),
-				(uint32)((_soundPcm.size() * 100) / _soundSampleRate)};
-			_soundCues.push_back(cue);
-		} else if (command == 6) {
-			loopCount = bits.read(16);
-			loopPosition = bits.position();
-		} else if (command == 7) {
-			if (loopCount > 0 && loopPosition) {
-				loopCount--;
-				bits.setPosition(loopPosition);
-			}
-		} else if (command == 99) {
-			sample = bits.read(8);
-		}
-	}
-
-	return !_soundPcm.empty() && !bits.fault();
-}
-
 void ComfyEngine::soundPlayEntry(uint16 index) {
 	debug(5, "COMFY VOC: play id=%u", index);
 	_mixer->stopHandle(_soundHandle);
@@ -1055,6 +827,11 @@ void ComfyEngine::soundPlayEntry(uint16 index) {
 		return;
 	}
 
+	_soundTimingPaused = false;
+	_soundVocBlockCount = 0;
+	_soundVocCounterSnapshot = 0;
+	_soundVocTimingDelta = 0;
+
 	byte *buffers[2] = {nullptr, nullptr};
 	uint32 decodedSizes[2] = {0, 0};
 	if (!soundDecodePcmBlock(0, buffers[0], decodedSizes[0]) ||
@@ -1102,6 +879,8 @@ void ComfyEngine::soundAdvanceTick() {
 	if (_soundPaused)
 		return;
 
+	soundUpdateVocTiming();
+
 	if (!_mixer->isSoundHandleActive(_soundHandle)) {
 		_soundQueueStream = nullptr;
 		if (_soundDecoderState && _soundEventSubIndex != 0) {
@@ -1142,6 +921,7 @@ void ComfyEngine::soundAdvanceTick() {
 		_soundQueueStream = nullptr;
 		_soundCues.clear();
 		_soundNextCue = 0;
+		_soundVocTimingDelta = 0;
 		if (_midiPlyrDriver) {
 			_midiPlyrDriver->vocSrResetBlockNo();
 		}


Commit: 03a2e549535627e589f34afeca9d9a6ae7463e0f
    https://github.com/scummvm/scummvm/commit/03a2e549535627e589f34afeca9d9a6ae7463e0f
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: PANTHER: Fix crashes

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/anim_file.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/scene.cpp
    engines/comfy/script_vm.cpp
    engines/comfy/sound.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index 7297a8b1faf..b2b4eedbced 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -552,6 +552,60 @@ void ComfyEngine::spriteBlitClipped(int16 spriteId, int16 x, int16 y) {
 	renderSetDirty();
 }
 
+bool ComfyEngine::spriteCoversPoint(int16 spriteId, int16 x, int16 y, int16 pointX, int16 pointY) {
+	SpriteResource *loadedSprite = spriteGetPtr(spriteId);
+	if (!loadedSprite)
+		return false;
+
+	SpriteResource &sprite = *loadedSprite;
+	if (pointX < x || pointY < y || pointX >= x + (int16)sprite.header.width ||
+			pointY >= y + (int16)sprite.header.height)
+		return false;
+
+	if (sprite.header.width == _logicalScreenWidth && sprite.header.height == _logicalScreenHeight)
+		return true;
+
+	uint32 rowPos = 0;
+	for (uint row = 0; row < sprite.header.height && rowPos + 2 <= sprite.pixels.size(); row++) {
+		uint16 rowSize = READ_LE_UINT16(&sprite.pixels[rowPos]);
+		if (rowSize < 2 || rowPos + rowSize > sprite.pixels.size())
+			return false;
+
+		int16 drawY = y + row;
+		uint32 packetPos = rowPos + 2;
+		int16 drawX = x;
+		while (packetPos < rowPos + rowSize) {
+			byte op = sprite.pixels[packetPos++];
+			uint16 count = op & 0x3F;
+			if (op & 0x80) {
+				if (packetPos >= rowPos + rowSize)
+					return false;
+
+				packetPos++;
+				if (drawY == pointY && pointX >= drawX && pointX < drawX + (int16)count)
+					return true;
+
+				drawX += count;
+			} else if (op & 0x40) {
+				drawX += count;
+			} else {
+				if (packetPos + count > rowPos + rowSize)
+					return false;
+
+				if (drawY == pointY && pointX >= drawX && pointX < drawX + (int16)count)
+					return true;
+
+				packetPos += count;
+				drawX += count;
+			}
+		}
+
+		rowPos += rowSize;
+	}
+
+	return false;
+}
+
 uint32 ComfyEngine::actorReadU32(Actor &actor, uint offset) {
 	if (offset + 4 > _actorSize)
 		return 0;
@@ -899,6 +953,16 @@ void ComfyEngine::actorSetAllVisible() {
 		actorWriteU8(_actors[i], kActorDirty, 1);
 }
 
+void ComfyEngine::actorClearFirstAnimFrameSelector() {
+	for (uint actorIndex = 1; actorIndex < COMFY_ACTOR_COUNT; actorIndex++) {
+		Actor *actor = actorGetPtr(actorIndex);
+		if (actor && actorReadU32(*actor, kActorSpriteSelector) == 0x00FFFFFF) {
+			actorWriteU32(*actor, kActorSpriteSelector, 0);
+			break;
+		}
+	}
+}
+
 bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
 	Actor *actor = actorGetPtr(actorIndex);
 	descendChildren = false;
@@ -1063,7 +1127,7 @@ void ComfyEngine::actorDrawList(uint16 actorIndex, int16 x, int16 y, bool visibl
 	}
 }
 
-void ComfyEngine::renderQueueDrawCommand(int16 x, int16 y, uint32 selector, byte mode) {
+void ComfyEngine::renderQueueDrawCommand(int16 x, int16 y, uint32 selector, byte mode, uint16 actorIndex) {
 	if (!selector)
 		return;
 
@@ -1075,18 +1139,46 @@ void ComfyEngine::renderQueueDrawCommand(int16 x, int16 y, uint32 selector, byte
 	command.y = y;
 	command.selector = selector;
 	command.mode = mode;
+	command.actorIndex = actorIndex;
 	if (_drawCommandCount >= COMFY_DRAW_COMMAND_CAPACITY)
 		error("Too many actor draw commands");
 }
 
 void ComfyEngine::renderFlushDrawCommands() {
-	if (_isPanther && actorGetFrame())
+	if ((_isPanther || _engineVersion == 3) && actorGetFrame())
 		backgroundRestoreDirtyRects();
 
 	for (uint i = 0; i < _drawCommandCount; i++) {
 		DrawCommand &command = _drawCommands[i];
 		if (command.mode == 2) {
+			if (_engineVersion == 3) {
+				for (uint next = i + 1; next < _drawCommandCount; next++) {
+					DrawCommand &nextCommand = _drawCommands[next];
+					if (nextCommand.mode != 0)
+						continue;
+
+					SpriteResource *nextSprite = spriteGetPtr((int16)nextCommand.selector);
+					if (!nextSprite)
+						continue;
+
+					VideoRectRecord dirtyRect;
+					dirtyRect.left = nextCommand.x;
+					dirtyRect.top = nextCommand.y;
+					dirtyRect.right = nextCommand.x + nextSprite->header.width;
+					dirtyRect.bottom = nextCommand.y + nextSprite->header.height;
+					dirtyRect.area = (uint32)nextSprite->header.width * nextSprite->header.height;
+					videoFindBestMode(dirtyRect);
+				}
+			}
+
+			bool coversMouse = animFrameCoversPoint(command.x, command.y, _mouseX, _mouseY);
 			animFrameBlitAt(command.x, command.y);
+			if (_engineVersion == 3 && command.actorIndex) {
+				Actor *actor = actorGetPtr(command.actorIndex);
+				if (actor)
+					actorWriteU8(*actor, kActorBlitHitMouse, coversMouse ? 1 : 0);
+			}
+
 			continue;
 		}
 
@@ -1094,7 +1186,14 @@ void ComfyEngine::renderFlushDrawCommands() {
 		if (!sprite)
 			continue;
 
+		bool coversMouse = spriteCoversPoint((int16)command.selector, command.x, command.y, _mouseX, _mouseY);
 		spriteBlitClipped((int16)command.selector, command.x, command.y);
+		if (_engineVersion == 3 && command.actorIndex) {
+			Actor *actor = actorGetPtr(command.actorIndex);
+			if (actor)
+				actorWriteU8(*actor, kActorBlitHitMouse, coversMouse ? 1 : 0);
+		}
+
 		if (command.mode == 0) {
 			VideoRectRecord dirtyRect;
 			dirtyRect.left = command.x;
@@ -1185,17 +1284,19 @@ uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &m
 
 		_keymaskX = baseX + (int16)dx;
 		_keymaskY = baseY + (int16)dy;
-		if (_keymaskX >= 0x0280 || _keymaskX <= (int16)0xFEC0 ||
-				_keymaskY >= 0x0190 || _keymaskY <= (int16)0xFF38)
+		if (_engineVersion <= 2 && (_keymaskX >= 0x0280 || _keymaskX <= (int16)0xFEC0 ||
+				_keymaskY >= 0x0190 || _keymaskY <= (int16)0xFF38))
 			continue;
 
-		SpriteResource *sprite = spriteGetPtr((int16)spriteId);
+		SpriteResource *sprite = _engineVersion <= 2 ?
+			spriteGetPtr((int16)spriteId) :
+			spriteLookup(spriteId, _keymaskX, _keymaskY);
 		if (!sprite)
 			continue;
 
 		int16 left = _keymaskX - sprite->header.hotspotX;
 		int16 top = _keymaskY - sprite->header.hotspotY;
-		if (mode == 1 && !_usesAnimFile)
+		if (mode == 1 && _engineVersion <= 2 && !_isPanther)
 			spriteBlitClipped((int16)spriteId, left, top);
 
 		if (rect) {
@@ -1203,7 +1304,7 @@ uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &m
 			rect->top = top;
 			rect->right = left + sprite->header.width;
 			rect->bottom = top + sprite->header.height;
-			rect->area = _usesAnimFile ? spriteId :
+			rect->area = (_isPanther || _engineVersion == 3) ? spriteId :
 				(uint32)sprite->header.width * sprite->header.height;
 		}
 	}
@@ -1302,13 +1403,14 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 	}
 
 	animFrameRecordVocCounter(1);
-	if (_isPanther && _videoMode != 2 && _videoMode != 4)
+	bool queuedActorDraw = _usesAnimFile && (_isPanther || _engineVersion == 3) && (_videoMode == 2 || _videoMode == 4);
+	if ((_isPanther || _engineVersion == 3) && !queuedActorDraw)
 		actorDrawLegacyInternal(actorIndex, x, y);
 	else
 		actorDrawInternal(actorIndex, x, y, true);
 
 	if (_usesAnimFile) {
-		if (_isPanther && (_videoMode == 2 || _videoMode == 4))
+		if (queuedActorDraw)
 			renderFlushDrawCommands();
 
 		animFrameRecordVocCounter(2);
@@ -1403,7 +1505,8 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 	VideoRectRecord oldRect = actorReadCachedRect(*actor);
 	actorDrawList(actorReadU16(*actor, kActorSiblingHead), drawX, drawY, visible);
 	uint32 selector = actorReadU32(*actor, kActorSpriteSelector);
-	if (_isPanther) {
+	bool useDrawQueue = _usesAnimFile && (_isPanther || _engineVersion == 3) && (_videoMode == 2 || _videoMode == 4);
+	if (_isPanther || _engineVersion == 3) {
 		VideoRectRecord newRect;
 		if (selector == 0x00FFFFFF) {
 			bool changed = false;
@@ -1420,10 +1523,10 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 				newRect.top = drawY;
 				actorWriteU8(*actor, _actorCachedVisibleOffset, visible ? 1 : 0);
 				actorWriteCachedRect(*actor, newRect);
-				renderQueueDrawCommand(drawX, drawY, selector, 2);
+				renderQueueDrawCommand(drawX, drawY, selector, 2, actorIndex);
 			} else if (visible && actorReadU8(*actor, kActorVisible)) {
 				animFrameInvalidateRects(drawX, drawY, 0);
-				renderQueueDrawCommand(drawX, drawY, selector, 2);
+				renderQueueDrawCommand(drawX, drawY, selector, 2, actorIndex);
 			}
 
 			actorDrawList(actorReadU16(*actor, kActorChildHead), drawX, drawY, visible);
@@ -1476,7 +1579,7 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 						videoFindBestMode(previousRect);
 
 					renderQueueDrawCommand(currentRect.left, currentRect.top,
-						currentRect.area, equal ? 1 : 0);
+						currentRect.area, equal ? 1 : 0, actorIndex);
 				}
 			}
 
@@ -1494,10 +1597,10 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 				if (scripted && currentLastRect != 0xFFFF) {
 					for (uint i = 0; i <= currentLastRect; i++) {
 						VideoRectRecord &rect = _keymaskRects[i];
-						renderQueueDrawCommand(rect.left, rect.top, rect.area, 0);
+						renderQueueDrawCommand(rect.left, rect.top, rect.area, 0, actorIndex);
 					}
 				} else if (!scripted) {
-					renderQueueDrawCommand(newRect.left, newRect.top, newRect.area, 0);
+					renderQueueDrawCommand(newRect.left, newRect.top, newRect.area, 0, actorIndex);
 				}
 			}
 
@@ -1527,10 +1630,10 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			if (scripted && currentLastRect != 0xFFFF) {
 				for (uint i = 0; i <= currentLastRect; i++) {
 					VideoRectRecord &rect = _keymaskRects[i];
-					renderQueueDrawCommand(rect.left, rect.top, rect.area, 1);
+					renderQueueDrawCommand(rect.left, rect.top, rect.area, 1, actorIndex);
 				}
 			} else if (!scripted) {
-				renderQueueDrawCommand(newRect.left, newRect.top, newRect.area, 1);
+				renderQueueDrawCommand(newRect.left, newRect.top, newRect.area, 1, actorIndex);
 			}
 		}
 
@@ -1558,8 +1661,8 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 				for (uint i = 0; i <= scriptedLastRect; i++) {
 					VideoRectRecord &drawRecord = _keymaskRects[i];
 					if (drawRecord.area) {
-						if (_isPanther)
-							renderQueueDrawCommand(drawRecord.left, drawRecord.top, drawRecord.area, 1);
+						if (useDrawQueue)
+							renderQueueDrawCommand(drawRecord.left, drawRecord.top, drawRecord.area, 1, actorIndex);
 						else
 							spriteBlitClipped((int16)drawRecord.area, drawRecord.left, drawRecord.top);
 					}
@@ -1591,8 +1694,8 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 					if (sprite) {
 						int16 spriteX = drawX + dx - sprite->header.hotspotX;
 						int16 spriteY = drawY + dy - sprite->header.hotspotY;
-						if (_isPanther && (_videoMode == 2 || _videoMode == 4))
-							renderQueueDrawCommand(spriteX, spriteY, spriteId, 1);
+						if (useDrawQueue)
+							renderQueueDrawCommand(spriteX, spriteY, spriteId, 1, actorIndex);
 						else
 							spriteBlitClipped((int16)spriteId, spriteX, spriteY);
 					}
@@ -1613,8 +1716,8 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 		newRect.bottom = drawY + frameHeight;
 		newRect.area = frameWidth * frameHeight;
 		if (visible) {
-			if (_isPanther && (_videoMode == 2 || _videoMode == 4)) {
-				renderQueueDrawCommand(drawX, drawY, selector, 2);
+			if (useDrawQueue) {
+				renderQueueDrawCommand(drawX, drawY, selector, 2, actorIndex);
 			} else {
 				animFrameInvalidateRects(drawX, drawY, 1);
 				animFrameBlitAt(drawX, drawY);
@@ -1631,8 +1734,8 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			if (visible) {
 				int16 spriteX = drawX - sprite->header.hotspotX;
 				int16 spriteY = drawY - sprite->header.hotspotY;
-				if (_isPanther && (_videoMode == 2 || _videoMode == 4))
-					renderQueueDrawCommand(spriteX, spriteY, selector, 1);
+				if (useDrawQueue)
+					renderQueueDrawCommand(spriteX, spriteY, selector, 1, actorIndex);
 				else
 					spriteBlitClipped((int16)selector, spriteX, spriteY);
 			}
diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
index d5453c8ddf1..5ef793e16aa 100644
--- a/engines/comfy/anim_file.cpp
+++ b/engines/comfy/anim_file.cpp
@@ -101,6 +101,9 @@ void ComfyEngine::animFrameShutdown(bool freeBuffers) {
 		if (_stringTable.size() > 14)
 			_stringTable[14] = 0;
 
+		if (_animUsesWaveVocCounter)
+			vocQueuePlayAll();
+
 		if (_animCurrentFrameKey)
 			keyBitSet(_animCurrentFrameKey);
 
@@ -127,6 +130,7 @@ void ComfyEngine::animFileShutdown() {
 	_animIndexTable.clear();
 	_animIndexLoaded = false;
 	_animPantherFormat = false;
+	_animShutdownBeforeSceneStart = false;
 }
 
 void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 actorSceneHandle) {
@@ -134,6 +138,7 @@ void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 ac
 		return;
 
 	animFrameShutdown(true);
+	_animShutdownBeforeSceneStart = true;
 
 	uint32 offset = _animIndexTable[animIndex];
 	if (offset > _animFileData.size() || COMFY_ANMFILE_HEADER_BYTES > _animFileData.size() - offset)
@@ -156,6 +161,7 @@ void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 ac
 	_animFrameCommandArgument = 0;
 	_animFrameCommandFlag = false;
 	_animPosition = offset + COMFY_ANMFILE_HEADER_BYTES;
+	_animSavedStreamPosition = COMFY_ANMFILE_HEADER_BYTES;
 	_animSoundDataPosition = 0;
 	_animCurrentIndex = animIndex;
 	_animCurrentActorSceneHandle = actorSceneHandle;
@@ -383,17 +389,48 @@ void ComfyEngine::animFileTickCommands() {
 
 		byte *header = &_animFileData[_animPosition];
 		uint16 command = READ_LE_UINT16(header);
+		uint32 commandStart = _animPosition;
 		uint32 rawCommandSize = _animPantherFormat ? READ_LE_UINT32(header + 2) : READ_LE_UINT16(header + 2);
+		int32 signedCommandSize = _animPantherFormat ? (int32)rawCommandSize : (int32)(uint16)rawCommandSize;
 		uint32 commandSize = rawCommandSize;
-		debug(5, "COMFY ANM: index=%u position=%u command=0x%04X size=%u argument=%u",
-			_animCurrentIndex, _animPosition, command, commandSize,
+		debug(5, "COMFY ANM: index=%u position=%u command=0x%04X size=%u signedSize=%d argument=%u",
+			_animCurrentIndex, _animPosition, command, commandSize, signedCommandSize,
 			_animPantherFormat ? READ_LE_UINT16(header + 6) : 0);
+
+		// WPANTHER compares the FR command size as signed. Some Panther data uses
+		// negative sizes here; this marks the frame ready without decoding payload.
+		if (_animPantherFormat && command == kAnimCommandFrame && signedCommandSize <= (int32)headerSize) {
+			int64 nextPosition = (int64)commandStart + signedCommandSize;
+			if (nextPosition < 0 || nextPosition > (int64)_animFileData.size())
+				error("Invalid Panther animation frame command cursor: index=%u frameKey=%u position=%u command=0x%04X signedSize=%d header=%02X %02X %02X %02X %02X %02X %02X %02X",
+					_animCurrentIndex, _animCurrentFrameKey, commandStart, command, signedCommandSize,
+					header[0], header[1], header[2], header[3], header[4], header[5], header[6], header[7]);
+
+			uint32 frameStart = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
+			_animSavedStreamPosition = (uint32)nextPosition - frameStart;
+
+			// The original file object has already consumed the 8-byte FR header.
+			// Its separately serialized cursor can be signed and point backward.
+			_animPosition = commandStart + headerSize;
+			frameReady = true;
+			continue;
+		}
+
 		if (commandSize < headerSize || commandSize > _animFileData.size() - _animPosition)
-			error("Invalid animation command size in ANMFILE.DAT");
+			error("Invalid animation command size in ANMFILE.DAT: index=%u frameKey=%u position=%u command=0x%04X size=%u headerSize=%u remaining=%u argument=%u panther=%u engineVersion=%u header=%02X %02X %02X %02X %02X %02X %02X %02X",
+				_animCurrentIndex, _animCurrentFrameKey, _animPosition, command, commandSize, headerSize,
+				(uint)(_animFileData.size() - _animPosition),
+				_animPantherFormat ? READ_LE_UINT16(header + 6) : 0,
+				_animPantherFormat ? 1 : 0, _engineVersion,
+				header[0], header[1], header[2], header[3],
+				headerSize > 4 ? header[4] : 0, headerSize > 5 ? header[5] : 0,
+				headerSize > 6 ? header[6] : 0, headerSize > 7 ? header[7] : 0);
 
 		uint32 payloadSize = commandSize - headerSize;
 		byte *payload = header + headerSize;
 		_animPosition += commandSize;
+		_animSavedStreamPosition = _animPosition -
+			(_animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES);
 		if (command == kAnimCommandEnd) {
 			ended = true;
 		} else if (command == kAnimCommandStoreFrameBytes) {
@@ -408,8 +445,14 @@ void ComfyEngine::animFileTickCommands() {
 				_animSoundDataPosition += payloadSize;
 		} else if (command == kAnimCommandDirtyRect) {
 			_animFrameCommandDataSize = payloadSize;
-			_animFrameCommandFlag = false;
-			_animFrameCommandArgument = _animPantherFormat ? READ_LE_UINT16(header + 6) : payloadSize;
+			if (_animPantherFormat && _engineVersion == 3) {
+				_animFrameCommandFlag = (READ_LE_UINT16(header + 6) & 0x8000) != 0;
+				_animFrameCommandArgument = READ_LE_UINT16(header + 6) & 0x07FF;
+			} else {
+				_animFrameCommandFlag = false;
+				_animFrameCommandArgument = _animPantherFormat ? READ_LE_UINT16(header + 6) : payloadSize;
+			}
+
 			memset(_animFrameCommandData, 0, sizeof(_animFrameCommandData));
 			memcpy(_animFrameCommandData, payload, MIN<uint32>(payloadSize, sizeof(_animFrameCommandData)));
 		} else if (command == kAnimCommandFrame) {
@@ -561,6 +604,36 @@ bool ComfyEngine::animFrameBlitAt(int16 x, int16 y) {
 	return true;
 }
 
+bool ComfyEngine::animFrameCoversPoint(int16 x, int16 y, int16 pointX, int16 pointY) {
+	if (_animFrameBuffer.empty())
+		return false;
+
+	uint16 frameWidth = 0;
+	uint16 frameHeight = 0;
+	if (!animFrameGetDimensions(frameWidth, frameHeight))
+		return false;
+
+	if (pointX < x || pointY < y || pointX >= x + (int16)frameWidth ||
+			pointY >= y + (int16)frameHeight)
+		return false;
+
+	bool dirty = false;
+	for (uint i = 0; i < _resolutionChangeCount; i++) {
+		VideoRectRecord &dirtyRect = _resolutionChanges[i];
+		if (pointX >= dirtyRect.left && pointX < dirtyRect.right &&
+				pointY >= dirtyRect.top && pointY < dirtyRect.bottom) {
+			dirty = true;
+			break;
+		}
+	}
+
+	if (!dirty)
+		return false;
+
+	uint32 offset = (uint32)(pointY - y) * _logicalScreenWidth + pointX - x;
+	return offset < _animFrameBuffer.size() && _animFrameBuffer[offset] != 0xFF;
+}
+
 void ComfyEngine::animFrameInvalidateRects(int16 x, int16 y, byte mode) {
 	if (_animFrameBuffer.empty())
 		return;
@@ -568,15 +641,22 @@ void ComfyEngine::animFrameInvalidateRects(int16 x, int16 y, byte mode) {
 	uint16 rectCount = MIN<uint16>(_animFrameCommandDataSize / 4,
 		sizeof(_animFrameCommandData) / 4);
 	uint16 splitIndex = _animFrameCommandArgument / 4;
+	uint16 columns = _isPanther ? 0x00A0 : 0x0050;
+	if (_engineVersion == 3 && _animFrameCommandFlag) {
+		uint16 frameWidth = READ_LE_UINT16(_animFrameHeader + 10);
+		if (frameWidth)
+			columns = frameWidth / 4;
+	}
+
 	_animFrameDirtyRectCount = 0;
 	for (uint i = 0; i < rectCount; i++) {
 		uint16 start = READ_LE_UINT16(_animFrameCommandData + i * 4);
 		uint16 end = READ_LE_UINT16(_animFrameCommandData + i * 4 + 2);
 		VideoRectRecord rect;
-		rect.left = x + (start % (_logicalScreenWidth / 4)) * 4;
-		rect.top = y + (start / (_logicalScreenWidth / 4)) * 4;
-		rect.right = x + ((end % (_logicalScreenWidth / 4)) + 1) * 4;
-		rect.bottom = y + ((end / (_logicalScreenWidth / 4)) + 1) * 4;
+		rect.left = x + (start % columns) * 4;
+		rect.top = y + (start / columns) * 4;
+		rect.right = x + ((end % columns) + 1) * 4;
+		rect.bottom = y + ((end / columns) + 1) * 4;
 		rect.area = (uint32)(rect.right - rect.left) * (rect.bottom - rect.top);
 
 		if (i < splitIndex) {
@@ -650,12 +730,7 @@ void ComfyEngine::animFilePackState(byte *state) {
 		WRITE_LE_UINT32(state + 0x24, _animFrameStorage.size());
 	}
 
-	uint32 streamPosition = 0;
-	if (_animCurrentIndex < _animIndexTable.size()) {
-		uint32 frameStart = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
-		if (_animPosition >= frameStart)
-			streamPosition = _animPosition - frameStart;
-	}
+	uint32 streamPosition = _animSavedStreamPosition;
 
 	uint32 streamPositionOffset = _animPantherFormat ? 0x27 : 0x28;
 	uint32 chunkTableOffset = _animPantherFormat ? 0x2B : 0x2C;
@@ -678,6 +753,7 @@ void ComfyEngine::animFileRestoreStreamPosition(const byte *state) {
 		error("Invalid restored stream position in ANMFILE.DAT");
 
 	_animPosition = frameStart + streamPosition;
+	_animSavedStreamPosition = streamPosition;
 }
 
 void ComfyEngine::animFileRebuildStorage(uint32 targetSize) {
@@ -701,9 +777,17 @@ void ComfyEngine::animFileRebuildStorage(uint32 targetSize) {
 		byte *header = &_animFileData[position];
 		uint16 command = READ_LE_UINT16(header);
 		uint32 rawCommandSize = _animPantherFormat ? READ_LE_UINT32(header + 2) : READ_LE_UINT16(header + 2);
+		int32 signedCommandSize = _animPantherFormat ? (int32)rawCommandSize : (int32)(uint16)rawCommandSize;
 		uint32 commandSize = rawCommandSize;
+		if (_animPantherFormat && command == kAnimCommandFrame && signedCommandSize <= (int32)headerSize)
+			break;
+
 		if (commandSize < headerSize || commandSize > _animFileData.size() - position)
-			error("Invalid command while rebuilding animation storage");
+			error("Invalid command while rebuilding animation storage: index=%u frameKey=%u position=%u target=%u command=0x%04X size=%u signedSize=%d header=%02X %02X %02X %02X %02X %02X %02X %02X",
+				_animCurrentIndex, _animCurrentFrameKey, position, _animPosition, command, commandSize,
+				signedCommandSize, header[0], header[1], header[2], header[3],
+				headerSize > 4 ? header[4] : 0, headerSize > 5 ? header[5] : 0,
+				headerSize > 6 ? header[6] : 0, headerSize > 7 ? header[7] : 0);
 
 		uint32 payloadSize = commandSize - headerSize;
 		byte *payload = header + headerSize;
@@ -717,8 +801,14 @@ void ComfyEngine::animFileRebuildStorage(uint32 targetSize) {
 				memcpy(&_animFrameStorage[oldSize], payload, copySize);
 		} else if (command == kAnimCommandDirtyRect) {
 			_animFrameCommandDataSize = payloadSize;
-			_animFrameCommandFlag = false;
-			_animFrameCommandArgument = _animPantherFormat ? READ_LE_UINT16(header + 6) : payloadSize;
+			if (_animPantherFormat && _engineVersion == 3) {
+				_animFrameCommandFlag = (READ_LE_UINT16(header + 6) & 0x8000) != 0;
+				_animFrameCommandArgument = READ_LE_UINT16(header + 6) & 0x07FF;
+			} else {
+				_animFrameCommandFlag = false;
+				_animFrameCommandArgument = _animPantherFormat ? READ_LE_UINT16(header + 6) : payloadSize;
+			}
+
 			memset(_animFrameCommandData, 0, sizeof(_animFrameCommandData));
 			memcpy(_animFrameCommandData, payload, MIN<uint32>(payloadSize, sizeof(_animFrameCommandData)));
 		}
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index c9eaeb638cf..bb99e74171e 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -460,7 +460,17 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 			if (_musicEventFlag)
 				vocQueuePlayAll();
 
-			if (vocQueueIsIdle() || _musicEnabled) {
+			bool processMusicEvents = true;
+			if (_engineVersion == 3 && animFrameIsActive() && !animFrameIsReady())
+				processMusicEvents = false;
+
+			if (!_isPanther && !vocQueueIsIdle() && !_musicEnabled)
+				processMusicEvents = false;
+
+			if (processMusicEvents) {
+				if (_engineVersion == 3)
+					_animShutdownBeforeSceneStart = false;
+
 				uint16 track = 1;
 				for (;;) {
 					_musicEventMask = (uint16)((int16)_musicEventMask >> 1);
@@ -477,7 +487,16 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 
 		keyBitClear(0x42);
 		if (_pendingScene) {
+			bool animFrameReady = animFrameIsReady();
+			if (_engineVersion == 3 && _animShutdownBeforeSceneStart)
+				animFrameShutdown(true);
+
 			sceneStartWithMusic(_pendingScene);
+			if (_engineVersion == 3 && !animFrameReady) {
+				animFrameShutdown(true);
+				actorClearFirstAnimFrameSelector();
+			}
+
 			if (!_musicEnabled)
 				vocQueuePlayAll();
 
@@ -485,7 +504,7 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 			frame = actorGetFrame();
 			if (frame)
 				backgroundTransitionFrames(frame, _backgroundFrame);
-		} else {
+		} else if (_engineVersion != 3) {
 			actorSetAllVisible();
 		}
 	}
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 084fd5236e6..9308d7eb253 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -131,12 +131,14 @@ private:
 		int16 y;
 		uint32 selector;
 		byte mode;
+		uint16 actorIndex;
 
 		DrawCommand() {
 			x = 0;
 			y = 0;
 			selector = 0;
 			mode = 0;
+			actorIndex = 0;
 		}
 	};
 
@@ -359,7 +361,8 @@ private:
 		kActorDirty = 0x44,
 		kActorCachedRect = 0x45,
 		kActorCachedVisible = 0x4F,
-		kActorCachedSprite = 0x50
+		kActorCachedSprite = 0x50,
+		kActorBlitHitMouse = 0x56
 	};
 
 	enum ScriptDispatchStatus {
@@ -652,6 +655,7 @@ private:
 	byte _animFrameHeader[COMFY_ANMFILE_HEADER_BYTES];
 	byte _animFrameCommandData[COMFY_ANMFRAME_COMMAND_DATA_BYTES];
 	uint32 _animPosition = 0;
+	uint32 _animSavedStreamPosition = 0;
 	uint32 _animSoundDataPosition = 0;
 	uint16 _animFrameCommandDataSize = 0;
 	uint16 _animFrameCommandArgument = 0;
@@ -672,6 +676,7 @@ private:
 	bool _animActive = false;
 	bool _animFrameReady = false;
 	bool _animUsesWaveVocCounter = false;
+	bool _animShutdownBeforeSceneStart = false;
 	uint16 _exprStack[COMFY_EXPR_STACK_CAPACITY];
 	uint16 _exprStackTop = 0;
 	bool _scriptFault = false;
@@ -775,6 +780,7 @@ private:
 	void spriteGetConvPtr(int16 spriteId);
 	bool spriteDecompressTile(SpriteResource &sprite, const byte *source, uint32 sourceSize);
 	void spriteBlitClipped(int16 spriteId, int16 x, int16 y);
+	bool spriteCoversPoint(int16 spriteId, int16 x, int16 y, int16 pointX, int16 pointY);
 	void spriteBlitRle(byte *destination, const byte *source, uint32 sourceSize);
 	bool sceneOpen(uint32 sceneEntryListOffset);
 	void sceneShutdown();
@@ -822,6 +828,7 @@ private:
 	void actorFreeTreePc(uint16 actorIndex);
 	void actorClearDirtyTree(uint16 actorIndex);
 	void actorSetAllVisible();
+	void actorClearFirstAnimFrameSelector();
 	uint16 actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible, byte active,
 		uint32 pc, int16 x, int16 y, int16 sprite, byte insertAsChild);
 	bool actorRunScript(uint16 actorIndex, bool &descendChildren);
@@ -830,7 +837,7 @@ private:
 	void actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool visible);
 	bool actorDrawLegacyInternal(uint16 actorIndex, int16 x, int16 y);
 	void actorDrawList(uint16 actorIndex, int16 x, int16 y, bool visible);
-	void renderQueueDrawCommand(int16 x, int16 y, uint32 selector, byte mode);
+	void renderQueueDrawCommand(int16 x, int16 y, uint32 selector, byte mode, uint16 actorIndex);
 	void renderFlushDrawCommands();
 	void renderFlushCachedDirtyRects();
 	uint16 scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &maskRecord,
@@ -866,6 +873,7 @@ private:
 	void animFrameWaitForVocCounter();
 	void animFrameSetReady(bool ready);
 	bool animFrameBlitAt(int16 x, int16 y);
+	bool animFrameCoversPoint(int16 x, int16 y, int16 pointX, int16 pointY);
 	void animFrameInvalidateRects(int16 x, int16 y, byte mode);
 	bool animFrameGetDimensions(uint16 &width, uint16 &height);
 	void animFrameClear();
@@ -914,6 +922,13 @@ private:
 	bool vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc);
 	void vocQueuePlayAll();
 	bool vocQueueIsIdle();
+	void wcomfy99SetWaveBalancePercent(uint16 value);
+	void wcomfy99SetWaveLeftPercent(uint16 value);
+	void wcomfy99SetWaveRightPercent(uint16 value);
+	void wcomfy99SetMixerVolumePercent(uint16 value);
+	void wcomfy99SetHostMediaRangePercent(uint16 value);
+	void wcomfy99SetHostMediaMode(byte mode);
+	void wcomfy99RestoreHostStateAfterSceneStart();
 	bool soundInit();
 	void soundShutdown();
 	void soundHdrReadFromXms(byte *destination, uint16 index, uint16 size);
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index 615d2d5ff7b..6dc339a897b 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -338,6 +338,9 @@ void ComfyEngine::sceneStartWithMusic(uint16 scene) {
 
 	if (_keyBits)
 		memcpy(_keyBits, keySnapshot, MIN<uint32>(sizeof(keySnapshot), _keyBitsSize));
+
+	if (_engineVersion == 3)
+		wcomfy99RestoreHostStateAfterSceneStart();
 }
 
 bool ComfyEngine::sceneEntryLoad(uint16 descriptor, uint16 index) {
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 3382d57fd54..67f66210ac4 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -827,35 +827,29 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 			uint16 argument = scriptReadWord(pc);
 			pc += 2;
-			uint16 percentage = argument == 0x00FF ? 0x00FF : ((int16)argument < 0 ? 0 : MIN<uint16>(argument, 100));
 
 			switch (subop) {
 			case 1:
 				_wcomfy99HostWordA = argument;
 				break;
 			case 2:
-				if (percentage != 0x00FF)
-					_wcomfy99WaveVolumePercent = percentage;
+				wcomfy99SetWaveBalancePercent(argument);
 				break;
 			case 3:
-				if (percentage != 0x00FF)
-					_wcomfy99WaveLeftPercent = percentage;
+				_wcomfy99HostWordB = argument;
 				break;
 			case 4:
-				if (percentage != 0x00FF)
-					_wcomfy99WaveRightPercent = percentage;
+				wcomfy99SetWaveLeftPercent(argument);
 				break;
 			case 5:
-			case 6:
-				if (percentage != 0x00FF)
-					_wcomfy99MixerVolumePercent = percentage;
+				wcomfy99SetWaveRightPercent(argument);
 				break;
+			case 6:
 			case 7:
-				if (percentage != 0x00FF)
-					_wcomfy99MixerAltPercent = percentage;
+				wcomfy99SetHostMediaRangePercent(argument);
 				break;
 			case 8:
-				_wcomfy99HostWordB = argument;
+				wcomfy99SetMixerVolumePercent(argument);
 				break;
 			default:
 				break;
diff --git a/engines/comfy/sound.cpp b/engines/comfy/sound.cpp
index 0552d7acf4e..3e14bddbf59 100644
--- a/engines/comfy/sound.cpp
+++ b/engines/comfy/sound.cpp
@@ -522,6 +522,91 @@ private:
 	BufferState _bufferStates[2];
 };
 
+void ComfyEngine::wcomfy99SetWaveBalancePercent(uint16 value) {
+	if ((int16)value < 0)
+		value = 0;
+	else if (value > 100)
+		value = 100;
+
+	_wcomfy99VocState0 = (byte)value;
+	_wcomfy99WaveVolumePercent = value;
+}
+
+void ComfyEngine::wcomfy99SetWaveLeftPercent(uint16 value) {
+	if (value == 0x00FF)
+		return;
+
+	if ((int16)value < 0)
+		value = 0;
+	else if (value > 100)
+		value = 100;
+
+	_wcomfy99VocState2 = (byte)value;
+	_wcomfy99WaveLeftPercent = value;
+}
+
+void ComfyEngine::wcomfy99SetWaveRightPercent(uint16 value) {
+	if (value == 0x00FF)
+		return;
+
+	if ((int16)value < 0)
+		value = 0;
+	else if (value > 100)
+		value = 100;
+
+	_wcomfy99VocState3 = (byte)value;
+	_wcomfy99WaveRightPercent = value;
+}
+
+void ComfyEngine::wcomfy99SetMixerVolumePercent(uint16 value) {
+	if (value == 0x00FF)
+		return;
+
+	if ((int16)value < 0)
+		value = 0;
+	else if (value > 100)
+		value = 100;
+
+	_wcomfy99VocState6 = (byte)value;
+	_wcomfy99MixerVolumePercent = value;
+}
+
+void ComfyEngine::wcomfy99SetHostMediaRangePercent(uint16 value) {
+	if ((int16)value < 0)
+		value = 0;
+	else if (value > 100)
+		value = 100;
+
+	_wcomfy99MixerAltPercent = value;
+}
+
+void ComfyEngine::wcomfy99SetHostMediaMode(byte mode) {
+	if (mode == 1 || mode == 3) {
+		_wcomfy99VocState1 = 1;
+		if (!_wcomfy99HostMediaValueAvailable) {
+			_wcomfy99HostMediaValue = 0;
+			_wcomfy99HostMediaValueAvailable = true;
+		}
+	} else if (mode == 2) {
+		_wcomfy99VocState1 = 0;
+		_wcomfy99HostMediaValue = 0;
+		_wcomfy99HostMediaValueAvailable = false;
+	}
+}
+
+void ComfyEngine::wcomfy99RestoreHostStateAfterSceneStart() {
+	wcomfy99SetWaveBalancePercent(_wcomfy99VocState0);
+	wcomfy99SetWaveLeftPercent(_wcomfy99VocState2);
+	wcomfy99SetWaveRightPercent(_wcomfy99VocState3);
+	wcomfy99SetMixerVolumePercent(_wcomfy99VocState6);
+	if (_wcomfy99VocState1) {
+		wcomfy99SetHostMediaMode(2);
+		wcomfy99SetHostMediaMode(1);
+	} else {
+		wcomfy99SetHostMediaMode(2);
+	}
+}
+
 bool ComfyEngine::soundInit() {
 	if (!readAssetFile(Common::Path("VOCFILE.DAT"), _vocFileData) || _vocFileData.size() < 4)
 		return false;


Commit: 3a979923cc41859734431c9eb403c7e56fe401f4
    https://github.com/scummvm/scummvm/commit/3a979923cc41859734431c9eb403c7e56fe401f4
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: PANTHER: Fix gfx glitches

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/anim_file.cpp
    engines/comfy/script_vm.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index b2b4eedbced..af37f1afc94 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -1140,6 +1140,7 @@ void ComfyEngine::renderQueueDrawCommand(int16 x, int16 y, uint32 selector, byte
 	command.selector = selector;
 	command.mode = mode;
 	command.actorIndex = actorIndex;
+
 	if (_drawCommandCount >= COMFY_DRAW_COMMAND_CAPACITY)
 		error("Too many actor draw commands");
 }
diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
index 5ef793e16aa..1a36f9152d4 100644
--- a/engines/comfy/anim_file.cpp
+++ b/engines/comfy/anim_file.cpp
@@ -114,7 +114,7 @@ void ComfyEngine::animFrameShutdown(bool freeBuffers) {
 
 	if (freeBuffers) {
 		_animFrameBuffer.clear();
-		if (_animCurrentActorSceneHandle < _sceneHandles.size()) {
+		if (_animCurrentActorSceneHandle && _animCurrentActorSceneHandle < _sceneHandles.size()) {
 			Actor *actor = actorGetPtr(sceneGetHandle(_animCurrentActorSceneHandle));
 			if (actor)
 				actorWriteU32(*actor, kActorSpriteSelector, 0);
@@ -137,7 +137,10 @@ void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 ac
 	if (!_animIndexLoaded || _animActive || animIndex >= _animIndexTable.size())
 		return;
 
-	animFrameShutdown(true);
+	if (_engineVersion == 3)
+		animFrameShutdown(true);
+
+	renderFlushCachedDirtyRects();
 	_animShutdownBeforeSceneStart = true;
 
 	uint32 offset = _animIndexTable[animIndex];
@@ -600,7 +603,6 @@ bool ComfyEngine::animFrameBlitAt(int16 x, int16 y) {
 		}
 	}
 
-	renderSetDirty();
 	return true;
 }
 
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 67f66210ac4..30ad20e3201 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -78,7 +78,8 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	}
 
 	case 0x03: {
-		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
+		uint16 actorSlot = scriptReadWord(pc);
+		Actor *target = actorResolve(actorSlot, _currentActor);
 		pc += 2;
 		uint16 frame = scriptReadStringIndex(pc);
 		pc += 2;
@@ -162,7 +163,8 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	}
 
 	case 0x09: {
-		actorSetFrame((int16)scriptReadWord(pc));
+		int16 frame = scriptReadWord(pc);
+		actorSetFrame(frame);
 		pc += 2;
 		if (!_usesAnimFile && _videoMode == 2)
 			videoSetResolution();
@@ -973,7 +975,8 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	}
 
 	case 0x53: {
-		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
+		uint16 actorSlot = scriptReadWord(pc);
+		Actor *target = actorResolve(actorSlot, _currentActor);
 		uint16 frame = scriptReadStringIndex(pc + 2);
 		pc += 4;
 		if (!target)


Commit: 9346038149bc5ff28e06d179ee71640ae95db8eb
    https://github.com/scummvm/scummvm/commit/9346038149bc5ff28e06d179ee71640ae95db8eb
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Add option to skip intro

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/detection.h
    engines/comfy/detection_tables.h
    engines/comfy/game.cpp
    engines/comfy/metaengine.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index bb99e74171e..2802c47b619 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -124,7 +124,7 @@ Common::Error ComfyEngine::gameInit() {
 		ConfMan.flushToDisk();
 	}
 
-	if (iniGetGameDataPath(0)) {
+	if (!_introDirectory.empty() && !ConfMan.getBool("skip_intro") && iniGetGameDataPath(0)) {
 		sceneRun(_currentScene, false, true);
 		if (shouldQuit()) {
 			gameShutdown();
diff --git a/engines/comfy/detection.h b/engines/comfy/detection.h
index 4baa9c89c99..cf3799dd30e 100644
--- a/engines/comfy/detection.h
+++ b/engines/comfy/detection.h
@@ -57,6 +57,7 @@ extern const PlainGameDescriptor comfyGames[];
 extern const ComfyGameDescription gameDescriptions[];
 
 #define GAMEOPTION_FORCE_LANGUAGE_SETUP GUIO_GAMEOPTIONS1
+#define GAMEOPTION_SKIP_INTRO           GUIO_GAMEOPTIONS2
 
 } // End of namespace Comfy
 
diff --git a/engines/comfy/detection_tables.h b/engines/comfy/detection_tables.h
index 96231033a6a..1146d9769c8 100644
--- a/engines/comfy/detection_tables.h
+++ b/engines/comfy/detection_tables.h
@@ -44,7 +44,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		1,
 		0
@@ -62,7 +62,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		3,
 		0
@@ -78,7 +78,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		2,
 		COMFY_SCRIPT_OPCODE_31
@@ -93,7 +93,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		2,
 		COMFY_SCRIPT_OPCODE_31 | COMFY_SCRIPT_OPCODE_33
@@ -108,7 +108,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		1,
 		0
@@ -123,7 +123,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		2,
 		0
@@ -139,7 +139,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		3,
 		0
@@ -155,7 +155,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		3,
 		0
@@ -171,7 +171,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		3,
 		0
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index 30916c37948..d0c6e595c93 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -107,6 +107,7 @@ void ComfyEngine::gameConfigInit() {
 	ConfMan.registerDefault("comfy_language", 2);
 	ConfMan.registerDefault("comfy_language_chosen", false);
 	ConfMan.registerDefault("force_language_setup", false);
+	ConfMan.registerDefault("skip_intro", false);
 	ConfMan.registerDefault("comfy_screen_update_interleaved", false);
 	ConfMan.registerDefault("comfy_input_device", 0);
 }
diff --git a/engines/comfy/metaengine.cpp b/engines/comfy/metaengine.cpp
index e3782fc1da6..89fc8fac483 100644
--- a/engines/comfy/metaengine.cpp
+++ b/engines/comfy/metaengine.cpp
@@ -42,6 +42,17 @@ static const ADExtraGuiOptionsMap optionsList[] = {
 			0
 		}
 	},
+	{
+		GAMEOPTION_SKIP_INTRO,
+		{
+			_s("Skip intro"),
+			_s("Skip the intro sequence which precedes the interactive movie"),
+			"skip_intro",
+			false,
+			0,
+			0
+		}
+	},
 	AD_EXTRA_GUI_OPTIONS_TERMINATOR
 };
 


Commit: 4c9415a198461c9a1755eebc8b927a5ed9b698a0
    https://github.com/scummvm/scummvm/commit/4c9415a198461c9a1755eebc8b927a5ed9b698a0
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Fix gfx regression in older games

Changed paths:
    engines/comfy/anim_file.cpp


diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
index 1a36f9152d4..6ee7c200054 100644
--- a/engines/comfy/anim_file.cpp
+++ b/engines/comfy/anim_file.cpp
@@ -181,9 +181,6 @@ void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 ac
 	_animVocDeltaA = 0;
 	_animActive = true;
 	_animFrameReady = false;
-	debug(5, "COMFY ANM: load index=%u offset=%u size=%u width=%u height=%u vocClock=%u",
-		animIndex, offset, (uint)_animFileData.size(), READ_LE_UINT16(_animFrameHeader + 10),
-		READ_LE_UINT16(_animFrameHeader + 12), _animVocClockHz);
 
 	if (actorSceneHandle < _sceneHandles.size()) {
 		Actor *actor = actorGetPtr(sceneGetHandle(actorSceneHandle));
@@ -396,9 +393,6 @@ void ComfyEngine::animFileTickCommands() {
 		uint32 rawCommandSize = _animPantherFormat ? READ_LE_UINT32(header + 2) : READ_LE_UINT16(header + 2);
 		int32 signedCommandSize = _animPantherFormat ? (int32)rawCommandSize : (int32)(uint16)rawCommandSize;
 		uint32 commandSize = rawCommandSize;
-		debug(5, "COMFY ANM: index=%u position=%u command=0x%04X size=%u signedSize=%d argument=%u",
-			_animCurrentIndex, _animPosition, command, commandSize, signedCommandSize,
-			_animPantherFormat ? READ_LE_UINT16(header + 6) : 0);
 
 		// WPANTHER compares the FR command size as signed. Some Panther data uses
 		// negative sizes here; this marks the frame ready without decoding payload.
@@ -460,10 +454,15 @@ void ComfyEngine::animFileTickCommands() {
 			memcpy(_animFrameCommandData, payload, MIN<uint32>(payloadSize, sizeof(_animFrameCommandData)));
 		} else if (command == kAnimCommandFrame) {
 			if (commandSize > 8) {
-				if (_animPantherFormat)
+				if (_animPantherFormat) {
 					animDecodePanther(payload, payloadSize);
-				else
+				} else {
 					animDecompressRle(payload, payloadSize, &_animFrameBuffer[0], _animFrameBuffer.size());
+					if (_framebufPtr) {
+						memcpy(_framebufPtr, &_animFrameBuffer[0], COMFY_ANMFRAME_BYTES);
+						renderSetDirty();
+					}
+				}
 			}
 
 			frameReady = true;


Commit: e322abce3c80adda09478dc727aa540f640b5a15
    https://github.com/scummvm/scummvm/commit/e322abce3c80adda09478dc727aa540f640b5a15
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Remove unused file

Changed paths:
  R engines/comfy/script_ops.cpp
    engines/comfy/module.mk


diff --git a/engines/comfy/module.mk b/engines/comfy/module.mk
index 2914102c847..f40e64c98e8 100644
--- a/engines/comfy/module.mk
+++ b/engines/comfy/module.mk
@@ -16,7 +16,6 @@ MODULE_OBJS = \
 	palette.o \
 	scene.o \
 	script.o \
-	script_ops.o \
 	script_vm.o \
 	sound.o \
 	timer.o \
diff --git a/engines/comfy/script_ops.cpp b/engines/comfy/script_ops.cpp
deleted file mode 100644
index 409cdeb90bd..00000000000
--- a/engines/comfy/script_ops.cpp
+++ /dev/null
@@ -1,25 +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/>.
- *
- */
-
-namespace Comfy {
-
-
-} // End of namespace Comfy


Commit: 3750a8962b66e22fd3f165d987c4f012aa20b3dc
    https://github.com/scummvm/scummvm/commit/3750a8962b66e22fd3f165d987c4f012aa20b3dc
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Fix blocked animations and missing sounds

Changed paths:
    engines/comfy/sound.cpp


diff --git a/engines/comfy/sound.cpp b/engines/comfy/sound.cpp
index 3e14bddbf59..26fc81b7355 100644
--- a/engines/comfy/sound.cpp
+++ b/engines/comfy/sound.cpp
@@ -29,6 +29,7 @@
 
 #define COMFY_ANM_COMMAND_END 0x2145
 #define COMFY_ANM_COMMAND_STORE_FRAME_BYTES 0x4356
+#define COMFY_ANM_COMMAND_FRAME 0x5246
 
 namespace Comfy {
 
@@ -486,9 +487,9 @@ private:
 	}
 
 	void pushCue(uint16 value) {
-		if (_cues.size() >= COMFY_SOUND_PITCH_COUNT_LIMIT)
-			return;
-
+		// The original keeps at most 0x13 pending pitch entries, but consumes them
+		// while refilling wave buffers. This host decoder stores the full cue
+		// timeline, so applying that pending-entry limit here would drop later cues.
 		ComfyEngine::SoundCue cue;
 		cue.value = value;
 		cue.streamPosition = _streamPosition;
@@ -737,7 +738,14 @@ bool ComfyEngine::soundPrepareDecoderState(uint16 index) {
 
 				byte *header = &_animFileData[position];
 				uint16 command = READ_LE_UINT16(header);
-				uint32 commandSize = _animPantherFormat ? READ_LE_UINT32(header + 2) : READ_LE_UINT16(header + 2);
+				uint32 rawCommandSize = _animPantherFormat ? READ_LE_UINT32(header + 2) : READ_LE_UINT16(header + 2);
+				int32 signedCommandSize = _animPantherFormat ? (int32)rawCommandSize : (int32)(uint16)rawCommandSize;
+				uint32 commandSize = rawCommandSize;
+				if (_animPantherFormat && command == COMFY_ANM_COMMAND_FRAME && signedCommandSize <= (int32)headerSize) {
+					position += headerSize;
+					continue;
+				}
+
 				if (commandSize < headerSize || commandSize > _animFileData.size() - position)
 					return false;
 


Commit: 7639c8321ed20d1b11e7b2e8ac3a45d0a84711a3
    https://github.com/scummvm/scummvm/commit/7639c8321ed20d1b11e7b2e8ac3a45d0a84711a3
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Add actor debugger and refactor ImGui code

Changed paths:
  A engines/comfy/debug.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/comfy_keyboard_ui.cpp
    engines/comfy/module.mk
    engines/comfy/scene.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 2802c47b619..e4bc9e0fc39 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -35,6 +35,38 @@ namespace Comfy {
 
 ComfyEngine *g_engine;
 
+#ifdef USE_IMGUI
+ImGuiState *_state = nullptr;
+
+void onImGuiInit() {
+	_state = new ImGuiState();
+	_state->_engine = (ComfyEngine *)g_engine;
+}
+
+void onImGuiRender() {
+	if (!_state || !_state->_engine || _state->_engine->shouldQuit())
+		return;
+
+	if (!_state->_engine->_keyboardUiInitialized)
+		return;
+
+	bool actorDebugEnabled = debugChannelSet(-1, kDebugImGui);
+	if (actorDebugEnabled)
+		_state->_engine->drawActorDebugUi(&_state->_actorDebugVisible);
+	else
+		_state->_actorDebugVisible = false;
+
+	drawComfyKeyboardUi(actorDebugEnabled);
+}
+
+void onImGuiCleanup() {
+	cleanupComfyKeyboardUi();
+
+	delete _state;
+	_state = nullptr;
+}
+#endif
+
 ComfyEngine::ComfyEngine(OSystem *syst, const ComfyGameDescription *gameDesc) : Engine(syst),
 	_game(gameDesc), _engineVersion(gameDesc->version),
 	_randomSource("Comfy"),
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 9308d7eb253..90a0894b5bd 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -97,13 +97,30 @@ class QueuingAudioStream;
 
 namespace Comfy {
 
+class ComfyEngine;
 class MidiPlyrDriver;
 struct SoundDecoderState;
 
 #ifdef USE_IMGUI
+typedef struct ImGuiState {
+	ComfyEngine *_engine = nullptr;
+	uint32 _activeMask = 0;
+	uint32 _latchedMask = 0;
+	uint32 _holdMask = 0;
+	uint16 _actorDebugLastScene = 0xFFFF;
+	uint32 _actorDebugLastSceneGeneration = 0xFFFFFFFF;
+	bool _visible = true;
+	bool _actorDebugVisible = false;
+	bool _actorDebugTreeView = false;
+} ImGuiState;
+
+extern ImGuiState *_state;
+
 void onImGuiInit();
 void onImGuiRender();
 void onImGuiCleanup();
+void drawComfyKeyboardUi(bool actorDebugEnabled);
+void cleanupComfyKeyboardUi();
 #endif
 
 class ComfyEngine : public Engine {
@@ -550,6 +567,7 @@ private:
 	uint16 _currentActor = 0;
 	uint16 _currentScene = 0;
 	uint16 _pendingScene = 0;
+	uint32 _debugSceneGeneration = 0;
 	uint16 _musicEventMask = 0;
 	byte _musicEventFlag = 0;
 	bool _musicEnabled = false;
@@ -942,6 +960,10 @@ private:
 	void soundUnpackState(byte *state);
 	void soundPlayEntry(uint16 index);
 	void soundAdvanceTick();
+#ifdef USE_IMGUI
+	bool debugScriptHasRange(uint32 pc, uint32 width);
+	uint16 debugScriptReadWord(uint32 pc);
+#endif
 
 protected:
 	// Engine APIs
@@ -952,6 +974,9 @@ public:
 	~ComfyEngine() override;
 
 	void setToyKeyboardState(uint32 activeMask, uint32 latchedMask, uint32 holdMask);
+#ifdef USE_IMGUI
+	void drawActorDebugUi(bool *visible);
+#endif
 
 	/**
 	 * Returns the game Id
diff --git a/engines/comfy/comfy_keyboard_ui.cpp b/engines/comfy/comfy_keyboard_ui.cpp
index 37a13961b35..820fa5194d2 100644
--- a/engines/comfy/comfy_keyboard_ui.cpp
+++ b/engines/comfy/comfy_keyboard_ui.cpp
@@ -29,16 +29,6 @@ namespace Comfy {
 
 #ifdef USE_IMGUI
 
-typedef struct ImGuiState {
-	ComfyEngine *_engine = nullptr;
-	uint32 _activeMask = 0;
-	uint32 _latchedMask = 0;
-	uint32 _holdMask = 0;
-	bool _visible = true;
-} ImGuiState;
-
-ImGuiState *_state = nullptr;
-
 static ImU32 keyboardColor(byte red, byte green, byte blue) {
 	return IM_COL32(red, green, blue, 255);
 }
@@ -129,15 +119,7 @@ static void keyboardDrawToggle(const char *label, uint bit, ImVec2 size, ImU32 o
 	}
 }
 
-void onImGuiInit() {
-	_state = new ImGuiState();
-	_state->_engine = (ComfyEngine *)g_engine;
-}
-
-void onImGuiRender() {
-	if (!_state || !_state->_engine || _state->_engine->shouldQuit())
-		return;
-
+void drawComfyKeyboardUi(bool actorDebugEnabled) {
 	if (!_state->_engine->_keyboardUiInitialized)
 		return;
 
@@ -153,6 +135,9 @@ void onImGuiRender() {
 	ImGui::SetNextWindowSize(ImVec2(740, 440), ImGuiCond_FirstUseEver);
 
 	if (ImGui::Begin("Comfy Keyboard", &_state->_visible, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoResize)) {
+		if (actorDebugEnabled)
+			ImGui::Checkbox("Actor debug", &_state->_actorDebugVisible);
+
 		ImU32 shell = keyboardColor(232, 228, 208);
 		ImU32 red = keyboardColor(199, 31, 27);
 		ImU32 handset = keyboardColor(211, 48, 38);
@@ -238,12 +223,9 @@ void onImGuiRender() {
 	_state->_latchedMask = 0;
 }
 
-void onImGuiCleanup() {
+void cleanupComfyKeyboardUi() {
 	if (_state && _state->_engine)
 		_state->_engine->setToyKeyboardState(0, 0, 0);
-
-	delete _state;
-	_state = nullptr;
 }
 
 #endif // USE_IMGUI
diff --git a/engines/comfy/debug.cpp b/engines/comfy/debug.cpp
new file mode 100644
index 00000000000..f5a36dad6b9
--- /dev/null
+++ b/engines/comfy/debug.cpp
@@ -0,0 +1,529 @@
+/* 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 "comfy/comfy.h"
+
+#include "common/endian.h"
+
+#ifdef USE_IMGUI
+#include "backends/imgui/imgui.h"
+#endif
+
+namespace Comfy {
+
+#ifdef USE_IMGUI
+
+static void debugIncludeMapPoint(int16 &mapLeft, int16 &mapTop, int16 &mapRight, int16 &mapBottom, int16 x, int16 y) {
+	mapLeft = MIN(mapLeft, x);
+	mapTop = MIN(mapTop, y);
+	mapRight = MAX(mapRight, x);
+	mapBottom = MAX(mapBottom, y);
+}
+
+static void debugIncludeMapRect(int16 &mapLeft, int16 &mapTop, int16 &mapRight, int16 &mapBottom,
+		int16 left, int16 top, int16 right, int16 bottom) {
+	debugIncludeMapPoint(mapLeft, mapTop, mapRight, mapBottom, left, top);
+	debugIncludeMapPoint(mapLeft, mapTop, mapRight, mapBottom, right, bottom);
+}
+
+static ImVec2 debugMapPointToCanvas(const ImVec2 &canvasPos, int16 mapLeft, int16 mapTop,
+		float scale, float margin, int16 x, int16 y) {
+	return ImVec2(canvasPos.x + ((float)x - mapLeft) * scale + margin,
+		canvasPos.y + ((float)y - mapTop) * scale + margin);
+}
+
+bool ComfyEngine::debugScriptHasRange(uint32 pc, uint32 width) {
+	uint32 tileOffset = pc % COMFY_TILE_SIZE;
+	uint32 tileBase = pc - tileOffset;
+	uint32 tileSize = tileBase < _picDataSize ? MIN<uint32>(COMFY_TILE_SIZE, _picDataSize - tileBase) : 0;
+
+	return tileBase <= _comfyObjData.size() && tileSize <= _comfyObjData.size() - tileBase &&
+		tileOffset <= tileSize && width <= tileSize - tileOffset;
+}
+
+uint16 ComfyEngine::debugScriptReadWord(uint32 pc) {
+	return debugScriptHasRange(pc, 2) ? READ_LE_UINT16(&_comfyObjData[pc]) : (uint16)0;
+}
+
+void ComfyEngine::drawActorDebugUi(bool *visible) {
+	if (!visible || !*visible)
+		return;
+
+	ImGui::SetNextWindowPos(ImVec2(760, 8), ImGuiCond_FirstUseEver);
+	ImGui::SetNextWindowSize(ImVec2(900, 760), ImGuiCond_FirstUseEver);
+	if (!ImGui::Begin("Comfy Actors", visible)) {
+		ImGui::End();
+		return;
+	}
+
+	ImGui::Text("Game: %s  version: %u  actors: %u", getGameId().c_str(), _engineVersion, (uint)_actors.size());
+	ImGui::TextDisabled("Tip: disable Visible/Active to isolate a problematic actor.");
+	bool centerFramebuffer = ImGui::Button("Center framebuffer");
+	ImGui::SameLine();
+	ImGui::Checkbox("Tree view", &_state->_actorDebugTreeView);
+	if (_state->_actorDebugLastScene != _currentScene ||
+			_state->_actorDebugLastSceneGeneration != _debugSceneGeneration) {
+		centerFramebuffer = true;
+		_state->_actorDebugLastScene = _currentScene;
+		_state->_actorDebugLastSceneGeneration = _debugSceneGeneration;
+	}
+	ImGui::Separator();
+
+	ImGui::BeginChild("comfy_actor_map", ImVec2(0, 320), true, ImGuiWindowFlags_HorizontalScrollbar);
+	ImVec2 canvasPos = ImGui::GetCursorScreenPos();
+	int16 mapLeft = 0;
+	int16 mapTop = 0;
+	int16 mapRight = _logicalScreenWidth;
+	int16 mapBottom = _logicalScreenHeight;
+
+	for (uint i = 0; i < _actors.size(); i++) {
+		Actor &actor = _actors[i];
+		uint16 sceneHandle = actorReadU16(actor, kActorSceneHandle);
+		if (!sceneHandle && i != 0)
+			continue;
+
+		int32 xFixed = (int32)actorReadU32(actor, kActorXFixed);
+		int32 yFixed = (int32)actorReadU32(actor, kActorYFixed);
+		uint16 parent = actorReadU16(actor, kActorParent);
+		uint guard = 0;
+		while (parent && parent < _actors.size() && guard++ < COMFY_ACTOR_COUNT) {
+			Actor *parentActor = actorGetPtr(parent);
+			if (!parentActor)
+				break;
+
+			xFixed += (int32)actorReadU32(*parentActor, kActorXFixed);
+			yFixed += (int32)actorReadU32(*parentActor, kActorYFixed);
+			parent = actorReadU16(*parentActor, kActorParent);
+		}
+
+		int16 x = (int16)(xFixed >> 12);
+		int16 y = (int16)(yFixed >> 12);
+		debugIncludeMapPoint(mapLeft, mapTop, mapRight, mapBottom, x, y);
+
+		uint32 selector = actorReadU32(actor, kActorSpriteSelector);
+		if (selector && !(selector & 0xFF000000) && selector != 0x00FFFFFF &&
+				selector < _spriteResources.size() && _spriteResources[selector].loaded) {
+			SpriteResource &sprite = _spriteResources[selector];
+			debugIncludeMapRect(mapLeft, mapTop, mapRight, mapBottom,
+				x - sprite.header.hotspotX, y - sprite.header.hotspotY,
+				x - sprite.header.hotspotX + sprite.header.width,
+				y - sprite.header.hotspotY + sprite.header.height);
+		} else if (selector & 0xFF000000) {
+			uint32 pc = selector & 0x00FFFFFF;
+			int16 wordsLeft = (int16)(debugScriptReadWord(pc) - 1);
+			pc += 2;
+			while (wordsLeft > 0 && debugScriptHasRange(pc, 6)) {
+				uint16 rawSpriteId = debugScriptReadWord(pc);
+				int16 dx = debugScriptReadWord(pc + 2);
+				int16 dy = debugScriptReadWord(pc + 4);
+				pc += 6;
+				wordsLeft -= 3;
+				uint16 spriteId = rawSpriteId;
+				if (spriteId & 0x8000) {
+					if (!debugScriptHasRange(pc, 4))
+						break;
+
+					wordsLeft -= 2;
+					uint16 key = debugScriptReadWord(pc);
+					pc += 2;
+					if (keyBitTest(key))
+						spriteId &= 0x7FFF;
+					else
+						spriteId = debugScriptReadWord(pc);
+
+					pc += 2;
+				}
+
+				int16 limbX = x + dx;
+				int16 limbY = y + dy;
+				debugIncludeMapPoint(mapLeft, mapTop, mapRight, mapBottom, limbX, limbY);
+				if (spriteId && spriteId < _spriteResources.size() && _spriteResources[spriteId].loaded) {
+					SpriteResource &sprite = _spriteResources[spriteId];
+					debugIncludeMapRect(mapLeft, mapTop, mapRight, mapBottom,
+						limbX - sprite.header.hotspotX, limbY - sprite.header.hotspotY,
+						limbX - sprite.header.hotspotX + sprite.header.width,
+						limbY - sprite.header.hotspotY + sprite.header.height);
+				}
+			}
+		}
+	}
+
+	const float margin = 32.0F;
+	float scale = 1.0F;
+	ImVec2 canvasSize((float)(mapRight - mapLeft) * scale + margin * 2.0F,
+		(float)(mapBottom - mapTop) * scale + margin * 2.0F);
+
+	ImDrawList *drawList = ImGui::GetWindowDrawList();
+	drawList->PushClipRect(canvasPos, ImVec2(canvasPos.x + canvasSize.x, canvasPos.y + canvasSize.y), true);
+	drawList->AddRectFilled(canvasPos, ImVec2(canvasPos.x + canvasSize.x, canvasPos.y + canvasSize.y), IM_COL32(18, 20, 24, 230));
+	drawList->AddRect(canvasPos, ImVec2(canvasPos.x + canvasSize.x, canvasPos.y + canvasSize.y), IM_COL32(180, 180, 180, 180));
+	ImVec2 screenTopLeft = debugMapPointToCanvas(canvasPos, mapLeft, mapTop, scale, margin, 0, 0);
+	ImVec2 screenBottomRight = debugMapPointToCanvas(canvasPos, mapLeft, mapTop, scale, margin,
+		_logicalScreenWidth, _logicalScreenHeight);
+	drawList->AddRectFilled(screenTopLeft, screenBottomRight, IM_COL32(38, 43, 54, 220));
+	drawList->AddRect(screenTopLeft, screenBottomRight, IM_COL32(110, 170, 240, 230));
+	for (uint i = 0; i < _actors.size(); i++) {
+		Actor &actor = _actors[i];
+		uint16 sceneHandle = actorReadU16(actor, kActorSceneHandle);
+		if (!sceneHandle && i != 0)
+			continue;
+
+		int32 xFixed = (int32)actorReadU32(actor, kActorXFixed);
+		int32 yFixed = (int32)actorReadU32(actor, kActorYFixed);
+		uint16 parent = actorReadU16(actor, kActorParent);
+		uint guard = 0;
+		while (parent && parent < _actors.size() && guard++ < COMFY_ACTOR_COUNT) {
+			Actor *parentActor = actorGetPtr(parent);
+			if (!parentActor)
+				break;
+
+			xFixed += (int32)actorReadU32(*parentActor, kActorXFixed);
+			yFixed += (int32)actorReadU32(*parentActor, kActorYFixed);
+			parent = actorReadU16(*parentActor, kActorParent);
+		}
+
+		int16 x = (int16)(xFixed >> 12);
+		int16 y = (int16)(yFixed >> 12);
+		bool visibleActor = actorReadU8(actor, kActorVisible) != 0;
+		bool activeActor = actorReadU8(actor, kActorActive) != 0;
+		ImU32 color = visibleActor ? (activeActor ? IM_COL32(82, 220, 120, 230) : IM_COL32(238, 185, 74, 230)) :
+			IM_COL32(120, 120, 120, 170);
+
+		ImVec2 point = debugMapPointToCanvas(canvasPos, mapLeft, mapTop, scale, margin, x, y);
+		drawList->AddCircleFilled(point, 3.0F, color);
+
+		char actorLabel[16];
+		snprintf(actorLabel, sizeof(actorLabel), "%u", i);
+		drawList->AddText(ImVec2(point.x + 4.0F, point.y - 4.0F), color, actorLabel);
+
+		uint32 selector = actorReadU32(actor, kActorSpriteSelector);
+		if (visibleActor && selector && !(selector & 0xFF000000) && selector != 0x00FFFFFF &&
+				selector < _spriteResources.size() && _spriteResources[selector].loaded) {
+			SpriteResource &sprite = _spriteResources[selector];
+			ImVec2 topLeft = debugMapPointToCanvas(canvasPos, mapLeft, mapTop, scale, margin,
+				x - sprite.header.hotspotX, y - sprite.header.hotspotY);
+			ImVec2 bottomRight = debugMapPointToCanvas(canvasPos, mapLeft, mapTop, scale, margin,
+				x - sprite.header.hotspotX + sprite.header.width,
+				y - sprite.header.hotspotY + sprite.header.height);
+			drawList->AddRect(topLeft, bottomRight, color);
+		} else if (selector & 0xFF000000) {
+			uint32 pc = selector & 0x00FFFFFF;
+			int16 wordsLeft = (int16)(debugScriptReadWord(pc) - 1);
+			pc += 2;
+			while (wordsLeft > 0 && debugScriptHasRange(pc, 6)) {
+				uint16 rawSpriteId = debugScriptReadWord(pc);
+				int16 dx = debugScriptReadWord(pc + 2);
+				int16 dy = debugScriptReadWord(pc + 4);
+				pc += 6;
+				wordsLeft -= 3;
+				uint16 spriteId = rawSpriteId;
+				if (spriteId & 0x8000) {
+					if (!debugScriptHasRange(pc, 4))
+						break;
+
+					wordsLeft -= 2;
+					uint16 key = debugScriptReadWord(pc);
+					pc += 2;
+					if (keyBitTest(key))
+						spriteId &= 0x7FFF;
+					else
+						spriteId = debugScriptReadWord(pc);
+
+					pc += 2;
+				}
+
+				int16 limbX = x + dx;
+				int16 limbY = y + dy;
+				ImVec2 limbPoint = debugMapPointToCanvas(canvasPos, mapLeft, mapTop, scale, margin, limbX, limbY);
+				drawList->AddCircleFilled(limbPoint, 2.0F, IM_COL32(120, 205, 255, 220));
+				if (spriteId && spriteId < _spriteResources.size() && _spriteResources[spriteId].loaded) {
+					SpriteResource &sprite = _spriteResources[spriteId];
+					ImVec2 topLeft = debugMapPointToCanvas(canvasPos, mapLeft, mapTop, scale, margin,
+						limbX - sprite.header.hotspotX, limbY - sprite.header.hotspotY);
+					ImVec2 bottomRight = debugMapPointToCanvas(canvasPos, mapLeft, mapTop, scale, margin,
+						limbX - sprite.header.hotspotX + sprite.header.width,
+						limbY - sprite.header.hotspotY + sprite.header.height);
+					drawList->AddRect(topLeft, bottomRight, IM_COL32(120, 205, 255, 180));
+				}
+			}
+		}
+	}
+
+	ImGui::Dummy(canvasSize);
+	if (centerFramebuffer) {
+		ImVec2 childSize = ImGui::GetWindowSize();
+		float targetX = ((float)-mapLeft + (float)_logicalScreenWidth / 2.0F) * scale + margin - childSize.x / 2.0F;
+		float targetY = ((float)-mapTop + (float)_logicalScreenHeight / 2.0F) * scale + margin - childSize.y / 2.0F;
+		ImGui::SetScrollX(MAX(0.0F, targetX));
+		ImGui::SetScrollY(MAX(0.0F, targetY));
+	}
+	drawList->PopClipRect();
+	ImGui::EndChild();
+	ImGui::Separator();
+
+	ImGui::BeginChild("comfy_actor_table_child", ImVec2(0, 0), true, ImGuiWindowFlags_HorizontalScrollbar);
+	if (_state->_actorDebugTreeView) {
+		bool visited[COMFY_ACTOR_COUNT];
+		memset(visited, 0, sizeof(visited));
+		uint16 actorStack[COMFY_ACTOR_COUNT * 2];
+		uint stackCount = 0;
+
+		if (_actors.size()) {
+			actorStack[stackCount] = 0;
+			stackCount++;
+			visited[0] = true;
+		}
+
+		while (stackCount) {
+			stackCount--;
+			uint16 actorIndex = actorStack[stackCount];
+			if (actorIndex == 0xFFFF) {
+				ImGui::TreePop();
+				continue;
+			}
+
+			if (actorIndex >= _actors.size())
+				continue;
+
+			Actor &actor = _actors[actorIndex];
+			uint16 sceneHandle = actorReadU16(actor, kActorSceneHandle);
+			if (!sceneHandle && actorIndex != 0)
+				continue;
+
+			uint16 children[COMFY_ACTOR_COUNT];
+			uint childCount = 0;
+			uint16 child = actorReadU16(actor, kActorChildHead);
+			uint guard = 0;
+			while (child && child < _actors.size() && child < COMFY_ACTOR_COUNT &&
+					childCount < COMFY_ACTOR_COUNT && guard++ < COMFY_ACTOR_COUNT) {
+				if (!visited[child]) {
+					children[childCount] = child;
+					childCount++;
+					visited[child] = true;
+				}
+
+				Actor *childActor = actorGetPtr(child);
+				if (!childActor)
+					break;
+
+				child = actorReadU16(*childActor, kActorSiblingHead);
+			}
+
+			uint32 selector = actorReadU32(actor, kActorSpriteSelector);
+			int32 xFixed = (int32)actorReadU32(actor, kActorXFixed);
+			int32 yFixed = (int32)actorReadU32(actor, kActorYFixed);
+			uint16 parent = actorReadU16(actor, kActorParent);
+			guard = 0;
+			while (parent && parent < _actors.size() && guard++ < COMFY_ACTOR_COUNT) {
+				Actor *parentActor = actorGetPtr(parent);
+				if (!parentActor)
+					break;
+
+				xFixed += (int32)actorReadU32(*parentActor, kActorXFixed);
+				yFixed += (int32)actorReadU32(*parentActor, kActorYFixed);
+				parent = actorReadU16(*parentActor, kActorParent);
+			}
+
+			int16 x = (int16)(xFixed >> 12);
+			int16 y = (int16)(yFixed >> 12);
+			bool visibleActor = actorReadU8(actor, kActorVisible) != 0;
+			bool activeActor = actorReadU8(actor, kActorActive) != 0;
+			ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanAvailWidth;
+			if (!childCount)
+				flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen;
+
+			ImGui::PushID((int)actorIndex);
+			bool open = ImGui::TreeNodeEx("actor", flags, "%u", actorIndex);
+
+			ImGui::SameLine(120.0F);
+			ImGui::Text("scene=%u pos=%d,%d selector=0x%08X move=%d",
+				sceneHandle, x, y, selector, (int16)actorReadU16(actor, kActorMoveTicks));
+
+			ImGui::SameLine(520.0F);
+			if (ImGui::Checkbox("Visible", &visibleActor)) {
+				actorWriteU8(actor, kActorVisible, visibleActor ? 1 : 0);
+				renderSetDirty();
+			}
+			ImGui::SameLine();
+			if (ImGui::Checkbox("Active", &activeActor))
+				actorWriteU8(actor, kActorActive, activeActor ? 1 : 0);
+			ImGui::PopID();
+
+			if (open && childCount) {
+				if (stackCount < ARRAYSIZE(actorStack)) {
+					actorStack[stackCount] = 0xFFFF;
+					stackCount++;
+				}
+
+				while (childCount && stackCount < ARRAYSIZE(actorStack)) {
+					childCount--;
+					actorStack[stackCount] = children[childCount];
+					stackCount++;
+				}
+			}
+
+			if (!stackCount) {
+				for (uint i = 0; i < _actors.size() && i < COMFY_ACTOR_COUNT &&
+						stackCount < ARRAYSIZE(actorStack); i++) {
+					Actor &orphanActor = _actors[i];
+					if (visited[i] || (!actorReadU16(orphanActor, kActorSceneHandle) && i != 0))
+						continue;
+
+					actorStack[stackCount] = i;
+					stackCount++;
+					visited[i] = true;
+					break;
+				}
+			}
+		}
+	} else if (ImGui::BeginTable("comfy_actor_table", 10, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg |
+			ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY | ImGuiTableFlags_ScrollX, ImVec2(0, 0))) {
+		ImGui::TableSetupColumn("#", ImGuiTableColumnFlags_WidthFixed, 32.0F);
+		ImGui::TableSetupColumn("Scene", ImGuiTableColumnFlags_WidthFixed, 48.0F);
+		ImGui::TableSetupColumn("Parent", ImGuiTableColumnFlags_WidthFixed, 52.0F);
+		ImGui::TableSetupColumn("Abs X", ImGuiTableColumnFlags_WidthFixed, 48.0F);
+		ImGui::TableSetupColumn("Abs Y", ImGuiTableColumnFlags_WidthFixed, 48.0F);
+		ImGui::TableSetupColumn("Selector", ImGuiTableColumnFlags_WidthFixed, 88.0F);
+		ImGui::TableSetupColumn("PC", ImGuiTableColumnFlags_WidthFixed, 80.0F);
+		ImGui::TableSetupColumn("Visible", ImGuiTableColumnFlags_WidthFixed, 58.0F);
+		ImGui::TableSetupColumn("Active", ImGuiTableColumnFlags_WidthFixed, 52.0F);
+		ImGui::TableSetupColumn("Move", ImGuiTableColumnFlags_WidthFixed, 44.0F);
+		ImGui::TableHeadersRow();
+
+		for (uint i = 0; i < _actors.size(); i++) {
+			Actor &actor = _actors[i];
+			uint16 sceneHandle = actorReadU16(actor, kActorSceneHandle);
+			if (!sceneHandle && i != 0)
+				continue;
+
+			uint32 selector = actorReadU32(actor, kActorSpriteSelector);
+			int32 xFixed = (int32)actorReadU32(actor, kActorXFixed);
+			int32 yFixed = (int32)actorReadU32(actor, kActorYFixed);
+			uint16 parent = actorReadU16(actor, kActorParent);
+			uint guard = 0;
+			while (parent && parent < _actors.size() && guard++ < COMFY_ACTOR_COUNT) {
+				Actor *parentActor = actorGetPtr(parent);
+				if (!parentActor)
+					break;
+
+				xFixed += (int32)actorReadU32(*parentActor, kActorXFixed);
+				yFixed += (int32)actorReadU32(*parentActor, kActorYFixed);
+				parent = actorReadU16(*parentActor, kActorParent);
+			}
+
+			int16 x = (int16)(xFixed >> 12);
+			int16 y = (int16)(yFixed >> 12);
+			bool visibleActor = actorReadU8(actor, kActorVisible) != 0;
+			bool activeActor = actorReadU8(actor, kActorActive) != 0;
+
+			ImGui::TableNextRow();
+			ImGui::TableSetColumnIndex(0);
+			bool open = ImGui::TreeNodeEx((void *)(uintptr)i, ImGuiTreeNodeFlags_SpanFullWidth, "%u", i);
+			ImGui::TableSetColumnIndex(1);
+			ImGui::Text("%u", sceneHandle);
+			ImGui::TableSetColumnIndex(2);
+			ImGui::Text("%u", actorReadU16(actor, kActorParent));
+			ImGui::TableSetColumnIndex(3);
+			ImGui::Text("%d", x);
+			ImGui::TableSetColumnIndex(4);
+			ImGui::Text("%d", y);
+			ImGui::TableSetColumnIndex(5);
+			ImGui::Text("0x%08X", selector);
+			ImGui::TableSetColumnIndex(6);
+			ImGui::Text("0x%08X", actorReadU32(actor, kActorCurrentPc));
+			ImGui::TableSetColumnIndex(7);
+			ImGui::PushID((int)i * 2);
+			if (ImGui::Checkbox("", &visibleActor)) {
+				actorWriteU8(actor, kActorVisible, visibleActor ? 1 : 0);
+				renderSetDirty();
+			}
+			ImGui::PopID();
+			ImGui::TableSetColumnIndex(8);
+			ImGui::PushID((int)i * 2 + 1);
+			if (ImGui::Checkbox("", &activeActor))
+				actorWriteU8(actor, kActorActive, activeActor ? 1 : 0);
+			ImGui::PopID();
+			ImGui::TableSetColumnIndex(9);
+			ImGui::Text("%d", (int16)actorReadU16(actor, kActorMoveTicks));
+
+			if (open) {
+				ImGui::TableNextRow();
+				ImGui::TableSetColumnIndex(1);
+				ImGui::Text("links prev=%u next=%u child=%u sibling=%u tail=%u",
+					actorReadU16(actor, kActorPrevLink), actorReadU16(actor, kActorNextLink),
+					actorReadU16(actor, kActorChildHead), actorReadU16(actor, kActorSiblingHead),
+					actorReadU16(actor, kActorChildTail));
+				ImGui::TableNextRow();
+				ImGui::TableSetColumnIndex(1);
+				ImGui::Text("local fixed x=0x%08X y=0x%08X moveDx=0x%08X moveDy=0x%08X",
+					actorReadU32(actor, kActorXFixed), actorReadU32(actor, kActorYFixed),
+					actorReadU32(actor, kActorMoveDx), actorReadU32(actor, kActorMoveDy));
+				if (selector & 0xFF000000) {
+					uint32 pc = selector & 0x00FFFFFF;
+					int16 wordsLeft = (int16)(debugScriptReadWord(pc) - 1);
+					pc += 2;
+					uint limb = 0;
+					while (wordsLeft > 0 && limb < 16 && debugScriptHasRange(pc, 6)) {
+						uint16 rawSpriteId = debugScriptReadWord(pc);
+						int16 dx = debugScriptReadWord(pc + 2);
+						int16 dy = debugScriptReadWord(pc + 4);
+						pc += 6;
+						wordsLeft -= 3;
+						uint16 spriteId = rawSpriteId;
+						uint16 key = 0;
+						if (spriteId & 0x8000) {
+							if (!debugScriptHasRange(pc, 4))
+								break;
+
+							wordsLeft -= 2;
+							key = debugScriptReadWord(pc);
+							pc += 2;
+							if (keyBitTest(key))
+								spriteId &= 0x7FFF;
+							else
+								spriteId = debugScriptReadWord(pc);
+
+							pc += 2;
+						}
+
+						ImGui::TableNextRow();
+						ImGui::TableSetColumnIndex(1);
+						ImGui::Text("limb %u raw=0x%04X sprite=%u key=%u dx=%d dy=%d final=%d,%d",
+							limb, rawSpriteId, spriteId, key, dx, dy, x + dx, y + dy);
+						limb++;
+					}
+				}
+
+				ImGui::TreePop();
+			}
+		}
+
+		ImGui::EndTable();
+	}
+	ImGui::EndChild();
+
+	ImGui::End();
+}
+
+
+#endif
+
+} // End of namespace Comfy
diff --git a/engines/comfy/module.mk b/engines/comfy/module.mk
index f40e64c98e8..9a64926547f 100644
--- a/engines/comfy/module.mk
+++ b/engines/comfy/module.mk
@@ -6,6 +6,7 @@ MODULE_OBJS = \
 	comfy.o \
 	comfy_keyboard_ui.o \
 	console.o \
+	debug.o \
 	expr.o \
 	game.o \
 	input.o \
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index 6dc339a897b..53f75596c26 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -325,6 +325,8 @@ void ComfyEngine::sceneStartWithMusic(uint16 scene) {
 	if (!envXmsToConv(&_sceneMemoryBlock[_sceneMidiInstanceOffset], scene))
 		return;
 
+	_debugSceneGeneration++;
+
 	midiSyncAndScan();
 	if (!_musicEnabled)
 		midiStopAll();


Commit: 5a496b68c713df5099565d3bc71d780248cfdfaa
    https://github.com/scummvm/scummvm/commit/5a496b68c713df5099565d3bc71d780248cfdfaa
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Refactor raw Actor blob to proper struct

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/anim_file.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/debug.cpp
    engines/comfy/expr.cpp
    engines/comfy/game.cpp
    engines/comfy/scene.cpp
    engines/comfy/script_vm.cpp
    engines/comfy/video.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index af37f1afc94..fe8ad824275 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -486,7 +486,7 @@ void ComfyEngine::backgroundRestoreDirtyRects() {
 		return;
 
 	for (uint i = 0; i < _resolutionChangeCount; i++) {
-		VideoRectRecord &rect = _resolutionChanges[i];
+		ComfyRect &rect = _resolutionChanges[i];
 		int16 width = rect.right - rect.left;
 		int16 height = rect.bottom - rect.top;
 		if (width <= 0 || height <= 0)
@@ -606,42 +606,6 @@ bool ComfyEngine::spriteCoversPoint(int16 spriteId, int16 x, int16 y, int16 poin
 	return false;
 }
 
-uint32 ComfyEngine::actorReadU32(Actor &actor, uint offset) {
-	if (offset + 4 > _actorSize)
-		return 0;
-
-	return READ_LE_UINT32(actor.raw + offset);
-}
-
-uint16 ComfyEngine::actorReadU16(Actor &actor, uint offset) {
-	if (offset + 2 > _actorSize)
-		return 0;
-
-	return READ_LE_UINT16(actor.raw + offset);
-}
-
-byte ComfyEngine::actorReadU8(Actor &actor, uint offset) {
-	if (offset >= _actorSize)
-		return 0;
-
-	return actor.raw[offset];
-}
-
-void ComfyEngine::actorWriteU32(Actor &actor, uint offset, uint32 value) {
-	if (offset + 4 <= _actorSize)
-		WRITE_LE_UINT32(actor.raw + offset, value);
-}
-
-void ComfyEngine::actorWriteU16(Actor &actor, uint offset, uint16 value) {
-	if (offset + 2 <= _actorSize)
-		WRITE_LE_UINT16(actor.raw + offset, value);
-}
-
-void ComfyEngine::actorWriteU8(Actor &actor, uint offset, byte value) {
-	if (offset < _actorSize)
-		actor.raw[offset] = value;
-}
-
 ComfyEngine::Actor *ComfyEngine::actorGetPtr(uint16 actorIndex) {
 	return actorIndex < _actors.size() ? &_actors[actorIndex] : nullptr;
 }
@@ -653,12 +617,12 @@ ComfyEngine::Actor *ComfyEngine::rootActor() {
 void ComfyEngine::actorSetFrame(int16 frame) {
 	Actor *root = rootActor();
 	if (root)
-		actorWriteU32(*root, kActorSpriteSelector, (uint32)(int32)frame);
+		root->spriteSelector = (uint32)(int32)frame;
 }
 
 uint16 ComfyEngine::actorGetFrame() {
 	Actor *root = rootActor();
-	return root ? (uint16)actorReadU32(*root, kActorSpriteSelector) : 0;
+	return root ? (uint16)root->spriteSelector : 0;
 }
 
 void ComfyEngine::actorSetPos(uint16 mode, int16 value) {
@@ -668,13 +632,12 @@ void ComfyEngine::actorSetPos(uint16 mode, int16 value) {
 
 	switch (mode) {
 	case 1:
-		actorWriteU32(*root, kActorXFixed, (uint32)(int32)value);
-		actorWriteU32(*root, kActorYFixed, 0);
+		root->xFixed = value;
+		root->yFixed = 0;
 		break;
 
 	case 2:
-		actorWriteU32(*root, kActorYFixed,
-			(actorReadU32(*root, kActorYFixed) + (int32)value) & 0xFF);
+		root->yFixed = (int32)(((uint32)root->yFixed + (uint32)(int32)value) & 0xFF);
 		break;
 
 	default:
@@ -691,14 +654,14 @@ ComfyEngine::Actor *ComfyEngine::actorResolve(uint16 sceneOrActor, uint16 fallba
 
 uint16 ComfyEngine::actorAlloc(uint16 sceneSlot) {
 	Actor *root = actorGetPtr(0);
-	uint16 actorIndex = root ? actorReadU16(*root, kActorNextLink) : 0;
+	uint16 actorIndex = root ? root->nextLink : 0;
 	if (!actorIndex || sceneSlot >= _sceneHandles.size())
 		return 0;
 
 	Actor *actor = actorGetPtr(actorIndex);
-	actorWriteU16(*root, kActorNextLink, actorReadU16(*actor, kActorNextLink));
+	root->nextLink = actor->nextLink;
 	_sceneHandles[sceneSlot] = actorIndex;
-	actorWriteU16(*actor, kActorSceneHandle, sceneSlot);
+	actor->sceneHandle = sceneSlot;
 	return actorIndex;
 }
 
@@ -712,10 +675,10 @@ void ComfyEngine::actorFreeSlot(uint16 sceneSlot) {
 		return;
 
 	Actor *root = actorGetPtr(0);
-	actorWriteU16(*actor, kActorNextLink, root ? actorReadU16(*root, kActorNextLink) : 0);
-	actorWriteU16(*actor, kActorSceneHandle, 0);
+	actor->nextLink = root ? root->nextLink : 0;
+	actor->sceneHandle = 0;
 	if (root)
-		actorWriteU16(*root, kActorNextLink, actorIndex);
+		root->nextLink = actorIndex;
 	_sceneHandles[sceneSlot] = 0;
 }
 
@@ -725,17 +688,17 @@ void ComfyEngine::actorInsertChild(uint16 childIndex, uint16 parentIndex) {
 	if (!child || !parent)
 		return;
 
-	uint16 tail = actorReadU16(*parent, kActorChildTail);
+	uint16 tail = parent->childTail;
 	if (tail) {
-		actorWriteU16(*actorGetPtr(tail), kActorNextLink, childIndex);
-		actorWriteU16(*child, kActorPrevLink, tail);
+		actorGetPtr(tail)->nextLink = childIndex;
+		child->prevLink = tail;
 	} else {
-		actorWriteU16(*parent, kActorChildHead, childIndex);
-		actorWriteU16(*child, kActorPrevLink, 0);
+		parent->childHead = childIndex;
+		child->prevLink = 0;
 	}
 
-	actorWriteU16(*child, kActorNextLink, 0);
-	actorWriteU16(*parent, kActorChildTail, childIndex);
+	child->nextLink = 0;
+	parent->childTail = childIndex;
 }
 
 void ComfyEngine::actorInsertSibling(uint16 actorIndex, uint16 ownerIndex) {
@@ -744,13 +707,13 @@ void ComfyEngine::actorInsertSibling(uint16 actorIndex, uint16 ownerIndex) {
 	if (!actor || !owner)
 		return;
 
-	uint16 head = actorReadU16(*owner, kActorSiblingHead);
+	uint16 head = owner->siblingHead;
 	if (head)
-		actorWriteU16(*actorGetPtr(head), kActorPrevLink, actorIndex);
+		actorGetPtr(head)->prevLink = actorIndex;
 
-	actorWriteU16(*actor, kActorNextLink, head);
-	actorWriteU16(*actor, kActorPrevLink, 0);
-	actorWriteU16(*owner, kActorSiblingHead, actorIndex);
+	actor->nextLink = head;
+	actor->prevLink = 0;
+	owner->siblingHead = actorIndex;
 }
 
 void ComfyEngine::actorUnlink(uint16 actorIndex) {
@@ -758,23 +721,23 @@ void ComfyEngine::actorUnlink(uint16 actorIndex) {
 	if (!actor)
 		return;
 
-	Actor *parent = actorGetPtr(actorReadU16(*actor, kActorParent));
+	Actor *parent = actorGetPtr(actor->parent);
 	if (!parent)
 		return;
 
-	uint16 next = actorReadU16(*actor, kActorNextLink);
-	uint16 previous = actorReadU16(*actor, kActorPrevLink);
+	uint16 next = actor->nextLink;
+	uint16 previous = actor->prevLink;
 	if (next)
-		actorWriteU16(*actorGetPtr(next), kActorPrevLink, previous);
-	else if (actorReadU16(*parent, kActorChildTail) == actorIndex)
-		actorWriteU16(*parent, kActorChildTail, previous);
+		actorGetPtr(next)->prevLink = previous;
+	else if (parent->childTail == actorIndex)
+		parent->childTail = previous;
 
 	if (previous)
-		actorWriteU16(*actorGetPtr(previous), kActorNextLink, next);
-	else if (actorReadU16(*parent, kActorSiblingHead) == actorIndex)
-		actorWriteU16(*parent, kActorSiblingHead, next);
+		actorGetPtr(previous)->nextLink = next;
+	else if (parent->siblingHead == actorIndex)
+		parent->siblingHead = next;
 	else
-		actorWriteU16(*parent, kActorChildHead, next);
+		parent->childHead = next;
 }
 
 uint16 ComfyEngine::actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible, byte active,
@@ -784,48 +747,48 @@ uint16 ComfyEngine::actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible,
 	if (!actorIndex || !actor)
 		return 8;
 
-	actorWriteU16(*actor, kActorSceneHandle, sceneSlot);
-	actorWriteU8(*actor, kActorVisible, visible);
-	actorWriteU8(*actor, kActorActive, active);
-	actorWriteU32(*actor, kActorCurrentPc, pc);
-	actorWriteU32(*actor, kActorCallPc, 0);
-	actorWriteU32(*actor, kActorResetPc, pc);
-	actorWriteU32(*actor, kActorXFixed, (uint32)((int32)x * 0x1000));
-	actorWriteU32(*actor, kActorYFixed, (uint32)((int32)y * 0x1000));
-	actorWriteU32(*actor, kActorSpriteSelector, (uint32)(int32)sprite);
-	actorWriteU16(*actor, kActorChildTail, 0);
-	actorWriteU16(*actor, kActorChildHead, 0);
-	actorWriteU16(*actor, kActorSiblingHead, 0);
-	actorWriteU16(*actor, kActorMoveTicks, 0);
-	actorWriteU16(*actor, kActorTriggerKey, 0);
-	actorWriteU16(*actor, kActorWaitTarget, 0);
-	actorWriteU16(*actor, kActorWaitAccum, 0);
-	actorWriteU8(*actor, kActorDirty, 1);
+	actor->sceneHandle = sceneSlot;
+	actor->visible = visible;
+	actor->active = active;
+	actor->currentPc = pc;
+	actor->callPc = 0;
+	actor->resetPc = pc;
+	actor->xFixed = (int32)x * 0x1000;
+	actor->yFixed = (int32)y * 0x1000;
+	actor->spriteSelector = (uint32)(int32)sprite;
+	actor->childTail = 0;
+	actor->childHead = 0;
+	actor->siblingHead = 0;
+	actor->moveTicks = 0;
+	actor->triggerKey = 0;
+	actor->waitTarget = 0;
+	actor->waitAccum = 0;
+	actor->dirty = 1;
 	if (_videoMode == 2 || _videoMode == 4) {
-		VideoRectRecord empty;
-		actorWriteCachedRect(*actor, empty);
-		actorWriteU32(*actor, _actorCachedSpriteOffset, 0);
-		actorWriteU8(*actor, _actorCachedVisibleOffset, 0);
+		ComfyRect empty;
+		actor->cachedRect = empty;
+		actor->cachedSprite = 0;
+		actor->cachedVisible = 0;
 	}
 
 	if (parentSlot) {
 		uint16 parentIndex = sceneGetHandle(parentSlot);
-		actorWriteU16(*actor, kActorParent, parentIndex);
+		actor->parent = parentIndex;
 		if (insertAsChild)
 			actorInsertChild(actorIndex, parentIndex);
 		else
 			actorInsertSibling(actorIndex, parentIndex);
 	} else {
-		actorWriteU16(*actor, kActorParent, 0);
-		actorWriteU16(*actor, kActorNextLink, 0);
-		actorWriteU16(*actor, kActorPrevLink, 0);
+		actor->parent = 0;
+		actor->nextLink = 0;
+		actor->prevLink = 0;
 	}
 
 	return 1;
 }
 
 void ComfyEngine::actorSetPc(Actor &actor, uint32 pc) {
-	uint32 previous = actorReadU32(actor, kActorCallPc);
+	uint32 previous = actor.callPc;
 	uint32 packed = pc;
 	if (previous) {
 		byte entry = _actorPcTable[0] >> 24;
@@ -839,14 +802,14 @@ void ComfyEngine::actorSetPc(Actor &actor, uint32 pc) {
 		packed = ((uint32)entry << 24) + pc;
 	}
 
-	actorWriteU32(actor, kActorCallPc, packed);
+	actor.callPc = packed;
 }
 
 uint32 ComfyEngine::actorPopPc(Actor &actor) {
-	uint32 packed = actorReadU32(actor, kActorCallPc);
+	uint32 packed = actor.callPc;
 	byte entry = packed >> 24;
 	if (entry) {
-		actorWriteU32(actor, kActorCallPc, _actorPcTable[entry]);
+		actor.callPc = _actorPcTable[entry];
 		_actorPcTable[entry] = _actorPcTable[0];
 		_actorPcTable[0] = (uint32)entry << 24;
 		if (_sceneActorPcOffset + sizeof(_actorPcTable) <= _sceneMemoryBlock.size()) {
@@ -854,14 +817,14 @@ uint32 ComfyEngine::actorPopPc(Actor &actor) {
 			WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneActorPcOffset + entry * 4], _actorPcTable[entry]);
 		}
 	} else {
-		actorWriteU32(actor, kActorCallPc, 0);
+		actor.callPc = 0;
 	}
 
 	return packed & 0x00FFFFFF;
 }
 
 void ComfyEngine::actorFreePcChain(Actor &actor) {
-	byte first = actorReadU32(actor, kActorCallPc) >> 24;
+	byte first = actor.callPc >> 24;
 	byte entry = first;
 	while (entry) {
 		byte next = _actorPcTable[entry] >> 24;
@@ -878,7 +841,7 @@ void ComfyEngine::actorFreePcChain(Actor &actor) {
 		entry = next;
 	}
 
-	actorWriteU32(actor, kActorCallPc, 0);
+	actor.callPc = 0;
 }
 
 void ComfyEngine::actorFreeTreePc(uint16 actorIndex) {
@@ -887,33 +850,33 @@ void ComfyEngine::actorFreeTreePc(uint16 actorIndex) {
 		return;
 
 	if (!_usesAnimFile && _videoMode == 2)
-		videoFindBestMode(actorReadCachedRect(*actor));
+		videoFindBestMode(actor->cachedRect);
 
 	actorFreePcChain(*actor);
 
-	uint16 child = actorReadU16(*actor, kActorSiblingHead);
+	uint16 child = actor->siblingHead;
 	while (child) {
 		Actor *childActor = actorGetPtr(child);
-		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
+		uint16 next = childActor ? childActor->nextLink : 0;
 		actorFreeTreePc(child);
 		child = next;
 	}
 
-	child = actorReadU16(*actor, kActorChildHead);
+	child = actor->childHead;
 	while (child) {
 		Actor *childActor = actorGetPtr(child);
-		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
+		uint16 next = childActor ? childActor->nextLink : 0;
 		actorFreeTreePc(child);
 		child = next;
 	}
 
 	if (_usesAnimFile) {
-		uint32 selector = actorReadU32(*actor, kActorSpriteSelector);
+		uint32 selector = actor->spriteSelector;
 		if (_videoMode == 2 || _videoMode == 4) {
 			if (selector & 0xFF000000) {
 				renderInvalidateFullFrame();
 			} else if (selector != 0x00FFFFFF) {
-				videoFindBestMode(actorReadCachedRect(*actor));
+				videoFindBestMode(actor->cachedRect);
 			}
 		}
 
@@ -921,7 +884,7 @@ void ComfyEngine::actorFreeTreePc(uint16 actorIndex) {
 			animFrameShutdown(true);
 	}
 
-	uint16 sceneSlot = actorReadU16(*actor, kActorSceneHandle);
+	uint16 sceneSlot = actor->sceneHandle;
 	actorFreeSlot(sceneSlot);
 }
 
@@ -930,19 +893,19 @@ void ComfyEngine::actorClearDirtyTree(uint16 actorIndex) {
 	if (!actor)
 		return;
 
-	actorWriteU8(*actor, kActorDirty, 0);
-	uint16 child = actorReadU16(*actor, kActorSiblingHead);
+	actor->dirty = 0;
+	uint16 child = actor->siblingHead;
 	while (child) {
 		Actor *childActor = actorGetPtr(child);
-		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
+		uint16 next = childActor ? childActor->nextLink : 0;
 		actorClearDirtyTree(child);
 		child = next;
 	}
 
-	child = actorReadU16(*actor, kActorChildHead);
+	child = actor->childHead;
 	while (child) {
 		Actor *childActor = actorGetPtr(child);
-		uint16 next = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
+		uint16 next = childActor ? childActor->nextLink : 0;
 		actorClearDirtyTree(child);
 		child = next;
 	}
@@ -950,14 +913,14 @@ void ComfyEngine::actorClearDirtyTree(uint16 actorIndex) {
 
 void ComfyEngine::actorSetAllVisible() {
 	for (uint i = 0; i + 1 < _actors.size(); i++)
-		actorWriteU8(_actors[i], kActorDirty, 1);
+		_actors[i].dirty = 1;
 }
 
 void ComfyEngine::actorClearFirstAnimFrameSelector() {
 	for (uint actorIndex = 1; actorIndex < COMFY_ACTOR_COUNT; actorIndex++) {
 		Actor *actor = actorGetPtr(actorIndex);
-		if (actor && actorReadU32(*actor, kActorSpriteSelector) == 0x00FFFFFF) {
-			actorWriteU32(*actor, kActorSpriteSelector, 0);
+		if (actor && actor->spriteSelector == 0x00FFFFFF) {
+			actor->spriteSelector = 0;
 			break;
 		}
 	}
@@ -972,41 +935,41 @@ bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
 	_currentActor = actorIndex;
 	_actorDestroyedCurrent = false;
 	if (_stringTable.size() > 3) {
-		_stringTable[2] = actorReadU16(*actor, kActorStringRef);
-		_stringTable[3] = actorReadU16(*actor, kActorStringRef + 2);
+		_stringTable[2] = actor->stringRefs[0];
+		_stringTable[3] = actor->stringRefs[1];
 	}
 
-	uint16 triggerKey = actorReadU16(*actor, kActorTriggerKey);
+	uint16 triggerKey = actor->triggerKey;
 	if (triggerKey && keyBitTest(triggerKey)) {
-		byte triggerFlags = actorReadU8(*actor, kActorTriggerFlags);
+		byte triggerFlags = actor->triggerFlags;
 		if (triggerFlags & 1)
-			actorSetPc(*actor, actorReadU32(*actor, kActorCurrentPc));
+			actorSetPc(*actor, actor->currentPc);
 
 		if (triggerFlags & 4)
 			keyBitClear(triggerKey);
 
 		if (triggerFlags & 2)
-			actorWriteU16(*actor, kActorTriggerKey, 0);
+			actor->triggerKey = 0;
 
-		actorWriteU16(*actor, kActorWaitTarget, 0);
-		actorWriteU16(*actor, kActorWaitAccum, 0);
-		actorWriteU32(*actor, kActorCurrentPc, actorReadU32(*actor, kActorTriggerPc));
+		actor->waitTarget = 0;
+		actor->waitAccum = 0;
+		actor->currentPc = actor->triggerPc;
 	}
 
 	bool timerWaitYield = false;
-	int16 waitTarget = actorReadU16(*actor, kActorWaitTarget);
+	int16 waitTarget = actor->waitTarget;
 	if (waitTarget) {
 		if (waitTarget > _timerCurrent) {
-			actorWriteU16(*actor, kActorWaitTarget, waitTarget - _timerCurrent);
+			actor->waitTarget = waitTarget - _timerCurrent;
 			timerWaitYield = true;
 		} else {
 			int16 elapsed = _timerCurrent - waitTarget;
-			actorWriteU16(*actor, kActorWaitAccum, actorReadU16(*actor, kActorWaitAccum) + elapsed);
-			actorWriteU16(*actor, kActorWaitTarget, 0);
+			actor->waitAccum += elapsed;
+			actor->waitTarget = 0;
 		}
 	}
 
-	int16 moveTicks = actorReadU16(*actor, kActorMoveTicks);
+	int16 moveTicks = actor->moveTicks;
 	if (moveTicks) {
 		int16 stepTicks = (int16)(uint16)(_timerCurrent + _timer0 + _timer1 + _timer2 + 2) / 4;
 		if (stepTicks > 20)
@@ -1014,42 +977,42 @@ bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
 
 		if (moveTicks < stepTicks) {
 			moveTicks = stepTicks;
-			actorWriteU16(*actor, kActorMoveTicks, moveTicks);
+			actor->moveTicks = moveTicks;
 		}
 
-		int32 moveDx = actorReadU32(*actor, kActorMoveDx);
-		int32 moveDy = actorReadU32(*actor, kActorMoveDy);
+		int32 moveDx = actor->moveDx;
+		int32 moveDy = actor->moveDy;
 		int32 stepDx = ((int32)stepTicks * moveDx) / moveTicks;
 		int32 stepDy = ((int32)stepTicks * moveDy) / moveTicks;
-		actorWriteU32(*actor, kActorXFixed, actorReadU32(*actor, kActorXFixed) + stepDx);
-		actorWriteU32(*actor, kActorYFixed, actorReadU32(*actor, kActorYFixed) + stepDy);
-		actorWriteU32(*actor, kActorMoveDx, moveDx - stepDx);
-		actorWriteU32(*actor, kActorMoveDy, moveDy - stepDy);
+		actor->xFixed = (int32)((uint32)actor->xFixed + (uint32)stepDx);
+		actor->yFixed = (int32)((uint32)actor->yFixed + (uint32)stepDy);
+		actor->moveDx = moveDx - stepDx;
+		actor->moveDy = moveDy - stepDy;
 		moveTicks -= stepTicks;
 		if (moveTicks < 0)
 			moveTicks = 0;
 
-		actorWriteU16(*actor, kActorMoveTicks, moveTicks);
-		if (moveTicks && actorReadU8(*actor, kActorBlockingMove)) {
+		actor->moveTicks = moveTicks;
+		if (moveTicks && actor->blockingMove) {
 			descendChildren = true;
 			return false;
 		}
 
-		if (!moveTicks && actorReadU16(*actor, kActorCompletionKey))
-			keyBitSet(actorReadU16(*actor, kActorCompletionKey));
+		if (!moveTicks && actor->completionKey)
+			keyBitSet(actor->completionKey);
 	}
 
 	if (timerWaitYield) {
 		if (_stringTable.size() > 3) {
-			actorWriteU16(*actor, kActorStringRef, _stringTable[2]);
-			actorWriteU16(*actor, kActorStringRef + 2, _stringTable[3]);
+			actor->stringRefs[0] = _stringTable[2];
+			actor->stringRefs[1] = _stringTable[3];
 		}
 
 		descendChildren = true;
 		return false;
 	}
 
-	uint32 pc = actorReadU32(*actor, kActorCurrentPc);
+	uint32 pc = actor->currentPc;
 	for (;;) {
 		ScriptDispatchStatus status = scriptStep(*actor, pc);
 		if (status == kScriptContinue)
@@ -1057,11 +1020,11 @@ bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
 
 		if (status == kScriptYield) {
 			if (_stringTable.size() > 3) {
-				actorWriteU16(*actor, kActorStringRef, _stringTable[2]);
-				actorWriteU16(*actor, kActorStringRef + 2, _stringTable[3]);
+				actor->stringRefs[0] = _stringTable[2];
+				actor->stringRefs[1] = _stringTable[3];
 			}
 
-			actorWriteU32(*actor, kActorCurrentPc, pc);
+			actor->currentPc = pc;
 		}
 
 		descendChildren = status == kScriptYield && !_actorDestroyedCurrent;
@@ -1077,7 +1040,7 @@ bool ComfyEngine::actorTickTree(uint16 actorIndex) {
 	if (!actor)
 		return false;
 
-	if (!actorReadU8(*actor, kActorActive)) {
+	if (!actor->active) {
 		actorClearDirtyTree(actorIndex);
 		return false;
 	}
@@ -1088,27 +1051,27 @@ bool ComfyEngine::actorTickTree(uint16 actorIndex) {
 	if (stopBranch || !descendChildren || !actor)
 		return stopBranch;
 
-	uint16 child = actorReadU16(*actor, kActorSiblingHead);
+	uint16 child = actor->siblingHead;
 	while (child) {
 		Actor *childActor = actorGetPtr(child);
-		uint16 savedNext = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
+		uint16 savedNext = childActor ? childActor->nextLink : 0;
 		if (actorTickTree(child))
 			child = savedNext;
 		else {
 			childActor = actorGetPtr(child);
-			child = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
+			child = childActor ? childActor->nextLink : 0;
 		}
 	}
 
-	child = actorReadU16(*actor, kActorChildHead);
+	child = actor->childHead;
 	while (child) {
 		Actor *childActor = actorGetPtr(child);
-		uint16 savedNext = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
+		uint16 savedNext = childActor ? childActor->nextLink : 0;
 		if (actorTickTree(child))
 			child = savedNext;
 		else {
 			childActor = actorGetPtr(child);
-			child = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
+			child = childActor ? childActor->nextLink : 0;
 		}
 	}
 
@@ -1123,7 +1086,7 @@ void ComfyEngine::actorDrawList(uint16 actorIndex, int16 x, int16 y, bool visibl
 			actorDraw(actorIndex, x, y);
 
 		Actor *actor = actorGetPtr(actorIndex);
-		actorIndex = actor ? actorReadU16(*actor, kActorNextLink) : 0;
+		actorIndex = actor ? actor->nextLink : 0;
 	}
 }
 
@@ -1162,7 +1125,7 @@ void ComfyEngine::renderFlushDrawCommands() {
 					if (!nextSprite)
 						continue;
 
-					VideoRectRecord dirtyRect;
+					ComfyRect dirtyRect;
 					dirtyRect.left = nextCommand.x;
 					dirtyRect.top = nextCommand.y;
 					dirtyRect.right = nextCommand.x + nextSprite->header.width;
@@ -1177,7 +1140,7 @@ void ComfyEngine::renderFlushDrawCommands() {
 			if (_engineVersion == 3 && command.actorIndex) {
 				Actor *actor = actorGetPtr(command.actorIndex);
 				if (actor)
-					actorWriteU8(*actor, kActorBlitHitMouse, coversMouse ? 1 : 0);
+					actor->blitHitMouse = coversMouse ? 1 : 0;
 			}
 
 			continue;
@@ -1192,11 +1155,11 @@ void ComfyEngine::renderFlushDrawCommands() {
 		if (_engineVersion == 3 && command.actorIndex) {
 			Actor *actor = actorGetPtr(command.actorIndex);
 			if (actor)
-				actorWriteU8(*actor, kActorBlitHitMouse, coversMouse ? 1 : 0);
+				actor->blitHitMouse = coversMouse ? 1 : 0;
 		}
 
 		if (command.mode == 0) {
-			VideoRectRecord dirtyRect;
+			ComfyRect dirtyRect;
 			dirtyRect.left = command.x;
 			dirtyRect.top = command.y;
 			dirtyRect.right = command.x + sprite->header.width;
@@ -1214,8 +1177,8 @@ void ComfyEngine::renderFlushCachedDirtyRects() {
 		videoFindBestMode(_animFrameDirtyRects[i]);
 }
 
-uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &maskRecord,
-		VideoRectRecord *rects, int16 baseX, int16 baseY) {
+uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, ComfyRect &maskRecord,
+		ComfyRect *rects, int16 baseX, int16 baseY) {
 	if (mode == 1) {
 		_keymaskBits = 0;
 		maskRecord.right = 0;
@@ -1271,7 +1234,7 @@ uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &m
 			_keymaskSpriteWord = spriteId;
 		}
 
-		VideoRectRecord *rect = bitIndex < COMFY_RESOLUTION_CHANGE_CAPACITY ? &rects[bitIndex] : nullptr;
+		ComfyRect *rect = bitIndex < COMFY_RESOLUTION_CHANGE_CAPACITY ? &rects[bitIndex] : nullptr;
 		if (rect) {
 			rect->left = 0;
 			rect->top = 0;
@@ -1305,8 +1268,13 @@ uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &m
 			rect->top = top;
 			rect->right = left + sprite->header.width;
 			rect->bottom = top + sprite->header.height;
-			rect->area = (_isPanther || _engineVersion == 3) ? spriteId :
-				(uint32)sprite->header.width * sprite->header.height;
+			if (_isPanther || _engineVersion == 3) {
+				rect->area = spriteId;
+			} else {
+				rect->area = (uint32)sprite->header.width * sprite->header.height;
+				if (_engineVersion == 1)
+					rect->area = (uint16)rect->area;
+			}
 		}
 	}
 
@@ -1319,8 +1287,8 @@ void ComfyEngine::actorEvalFrameSelection(uint16 actorIndex, int16 x, int16 y) {
 	if (!actor)
 		return;
 
-	uint32 selector = actorReadU32(*actor, _actorCachedSpriteOffset);
-	VideoRectRecord rect = actorReadCachedRect(*actor);
+	uint32 selector = actor->cachedSprite;
+	ComfyRect rect = actor->cachedRect;
 	if (selector == 0x00FFFFFF) {
 		animFrameInvalidateRects(rect.left, rect.top, 0);
 	} else if (selector & 0xFF000000) {
@@ -1331,9 +1299,12 @@ void ComfyEngine::actorEvalFrameSelection(uint16 actorIndex, int16 x, int16 y) {
 
 		if (last != 0xFFFF) {
 			for (uint i = 0; i <= last; i++) {
-				VideoRectRecord dirtyRect = _keymaskInvalidationRects[i];
+				ComfyRect dirtyRect = _keymaskInvalidationRects[i];
 				dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) *
 					(dirtyRect.bottom - dirtyRect.top);
+				if (_engineVersion == 1)
+					dirtyRect.area = (uint16)dirtyRect.area;
+
 				videoFindBestMode(dirtyRect);
 			}
 		}
@@ -1341,44 +1312,22 @@ void ComfyEngine::actorEvalFrameSelection(uint16 actorIndex, int16 x, int16 y) {
 		videoFindBestMode(rect);
 	}
 
-	actorWriteU32(*actor, _actorCachedSpriteOffset, 0);
-	uint16 child = actorReadU16(*actor, kActorSiblingHead);
+	actor->cachedSprite = 0;
+	uint16 child = actor->siblingHead;
 	while (child) {
 		actorEvalFrameSelection(child, x, y);
 		Actor *childActor = actorGetPtr(child);
-		child = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
+		child = childActor ? childActor->nextLink : 0;
 	}
 
-	child = actorReadU16(*actor, kActorChildHead);
+	child = actor->childHead;
 	while (child) {
 		actorEvalFrameSelection(child, x, y);
 		Actor *childActor = actorGetPtr(child);
-		child = childActor ? actorReadU16(*childActor, kActorNextLink) : 0;
+		child = childActor ? childActor->nextLink : 0;
 	}
 }
 
-ComfyEngine::VideoRectRecord ComfyEngine::actorReadCachedRect(Actor &actor) {
-	VideoRectRecord rect;
-	rect.left = actorReadU16(actor, kActorCachedRect);
-	rect.top = actorReadU16(actor, kActorCachedRect + 2);
-	rect.right = actorReadU16(actor, kActorCachedRect + 4);
-	rect.bottom = actorReadU16(actor, kActorCachedRect + 6);
-	rect.area = _actorCachedAreaIs32Bit ? actorReadU32(actor, kActorCachedRect + 8) :
-		actorReadU16(actor, kActorCachedRect + 8);
-	return rect;
-}
-
-void ComfyEngine::actorWriteCachedRect(Actor &actor, VideoRectRecord rect) {
-	actorWriteU16(actor, kActorCachedRect, rect.left);
-	actorWriteU16(actor, kActorCachedRect + 2, rect.top);
-	actorWriteU16(actor, kActorCachedRect + 4, rect.right);
-	actorWriteU16(actor, kActorCachedRect + 6, rect.bottom);
-	if (_actorCachedAreaIs32Bit)
-		actorWriteU32(actor, kActorCachedRect + 8, rect.area);
-	else
-		actorWriteU16(actor, kActorCachedRect + 8, rect.area);
-}
-
 bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 	Actor *actor = actorGetPtr(actorIndex);
 	if (!actor)
@@ -1391,13 +1340,13 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 		return false;
 	}
 
-	if (!_usesAnimFile && !actorReadU8(*actor, kActorVisible)) {
+	if (!_usesAnimFile && !actor->visible) {
 		if ((_videoMode == 2 || _videoMode == 4) &&
-				actorReadU8(*actor, kActorVisible) != actorReadU8(*actor, _actorCachedVisibleOffset)) {
-			int16 drawX = (int16)((int32)actorReadU32(*actor, kActorXFixed) >> 12) + x;
-			int16 drawY = (int16)((int32)actorReadU32(*actor, kActorYFixed) >> 12) + y;
+				actor->visible != actor->cachedVisible) {
+			int16 drawX = (int16)(actor->xFixed >> 12) + x;
+			int16 drawY = (int16)(actor->yFixed >> 12) + y;
 			actorEvalFrameSelection(actorIndex, drawX, drawY);
-			actorWriteU8(*actor, _actorCachedVisibleOffset, actorReadU8(*actor, kActorVisible));
+			actor->cachedVisible = actor->visible;
 		}
 
 		return true;
@@ -1422,23 +1371,23 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 
 bool ComfyEngine::actorDrawLegacyInternal(uint16 actorIndex, int16 x, int16 y) {
 	Actor *actor = actorGetPtr(actorIndex);
-	if (!actor || !actorReadU8(*actor, kActorVisible))
+	if (!actor || !actor->visible)
 		return true;
 
-	int16 drawX = (int16)((int32)actorReadU32(*actor, kActorXFixed) >> 12) + x;
-	int16 drawY = (int16)((int32)actorReadU32(*actor, kActorYFixed) >> 12) + y;
+	int16 drawX = (int16)(actor->xFixed >> 12) + x;
+	int16 drawY = (int16)(actor->yFixed >> 12) + y;
 	bool drawResult = true;
-	uint16 linkedActor = actorReadU16(*actor, kActorSiblingHead);
+	uint16 linkedActor = actor->siblingHead;
 	while (linkedActor && drawResult) {
 		drawResult = actorDrawLegacyInternal(linkedActor, drawX, drawY);
 		Actor *linked = actorGetPtr(linkedActor);
-		linkedActor = linked ? actorReadU16(*linked, kActorNextLink) : 0;
+		linkedActor = linked ? linked->nextLink : 0;
 	}
 
 	if (!drawResult)
 		return false;
 
-	uint32 selector = actorReadU32(*actor, kActorSpriteSelector);
+	uint32 selector = actor->spriteSelector;
 	if (selector == 0x00FFFFFF) {
 		animFrameInvalidateRects(drawX, drawY, 1);
 		drawResult = animFrameBlitAt(drawX, drawY);
@@ -1483,11 +1432,11 @@ bool ComfyEngine::actorDrawLegacyInternal(uint16 actorIndex, int16 x, int16 y) {
 	if (!drawResult)
 		return false;
 
-	linkedActor = actorReadU16(*actor, kActorChildHead);
+	linkedActor = actor->childHead;
 	while (linkedActor && drawResult) {
 		drawResult = actorDrawLegacyInternal(linkedActor, drawX, drawY);
 		Actor *linked = actorGetPtr(linkedActor);
-		linkedActor = linked ? actorReadU16(*linked, kActorNextLink) : 0;
+		linkedActor = linked ? linked->nextLink : 0;
 	}
 
 	return drawResult;
@@ -1498,20 +1447,20 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 	if (!actor)
 		return;
 
-	int16 drawX = (int16)((int32)actorReadU32(*actor, kActorXFixed) >> 12) + x;
-	int16 drawY = (int16)((int32)actorReadU32(*actor, kActorYFixed) >> 12) + y;
-	visible = visible && actorReadU8(*actor, kActorVisible);
-	byte oldVisible = actorReadU8(*actor, _actorCachedVisibleOffset);
-	uint32 oldSelector = actorReadU32(*actor, _actorCachedSpriteOffset);
-	VideoRectRecord oldRect = actorReadCachedRect(*actor);
-	actorDrawList(actorReadU16(*actor, kActorSiblingHead), drawX, drawY, visible);
-	uint32 selector = actorReadU32(*actor, kActorSpriteSelector);
+	int16 drawX = (int16)(actor->xFixed >> 12) + x;
+	int16 drawY = (int16)(actor->yFixed >> 12) + y;
+	visible = visible && actor->visible;
+	byte oldVisible = actor->cachedVisible;
+	uint32 oldSelector = actor->cachedSprite;
+	ComfyRect oldRect = actor->cachedRect;
+	actorDrawList(actor->siblingHead, drawX, drawY, visible);
+	uint32 selector = actor->spriteSelector;
 	bool useDrawQueue = _usesAnimFile && (_isPanther || _engineVersion == 3) && (_videoMode == 2 || _videoMode == 4);
 	if (_isPanther || _engineVersion == 3) {
-		VideoRectRecord newRect;
+		ComfyRect newRect;
 		if (selector == 0x00FFFFFF) {
 			bool changed = false;
-			if (oldVisible != (visible ? 1 : 0) && actorReadU8(*actor, kActorVisible) && oldVisible == 1)
+			if (oldVisible != (visible ? 1 : 0) && actor->visible && oldVisible == 1)
 				changed = true;
 
 			if (oldRect.left != drawX || oldRect.top != drawY)
@@ -1522,15 +1471,16 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 				animFrameInvalidateRects(drawX, drawY, 1);
 				newRect.left = drawX;
 				newRect.top = drawY;
-				actorWriteU8(*actor, _actorCachedVisibleOffset, visible ? 1 : 0);
-				actorWriteCachedRect(*actor, newRect);
+				actor->cachedVisible = visible ? 1 : 0;
+				actor->cachedRect = newRect;
+
 				renderQueueDrawCommand(drawX, drawY, selector, 2, actorIndex);
-			} else if (visible && actorReadU8(*actor, kActorVisible)) {
+			} else if (visible && actor->visible) {
 				animFrameInvalidateRects(drawX, drawY, 0);
 				renderQueueDrawCommand(drawX, drawY, selector, 2, actorIndex);
 			}
 
-			actorDrawList(actorReadU16(*actor, kActorChildHead), drawX, drawY, visible);
+			actorDrawList(actor->childHead, drawX, drawY, visible);
 			return;
 		}
 
@@ -1561,7 +1511,7 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 
 		if (scripted && oldSelector == selector && oldRect.left == newRect.left &&
 				oldRect.top == newRect.top && oldVisible == 1 && visible) {
-			VideoRectRecord oldMaskRecord = oldRect;
+			ComfyRect oldMaskRecord = oldRect;
 			uint16 oldLastRect = scriptEvalKeyMask(oldSelector & 0x00FFFFFF, 0,
 				oldMaskRecord, _keymaskOldRects, oldRect.left, oldRect.top);
 			if (oldLastRect != 0xFFFF && oldLastRect >= COMFY_RESOLUTION_CHANGE_CAPACITY)
@@ -1569,8 +1519,8 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 
 			if (oldLastRect != 0xFFFF) {
 				for (uint i = 0; i <= oldLastRect; i++) {
-					VideoRectRecord &currentRect = _keymaskRects[i];
-					VideoRectRecord &previousRect = _keymaskOldRects[i];
+					ComfyRect &currentRect = _keymaskRects[i];
+					ComfyRect &previousRect = _keymaskOldRects[i];
 					bool equal = currentRect.left == previousRect.left &&
 						currentRect.top == previousRect.top &&
 						currentRect.right == previousRect.right &&
@@ -1584,8 +1534,9 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 				}
 			}
 
-			actorWriteCachedRect(*actor, newRect);
-			actorDrawList(actorReadU16(*actor, kActorChildHead), drawX, drawY, visible);
+			actor->cachedRect = newRect;
+
+			actorDrawList(actor->childHead, drawX, drawY, visible);
 			return;
 		}
 
@@ -1597,7 +1548,7 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			if (visible && selector) {
 				if (scripted && currentLastRect != 0xFFFF) {
 					for (uint i = 0; i <= currentLastRect; i++) {
-						VideoRectRecord &rect = _keymaskRects[i];
+						ComfyRect &rect = _keymaskRects[i];
 						renderQueueDrawCommand(rect.left, rect.top, rect.area, 0, actorIndex);
 					}
 				} else if (!scripted) {
@@ -1609,7 +1560,7 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 				if (oldSelector == 0x00FFFFFF) {
 					renderFlushCachedDirtyRects();
 				} else if (oldSelector & 0xFF000000) {
-					VideoRectRecord oldMaskRecord = oldRect;
+					ComfyRect oldMaskRecord = oldRect;
 					uint16 oldLastRect = scriptEvalKeyMask(oldSelector & 0x00FFFFFF, 0,
 						oldMaskRecord, _keymaskOldRects, oldRect.left, oldRect.top);
 					if (oldLastRect != 0xFFFF && oldLastRect >= COMFY_RESOLUTION_CHANGE_CAPACITY)
@@ -1624,13 +1575,14 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 				}
 			}
 
-			actorWriteU8(*actor, _actorCachedVisibleOffset, visible ? 1 : 0);
-			actorWriteCachedRect(*actor, newRect);
-			actorWriteU32(*actor, _actorCachedSpriteOffset, selector);
+			actor->cachedVisible = visible ? 1 : 0;
+			actor->cachedRect = newRect;
+
+			actor->cachedSprite = selector;
 		} else if (visible) {
 			if (scripted && currentLastRect != 0xFFFF) {
 				for (uint i = 0; i <= currentLastRect; i++) {
-					VideoRectRecord &rect = _keymaskRects[i];
+					ComfyRect &rect = _keymaskRects[i];
 					renderQueueDrawCommand(rect.left, rect.top, rect.area, 1, actorIndex);
 				}
 			} else if (!scripted) {
@@ -1638,13 +1590,13 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			}
 		}
 
-		actorDrawList(actorReadU16(*actor, kActorChildHead), drawX, drawY, visible);
+		actorDrawList(actor->childHead, drawX, drawY, visible);
 		return;
 	}
 
 	bool oldScripted = (oldSelector & 0xFF000000) != 0;
 	bool newScripted = (selector & 0xFF000000) != 0;
-	VideoRectRecord newRect;
+	ComfyRect newRect;
 	uint16 scriptedLastRect = 0xFFFF;
 	if (newScripted) {
 		uint32 pc = selector & 0x00FFFFFF;
@@ -1660,7 +1612,7 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 
 			if (_usesAnimFile && visible && scriptedLastRect != 0xFFFF) {
 				for (uint i = 0; i <= scriptedLastRect; i++) {
-					VideoRectRecord &drawRecord = _keymaskRects[i];
+					ComfyRect &drawRecord = _keymaskRects[i];
 					if (drawRecord.area) {
 						if (useDrawQueue)
 							renderQueueDrawCommand(drawRecord.left, drawRecord.top, drawRecord.area, 1, actorIndex);
@@ -1716,6 +1668,9 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 		newRect.right = drawX + frameWidth;
 		newRect.bottom = drawY + frameHeight;
 		newRect.area = frameWidth * frameHeight;
+		if (_engineVersion == 1)
+			newRect.area = (uint16)newRect.area;
+
 		if (visible) {
 			if (useDrawQueue) {
 				renderQueueDrawCommand(drawX, drawY, selector, 2, actorIndex);
@@ -1732,6 +1687,9 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			newRect.right = newRect.left + sprite->header.width;
 			newRect.bottom = newRect.top + sprite->header.height;
 			newRect.area = sprite->header.width * sprite->header.height;
+			if (_engineVersion == 1)
+				newRect.area = (uint16)newRect.area;
+
 			if (visible) {
 				int16 spriteX = drawX - sprite->header.hotspotX;
 				int16 spriteY = drawY - sprite->header.hotspotY;
@@ -1751,7 +1709,7 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 
 		uint16 oldScriptedLastRect = 0xFFFF;
 		if (oldScripted) {
-			VideoRectRecord maskRecord = oldRect;
+			ComfyRect maskRecord = oldRect;
 			oldScriptedLastRect = scriptEvalKeyMask(oldSelector & 0x00FFFFFF, 0, maskRecord,
 				_keymaskOldRects, oldRect.left, oldRect.top);
 			if (oldScriptedLastRect != 0xFFFF && oldScriptedLastRect >= COMFY_RESOLUTION_CHANGE_CAPACITY)
@@ -1765,22 +1723,28 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 					scriptedLastRect != 0xFFFF && oldScriptedLastRect != 0xFFFF) {
 				uint16 last = MAX(scriptedLastRect, oldScriptedLastRect);
 				for (uint i = 0; i <= last; i++) {
-					VideoRectRecord *oldItem = i <= oldScriptedLastRect ? &_keymaskOldRects[i] : nullptr;
-					VideoRectRecord *newItem = i <= scriptedLastRect ? &_keymaskRects[i] : nullptr;
+					ComfyRect *oldItem = i <= oldScriptedLastRect ? &_keymaskOldRects[i] : nullptr;
+					ComfyRect *newItem = i <= scriptedLastRect ? &_keymaskRects[i] : nullptr;
 					bool equal = oldItem && newItem && oldItem->left == newItem->left && oldItem->top == newItem->top &&
 						oldItem->right == newItem->right && oldItem->bottom == newItem->bottom && oldItem->area == newItem->area;
 					if (!equal) {
 						if (oldItem) {
-							VideoRectRecord dirtyRect = *oldItem;
+							ComfyRect dirtyRect = *oldItem;
 							dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) *
 								(dirtyRect.bottom - dirtyRect.top);
+							if (_engineVersion == 1)
+								dirtyRect.area = (uint16)dirtyRect.area;
+
 							videoFindBestMode(dirtyRect);
 						}
 
 						if (newItem) {
-							VideoRectRecord dirtyRect = *newItem;
+							ComfyRect dirtyRect = *newItem;
 							dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) *
 								(dirtyRect.bottom - dirtyRect.top);
+							if (_engineVersion == 1)
+								dirtyRect.area = (uint16)dirtyRect.area;
+
 							videoFindBestMode(dirtyRect);
 						}
 					}
@@ -1789,9 +1753,12 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 				comparedScriptRects = true;
 			} else if (newScripted && scriptedLastRect != 0xFFFF) {
 				for (uint i = 0; i <= scriptedLastRect; i++) {
-					VideoRectRecord dirtyRect = _keymaskRects[i];
+					ComfyRect dirtyRect = _keymaskRects[i];
 					dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) *
 						(dirtyRect.bottom - dirtyRect.top);
+					if (_engineVersion == 1)
+						dirtyRect.area = (uint16)dirtyRect.area;
+
 					videoFindBestMode(dirtyRect);
 				}
 			} else if (!newScripted && selector != 0x00FFFFFF) {
@@ -1801,9 +1768,12 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			if (!comparedScriptRects) {
 				if (oldScripted && oldScriptedLastRect != 0xFFFF) {
 					for (uint i = 0; i <= oldScriptedLastRect; i++) {
-						VideoRectRecord dirtyRect = _keymaskOldRects[i];
+						ComfyRect dirtyRect = _keymaskOldRects[i];
 						dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) *
 							(dirtyRect.bottom - dirtyRect.top);
+						if (_engineVersion == 1)
+							dirtyRect.area = (uint16)dirtyRect.area;
+
 						videoFindBestMode(dirtyRect);
 					}
 				} else if (oldSelector == 0x00FFFFFF) {
@@ -1814,15 +1784,17 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			}
 		}
 
-		actorWriteU8(*actor, _actorCachedVisibleOffset, newVisible);
-		actorWriteU32(*actor, _actorCachedSpriteOffset, selector);
-		actorWriteCachedRect(*actor, newRect);
+		actor->cachedVisible = newVisible;
+		actor->cachedSprite = selector;
+		actor->cachedRect = newRect;
+		if (_engineVersion == 1)
+			actor->cachedRect.area &= 0xFFFF;
 	}
 
 	if (!_usesAnimFile)
 		animFrameRecordVocCounter(2);
 
-	actorDrawList(actorReadU16(*actor, kActorChildHead), drawX, drawY, visible);
+	actorDrawList(actor->childHead, drawX, drawY, visible);
 }
 
 
diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
index 6ee7c200054..714c9b7c3d3 100644
--- a/engines/comfy/anim_file.cpp
+++ b/engines/comfy/anim_file.cpp
@@ -117,7 +117,7 @@ void ComfyEngine::animFrameShutdown(bool freeBuffers) {
 		if (_animCurrentActorSceneHandle && _animCurrentActorSceneHandle < _sceneHandles.size()) {
 			Actor *actor = actorGetPtr(sceneGetHandle(_animCurrentActorSceneHandle));
 			if (actor)
-				actorWriteU32(*actor, kActorSpriteSelector, 0);
+				actor->spriteSelector = 0;
 		}
 
 		_animCurrentActorSceneHandle = 0;
@@ -185,7 +185,7 @@ void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 ac
 	if (actorSceneHandle < _sceneHandles.size()) {
 		Actor *actor = actorGetPtr(sceneGetHandle(actorSceneHandle));
 		if (actor)
-			actorWriteU32(*actor, kActorSpriteSelector, 0x00FFFFFF);
+			actor->spriteSelector = 0x00FFFFFF;
 	}
 
 	animFileTickCommands();
@@ -564,7 +564,7 @@ bool ComfyEngine::animFrameBlitAt(int16 x, int16 y) {
 
 	uint16 rectCount = _resolutionChangeCount;
 	for (uint i = 0; i < rectCount; i++) {
-		VideoRectRecord &dirtyRect = _resolutionChanges[i];
+		ComfyRect &dirtyRect = _resolutionChanges[i];
 		int16 left = MAX<int16>(dirtyRect.left, x);
 		int16 top = MAX<int16>(dirtyRect.top, y);
 		int16 right = MIN<int16>(dirtyRect.right, x + frameWidth);
@@ -620,7 +620,7 @@ bool ComfyEngine::animFrameCoversPoint(int16 x, int16 y, int16 pointX, int16 poi
 
 	bool dirty = false;
 	for (uint i = 0; i < _resolutionChangeCount; i++) {
-		VideoRectRecord &dirtyRect = _resolutionChanges[i];
+		ComfyRect &dirtyRect = _resolutionChanges[i];
 		if (pointX >= dirtyRect.left && pointX < dirtyRect.right &&
 				pointY >= dirtyRect.top && pointY < dirtyRect.bottom) {
 			dirty = true;
@@ -653,12 +653,14 @@ void ComfyEngine::animFrameInvalidateRects(int16 x, int16 y, byte mode) {
 	for (uint i = 0; i < rectCount; i++) {
 		uint16 start = READ_LE_UINT16(_animFrameCommandData + i * 4);
 		uint16 end = READ_LE_UINT16(_animFrameCommandData + i * 4 + 2);
-		VideoRectRecord rect;
+		ComfyRect rect;
 		rect.left = x + (start % columns) * 4;
 		rect.top = y + (start / columns) * 4;
 		rect.right = x + ((end % columns) + 1) * 4;
 		rect.bottom = y + ((end / columns) + 1) * 4;
 		rect.area = (uint32)(rect.right - rect.left) * (rect.bottom - rect.top);
+		if (_engineVersion == 1)
+			rect.area = (uint16)rect.area;
 
 		if (i < splitIndex) {
 			if (!mode)
@@ -677,6 +679,8 @@ void ComfyEngine::animFrameInvalidateRects(int16 x, int16 y, byte mode) {
 			_animFrameDirtyRects[0].right = _logicalScreenWidth;
 			_animFrameDirtyRects[0].bottom = _logicalScreenHeight;
 			_animFrameDirtyRects[0].area = framebufferBytes();
+			if (_engineVersion == 1)
+				_animFrameDirtyRects[0].area = (uint16)_animFrameDirtyRects[0].area;
 		}
 
 		if (mode)
@@ -864,7 +868,7 @@ void ComfyEngine::animFileUnpackState(const byte *state) {
 	if (_animCurrentActorSceneHandle < _sceneHandles.size()) {
 		Actor *actor = actorGetPtr(sceneGetHandle(_animCurrentActorSceneHandle));
 		if (actor)
-			actorWriteU32(*actor, kActorSpriteSelector, 0x00FFFFFF);
+			actor->spriteSelector = 0x00FFFFFF;
 	}
 
 	_animFrameBuffer.resize(framebufferBytes());
@@ -885,8 +889,8 @@ void ComfyEngine::animFrameInvalidateActorRect() {
 	if (!actor)
 		return;
 
-	actorWriteU16(*actor, kActorCachedRect, 0x270F);
-	actorWriteU16(*actor, kActorCachedRect + 4, 0x270F);
+	actor->cachedRect.left = 0x270F;
+	actor->cachedRect.right = 0x270F;
 }
 
 } // End of namespace Comfy
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index e4bc9e0fc39..fbd34fb1c0f 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -85,19 +85,8 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ComfyGameDescription *gameDesc) :
 	memset(_animStorageChunkFileOffsets, 0, sizeof(_animStorageChunkFileOffsets));
 	memset(_animStorageChunkOffsets, 0, sizeof(_animStorageChunkOffsets));
 	memset(_animStorageChunkSizes, 0, sizeof(_animStorageChunkSizes));
-	if (_engineVersion == 3) {
-		_actorSize = COMFY_ACTOR_SIZE_V3;
-		_actorCachedVisibleOffset = 0x51;
-		_actorCachedSpriteOffset = 0x52;
-		_actorCachedAreaIs32Bit = true;
-	}
-
 	if (!strcmp(gameDesc->desc.gameId, "panther")) {
 		_isPanther = true;
-		_actorSize = COMFY_PANTHER_ACTOR_SIZE;
-		_actorCachedVisibleOffset = 0x51;
-		_actorCachedSpriteOffset = 0x52;
-		_actorCachedAreaIs32Bit = true;
 		_vocQueueCapacity = COMFY_PANTHER_VOC_QUEUE_CAPACITY;
 	}
 
@@ -358,7 +347,7 @@ void ComfyEngine::processEvents() {
 }
 
 void ComfyEngine::mouseSetActor(Actor *actor) {
-	_mouseActorSceneHandle = actor ? actorReadU16(*actor, kActorSceneHandle) : 0;
+	_mouseActorSceneHandle = actor ? actor->sceneHandle : 0;
 }
 
 ComfyEngine::Actor *ComfyEngine::mouseGetActor() {
@@ -395,7 +384,7 @@ void ComfyEngine::mouseUpdateCursor() {
 		return;
 	}
 
-	uint32 selector = actorReadU32(*_mouseActor, kActorSpriteSelector);
+	uint32 selector = _mouseActor->spriteSelector;
 	if (!selector) {
 		_mouseCursorSprite = nullptr;
 		_mouseFlags &= ~0x10;
@@ -406,7 +395,7 @@ void ComfyEngine::mouseUpdateCursor() {
 	if (_mouseCursorSprite)
 		_mouseCursorSpriteId = (uint16)_mouseCursorSprite->id;
 
-	if (!actorReadU8(*_mouseActor, kActorVisible) && !(_mouseFlags & 8))
+	if (!_mouseActor->visible && !(_mouseFlags & 8))
 		_mouseFlags |= 8;
 
 	_mouseFlags &= ~0x10;
@@ -482,7 +471,7 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 		if (lastKey == 0x0101)
 			keepRunning = 0;
 		else if (mainLoopActor)
-			keepRunning = actorReadU8(*mainLoopActor, kActorActive);
+			keepRunning = mainLoopActor->active;
 
 		processEvents();
 		if (shouldQuit())
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 90a0894b5bd..f3185905096 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -54,7 +54,7 @@ class QueuingAudioStream;
 #define COMFY_PALETTE_BYTES 0x300
 #define COMFY_INPUT_QUEUE_CAPACITY 20
 #define COMFY_KEYBOARD_CONTACT_COUNT 24
-#define COMFY_ACTOR_SIZE 0x54
+#define COMFY_ACTOR_SIZE_V1 0x54
 #define COMFY_ACTOR_COUNT 0x79
 #define COMFY_EXPR_STACK_CAPACITY 64
 #define COMFY_ACTOR_PC_TABLE_COUNT 200
@@ -66,7 +66,7 @@ class QueuingAudioStream;
 #define COMFY_SCENE_MIDI_VERSION_BYTES_CLASSIC 0x167
 #define COMFY_SCENE_VOC_STATE_BYTES_V3 0x24D
 #define COMFY_SCENE_STATE_BYTES_V3 0x17F
-#define COMFY_PANTHER_ACTOR_SIZE 0x56
+#define COMFY_ACTOR_SIZE_V2 0x56
 #define COMFY_ACTOR_SIZE_V3 0x57
 #define COMFY_SCENE_ACTOR_PC_BYTES 0x320
 #define COMFY_SCENE_FRAME_BYTES 0x4E20
@@ -123,26 +123,27 @@ void drawComfyKeyboardUi(bool actorDebugEnabled);
 void cleanupComfyKeyboardUi();
 #endif
 
+struct ComfyRect {
+	int16 left;
+	int16 top;
+	int16 right;
+	int16 bottom;
+	// Version 1 stores area as a word; versions 2 and 3 store it as a dword.
+	uint32 area;
+
+	ComfyRect() {
+		left = 0;
+		top = 0;
+		right = 0;
+		bottom = 0;
+		area = 0;
+	}
+};
+
 class ComfyEngine : public Engine {
 private:
 	friend struct SoundDecoderState;
 
-	struct VideoRectRecord {
-		int16 left;
-		int16 top;
-		int16 right;
-		int16 bottom;
-		uint32 area;
-
-		VideoRectRecord() {
-			left = 0;
-			top = 0;
-			right = 0;
-			bottom = 0;
-			area = 0;
-		}
-	};
-
 	struct DrawCommand {
 		int16 x;
 		int16 y;
@@ -344,42 +345,75 @@ private:
 		uint32 counterThreshold;
 	};
 
+	// Serialized Actor strides are 0x54 in version 1, 0x56 in version 2, and 0x57 in version 3.
+	// Version 1 stores cachedRect.area as a word; later versions use a dword, and version 3 adds blitHitMouse.
+	// This is a host representation; XMS state serializes each field explicitly instead of copying this layout.
 	struct Actor {
-		byte raw[COMFY_ACTOR_SIZE_V3];
-	};
+		uint32 currentPc;
+		uint32 callPc;
+		uint32 resetPc;
+		int32 xFixed;
+		int32 yFixed;
+		uint32 spriteSelector;
+		int32 moveDx;
+		int32 moveDy;
+		uint32 triggerPc;
+		uint16 stringRefs[2];
+		uint16 sceneHandle;
+		byte visible;
+		byte active;
+		uint16 parent;
+		uint16 childTail;
+		uint16 childHead;
+		uint16 siblingHead;
+		uint16 nextLink;
+		uint16 prevLink;
+		uint16 moveTicks;
+		byte blockingMove;
+		uint16 completionKey;
+		uint16 triggerKey;
+		byte triggerFlags;
+		uint16 waitTarget;
+		uint16 waitAccum;
+		byte dirty;
+		ComfyRect cachedRect;
+		byte cachedVisible;
+		uint32 cachedSprite;
+		byte blitHitMouse;
 
-	enum ActorOffset {
-		kActorCurrentPc = 0x00,
-		kActorCallPc = 0x04,
-		kActorResetPc = 0x08,
-		kActorXFixed = 0x0C,
-		kActorYFixed = 0x10,
-		kActorSpriteSelector = 0x14,
-		kActorMoveDx = 0x18,
-		kActorMoveDy = 0x1C,
-		kActorTriggerPc = 0x20,
-		kActorStringRef = 0x24,
-		kActorSceneHandle = 0x28,
-		kActorVisible = 0x2A,
-		kActorActive = 0x2B,
-		kActorParent = 0x2C,
-		kActorChildTail = 0x2E,
-		kActorChildHead = 0x30,
-		kActorSiblingHead = 0x32,
-		kActorNextLink = 0x34,
-		kActorPrevLink = 0x36,
-		kActorMoveTicks = 0x38,
-		kActorBlockingMove = 0x3A,
-		kActorCompletionKey = 0x3B,
-		kActorTriggerKey = 0x3D,
-		kActorTriggerFlags = 0x3F,
-		kActorWaitTarget = 0x40,
-		kActorWaitAccum = 0x42,
-		kActorDirty = 0x44,
-		kActorCachedRect = 0x45,
-		kActorCachedVisible = 0x4F,
-		kActorCachedSprite = 0x50,
-		kActorBlitHitMouse = 0x56
+		Actor() {
+			currentPc = 0;
+			callPc = 0;
+			resetPc = 0;
+			xFixed = 0;
+			yFixed = 0;
+			spriteSelector = 0;
+			moveDx = 0;
+			moveDy = 0;
+			triggerPc = 0;
+			stringRefs[0] = 0;
+			stringRefs[1] = 0;
+			sceneHandle = 0;
+			visible = 0;
+			active = 0;
+			parent = 0;
+			childTail = 0;
+			childHead = 0;
+			siblingHead = 0;
+			nextLink = 0;
+			prevLink = 0;
+			moveTicks = 0;
+			blockingMove = 0;
+			completionKey = 0;
+			triggerKey = 0;
+			triggerFlags = 0;
+			waitTarget = 0;
+			waitAccum = 0;
+			dirty = 0;
+			cachedVisible = 0;
+			cachedSprite = 0;
+			blitHitMouse = 0;
+		}
 	};
 
 	enum ScriptDispatchStatus {
@@ -390,10 +424,6 @@ private:
 	const ComfyGameDescription *_game;
 	byte _engineVersion;
 	bool _isPanther = false;
-	uint16 _actorSize = COMFY_ACTOR_SIZE;
-	uint16 _actorCachedVisibleOffset = kActorCachedVisible;
-	uint16 _actorCachedSpriteOffset = kActorCachedSprite;
-	bool _actorCachedAreaIs32Bit = false;
 	uint16 _vocQueueCapacity = COMFY_VOC_QUEUE_CAPACITY;
 	Common::Path _gameDirectory;
 	Common::Path _introDirectory;
@@ -418,7 +448,7 @@ private:
 	uint16 _renderHeight = 0;
 	int16 _viewOffsetX = 0;
 	int16 _viewOffsetY = 0;
-	VideoRectRecord _resolutionChanges[COMFY_RESOLUTION_CHANGE_CAPACITY];
+	ComfyRect _resolutionChanges[COMFY_RESOLUTION_CHANGE_CAPACITY];
 	uint16 _resolutionChangeCount = 0;
 	uint16 _renderDirtyCount = 0;
 	bool _renderInterleaved = false;
@@ -522,11 +552,11 @@ private:
 	uint16 _keymaskResult = 0;
 	int16 _keymaskX = 0;
 	int16 _keymaskY = 0;
-	VideoRectRecord _keymaskCurrentRecord;
-	VideoRectRecord _keymaskRects[COMFY_RESOLUTION_CHANGE_CAPACITY];
-	VideoRectRecord _keymaskOldRects[COMFY_RESOLUTION_CHANGE_CAPACITY];
-	VideoRectRecord _keymaskInvalidationRects[COMFY_RESOLUTION_CHANGE_CAPACITY];
-	VideoRectRecord _animFrameDirtyRects[COMFY_ANIM_DIRTY_RECT_CAPACITY];
+	ComfyRect _keymaskCurrentRecord;
+	ComfyRect _keymaskRects[COMFY_RESOLUTION_CHANGE_CAPACITY];
+	ComfyRect _keymaskOldRects[COMFY_RESOLUTION_CHANGE_CAPACITY];
+	ComfyRect _keymaskInvalidationRects[COMFY_RESOLUTION_CHANGE_CAPACITY];
+	ComfyRect _animFrameDirtyRects[COMFY_ANIM_DIRTY_RECT_CAPACITY];
 	uint16 _animFrameDirtyRectCount = 0;
 	DrawCommand _drawCommands[COMFY_DRAW_COMMAND_CAPACITY];
 	uint16 _drawCommandCount = 0;
@@ -717,7 +747,7 @@ private:
 	void videoInit();
 	void videoShutdown(byte restorePalette);
 	void videoSetResolution();
-	void videoFindBestMode(VideoRectRecord record);
+	void videoFindBestMode(ComfyRect record);
 	void videoPresentFrame();
 	void renderSetDirty();
 	void renderFlushDirty();
@@ -823,12 +853,6 @@ private:
 	uint16 scriptEvalExpr(uint32 &pc, uint16 fallbackActor);
 	ScriptDispatchStatus scriptDispatch(Actor &actor, byte opcode, uint32 &pc);
 	ScriptDispatchStatus scriptStep(Actor &actor, uint32 &pc);
-	uint32 actorReadU32(Actor &actor, uint offset);
-	uint16 actorReadU16(Actor &actor, uint offset);
-	byte actorReadU8(Actor &actor, uint offset);
-	void actorWriteU32(Actor &actor, uint offset, uint32 value);
-	void actorWriteU16(Actor &actor, uint offset, uint16 value);
-	void actorWriteU8(Actor &actor, uint offset, byte value);
 	Actor *rootActor();
 	Actor *actorGetPtr(uint16 actorIndex);
 	void actorSetFrame(int16 frame);
@@ -858,11 +882,9 @@ private:
 	void renderQueueDrawCommand(int16 x, int16 y, uint32 selector, byte mode, uint16 actorIndex);
 	void renderFlushDrawCommands();
 	void renderFlushCachedDirtyRects();
-	uint16 scriptEvalKeyMask(uint32 pc, uint16 mode, VideoRectRecord &maskRecord,
-		VideoRectRecord *rects, int16 baseX, int16 baseY);
+	uint16 scriptEvalKeyMask(uint32 pc, uint16 mode, ComfyRect &maskRecord,
+		ComfyRect *rects, int16 baseX, int16 baseY);
 	void actorEvalFrameSelection(uint16 actorIndex, int16 x, int16 y);
-	VideoRectRecord actorReadCachedRect(Actor &actor);
-	void actorWriteCachedRect(Actor &actor, VideoRectRecord rect);
 	void timerInit();
 	void timerShutdown();
 	void lptKeyboardInit();
diff --git a/engines/comfy/debug.cpp b/engines/comfy/debug.cpp
index f5a36dad6b9..52fbd503425 100644
--- a/engines/comfy/debug.cpp
+++ b/engines/comfy/debug.cpp
@@ -96,29 +96,29 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 
 	for (uint i = 0; i < _actors.size(); i++) {
 		Actor &actor = _actors[i];
-		uint16 sceneHandle = actorReadU16(actor, kActorSceneHandle);
+		uint16 sceneHandle = actor.sceneHandle;
 		if (!sceneHandle && i != 0)
 			continue;
 
-		int32 xFixed = (int32)actorReadU32(actor, kActorXFixed);
-		int32 yFixed = (int32)actorReadU32(actor, kActorYFixed);
-		uint16 parent = actorReadU16(actor, kActorParent);
+		int32 xFixed = actor.xFixed;
+		int32 yFixed = actor.yFixed;
+		uint16 parent = actor.parent;
 		uint guard = 0;
 		while (parent && parent < _actors.size() && guard++ < COMFY_ACTOR_COUNT) {
 			Actor *parentActor = actorGetPtr(parent);
 			if (!parentActor)
 				break;
 
-			xFixed += (int32)actorReadU32(*parentActor, kActorXFixed);
-			yFixed += (int32)actorReadU32(*parentActor, kActorYFixed);
-			parent = actorReadU16(*parentActor, kActorParent);
+			xFixed = (int32)((uint32)xFixed + (uint32)parentActor->xFixed);
+			yFixed = (int32)((uint32)yFixed + (uint32)parentActor->yFixed);
+			parent = parentActor->parent;
 		}
 
 		int16 x = (int16)(xFixed >> 12);
 		int16 y = (int16)(yFixed >> 12);
 		debugIncludeMapPoint(mapLeft, mapTop, mapRight, mapBottom, x, y);
 
-		uint32 selector = actorReadU32(actor, kActorSpriteSelector);
+		uint32 selector = actor.spriteSelector;
 		if (selector && !(selector & 0xFF000000) && selector != 0x00FFFFFF &&
 				selector < _spriteResources.size() && _spriteResources[selector].loaded) {
 			SpriteResource &sprite = _spriteResources[selector];
@@ -182,28 +182,28 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 	drawList->AddRect(screenTopLeft, screenBottomRight, IM_COL32(110, 170, 240, 230));
 	for (uint i = 0; i < _actors.size(); i++) {
 		Actor &actor = _actors[i];
-		uint16 sceneHandle = actorReadU16(actor, kActorSceneHandle);
+		uint16 sceneHandle = actor.sceneHandle;
 		if (!sceneHandle && i != 0)
 			continue;
 
-		int32 xFixed = (int32)actorReadU32(actor, kActorXFixed);
-		int32 yFixed = (int32)actorReadU32(actor, kActorYFixed);
-		uint16 parent = actorReadU16(actor, kActorParent);
+		int32 xFixed = actor.xFixed;
+		int32 yFixed = actor.yFixed;
+		uint16 parent = actor.parent;
 		uint guard = 0;
 		while (parent && parent < _actors.size() && guard++ < COMFY_ACTOR_COUNT) {
 			Actor *parentActor = actorGetPtr(parent);
 			if (!parentActor)
 				break;
 
-			xFixed += (int32)actorReadU32(*parentActor, kActorXFixed);
-			yFixed += (int32)actorReadU32(*parentActor, kActorYFixed);
-			parent = actorReadU16(*parentActor, kActorParent);
+			xFixed = (int32)((uint32)xFixed + (uint32)parentActor->xFixed);
+			yFixed = (int32)((uint32)yFixed + (uint32)parentActor->yFixed);
+			parent = parentActor->parent;
 		}
 
 		int16 x = (int16)(xFixed >> 12);
 		int16 y = (int16)(yFixed >> 12);
-		bool visibleActor = actorReadU8(actor, kActorVisible) != 0;
-		bool activeActor = actorReadU8(actor, kActorActive) != 0;
+		bool visibleActor = actor.visible != 0;
+		bool activeActor = actor.active != 0;
 		ImU32 color = visibleActor ? (activeActor ? IM_COL32(82, 220, 120, 230) : IM_COL32(238, 185, 74, 230)) :
 			IM_COL32(120, 120, 120, 170);
 
@@ -214,7 +214,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 		snprintf(actorLabel, sizeof(actorLabel), "%u", i);
 		drawList->AddText(ImVec2(point.x + 4.0F, point.y - 4.0F), color, actorLabel);
 
-		uint32 selector = actorReadU32(actor, kActorSpriteSelector);
+		uint32 selector = actor.spriteSelector;
 		if (visibleActor && selector && !(selector & 0xFF000000) && selector != 0x00FFFFFF &&
 				selector < _spriteResources.size() && _spriteResources[selector].loaded) {
 			SpriteResource &sprite = _spriteResources[selector];
@@ -304,13 +304,13 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 				continue;
 
 			Actor &actor = _actors[actorIndex];
-			uint16 sceneHandle = actorReadU16(actor, kActorSceneHandle);
+			uint16 sceneHandle = actor.sceneHandle;
 			if (!sceneHandle && actorIndex != 0)
 				continue;
 
 			uint16 children[COMFY_ACTOR_COUNT];
 			uint childCount = 0;
-			uint16 child = actorReadU16(actor, kActorChildHead);
+			uint16 child = actor.childHead;
 			uint guard = 0;
 			while (child && child < _actors.size() && child < COMFY_ACTOR_COUNT &&
 					childCount < COMFY_ACTOR_COUNT && guard++ < COMFY_ACTOR_COUNT) {
@@ -324,28 +324,28 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 				if (!childActor)
 					break;
 
-				child = actorReadU16(*childActor, kActorSiblingHead);
+				child = childActor->siblingHead;
 			}
 
-			uint32 selector = actorReadU32(actor, kActorSpriteSelector);
-			int32 xFixed = (int32)actorReadU32(actor, kActorXFixed);
-			int32 yFixed = (int32)actorReadU32(actor, kActorYFixed);
-			uint16 parent = actorReadU16(actor, kActorParent);
+			uint32 selector = actor.spriteSelector;
+			int32 xFixed = actor.xFixed;
+			int32 yFixed = actor.yFixed;
+			uint16 parent = actor.parent;
 			guard = 0;
 			while (parent && parent < _actors.size() && guard++ < COMFY_ACTOR_COUNT) {
 				Actor *parentActor = actorGetPtr(parent);
 				if (!parentActor)
 					break;
 
-				xFixed += (int32)actorReadU32(*parentActor, kActorXFixed);
-				yFixed += (int32)actorReadU32(*parentActor, kActorYFixed);
-				parent = actorReadU16(*parentActor, kActorParent);
+				xFixed = (int32)((uint32)xFixed + (uint32)parentActor->xFixed);
+				yFixed = (int32)((uint32)yFixed + (uint32)parentActor->yFixed);
+				parent = parentActor->parent;
 			}
 
 			int16 x = (int16)(xFixed >> 12);
 			int16 y = (int16)(yFixed >> 12);
-			bool visibleActor = actorReadU8(actor, kActorVisible) != 0;
-			bool activeActor = actorReadU8(actor, kActorActive) != 0;
+			bool visibleActor = actor.visible != 0;
+			bool activeActor = actor.active != 0;
 			ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanAvailWidth;
 			if (!childCount)
 				flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen;
@@ -355,16 +355,16 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 
 			ImGui::SameLine(120.0F);
 			ImGui::Text("scene=%u pos=%d,%d selector=0x%08X move=%d",
-				sceneHandle, x, y, selector, (int16)actorReadU16(actor, kActorMoveTicks));
+				sceneHandle, x, y, selector, (int16)actor.moveTicks);
 
 			ImGui::SameLine(520.0F);
 			if (ImGui::Checkbox("Visible", &visibleActor)) {
-				actorWriteU8(actor, kActorVisible, visibleActor ? 1 : 0);
+				actor.visible = visibleActor ? 1 : 0;
 				renderSetDirty();
 			}
 			ImGui::SameLine();
 			if (ImGui::Checkbox("Active", &activeActor))
-				actorWriteU8(actor, kActorActive, activeActor ? 1 : 0);
+				actor.active = activeActor ? 1 : 0;
 			ImGui::PopID();
 
 			if (open && childCount) {
@@ -384,7 +384,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 				for (uint i = 0; i < _actors.size() && i < COMFY_ACTOR_COUNT &&
 						stackCount < ARRAYSIZE(actorStack); i++) {
 					Actor &orphanActor = _actors[i];
-					if (visited[i] || (!actorReadU16(orphanActor, kActorSceneHandle) && i != 0))
+					if (visited[i] || (!orphanActor.sceneHandle && i != 0))
 						continue;
 
 					actorStack[stackCount] = i;
@@ -410,29 +410,29 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 
 		for (uint i = 0; i < _actors.size(); i++) {
 			Actor &actor = _actors[i];
-			uint16 sceneHandle = actorReadU16(actor, kActorSceneHandle);
+			uint16 sceneHandle = actor.sceneHandle;
 			if (!sceneHandle && i != 0)
 				continue;
 
-			uint32 selector = actorReadU32(actor, kActorSpriteSelector);
-			int32 xFixed = (int32)actorReadU32(actor, kActorXFixed);
-			int32 yFixed = (int32)actorReadU32(actor, kActorYFixed);
-			uint16 parent = actorReadU16(actor, kActorParent);
+			uint32 selector = actor.spriteSelector;
+			int32 xFixed = actor.xFixed;
+			int32 yFixed = actor.yFixed;
+			uint16 parent = actor.parent;
 			uint guard = 0;
 			while (parent && parent < _actors.size() && guard++ < COMFY_ACTOR_COUNT) {
 				Actor *parentActor = actorGetPtr(parent);
 				if (!parentActor)
 					break;
 
-				xFixed += (int32)actorReadU32(*parentActor, kActorXFixed);
-				yFixed += (int32)actorReadU32(*parentActor, kActorYFixed);
-				parent = actorReadU16(*parentActor, kActorParent);
+				xFixed = (int32)((uint32)xFixed + (uint32)parentActor->xFixed);
+				yFixed = (int32)((uint32)yFixed + (uint32)parentActor->yFixed);
+				parent = parentActor->parent;
 			}
 
 			int16 x = (int16)(xFixed >> 12);
 			int16 y = (int16)(yFixed >> 12);
-			bool visibleActor = actorReadU8(actor, kActorVisible) != 0;
-			bool activeActor = actorReadU8(actor, kActorActive) != 0;
+			bool visibleActor = actor.visible != 0;
+			bool activeActor = actor.active != 0;
 
 			ImGui::TableNextRow();
 			ImGui::TableSetColumnIndex(0);
@@ -440,7 +440,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 			ImGui::TableSetColumnIndex(1);
 			ImGui::Text("%u", sceneHandle);
 			ImGui::TableSetColumnIndex(2);
-			ImGui::Text("%u", actorReadU16(actor, kActorParent));
+			ImGui::Text("%u", actor.parent);
 			ImGui::TableSetColumnIndex(3);
 			ImGui::Text("%d", x);
 			ImGui::TableSetColumnIndex(4);
@@ -448,34 +448,33 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 			ImGui::TableSetColumnIndex(5);
 			ImGui::Text("0x%08X", selector);
 			ImGui::TableSetColumnIndex(6);
-			ImGui::Text("0x%08X", actorReadU32(actor, kActorCurrentPc));
+			ImGui::Text("0x%08X", actor.currentPc);
 			ImGui::TableSetColumnIndex(7);
 			ImGui::PushID((int)i * 2);
 			if (ImGui::Checkbox("", &visibleActor)) {
-				actorWriteU8(actor, kActorVisible, visibleActor ? 1 : 0);
+				actor.visible = visibleActor ? 1 : 0;
 				renderSetDirty();
 			}
 			ImGui::PopID();
 			ImGui::TableSetColumnIndex(8);
 			ImGui::PushID((int)i * 2 + 1);
 			if (ImGui::Checkbox("", &activeActor))
-				actorWriteU8(actor, kActorActive, activeActor ? 1 : 0);
+				actor.active = activeActor ? 1 : 0;
 			ImGui::PopID();
 			ImGui::TableSetColumnIndex(9);
-			ImGui::Text("%d", (int16)actorReadU16(actor, kActorMoveTicks));
+			ImGui::Text("%d", (int16)actor.moveTicks);
 
 			if (open) {
 				ImGui::TableNextRow();
 				ImGui::TableSetColumnIndex(1);
 				ImGui::Text("links prev=%u next=%u child=%u sibling=%u tail=%u",
-					actorReadU16(actor, kActorPrevLink), actorReadU16(actor, kActorNextLink),
-					actorReadU16(actor, kActorChildHead), actorReadU16(actor, kActorSiblingHead),
-					actorReadU16(actor, kActorChildTail));
+					actor.prevLink, actor.nextLink, actor.childHead, actor.siblingHead,
+					actor.childTail);
 				ImGui::TableNextRow();
 				ImGui::TableSetColumnIndex(1);
 				ImGui::Text("local fixed x=0x%08X y=0x%08X moveDx=0x%08X moveDy=0x%08X",
-					actorReadU32(actor, kActorXFixed), actorReadU32(actor, kActorYFixed),
-					actorReadU32(actor, kActorMoveDx), actorReadU32(actor, kActorMoveDy));
+					(uint32)actor.xFixed, (uint32)actor.yFixed,
+					(uint32)actor.moveDx, (uint32)actor.moveDy);
 				if (selector & 0xFF000000) {
 					uint32 pc = selector & 0x00FFFFFF;
 					int16 wordsLeft = (int16)(debugScriptReadWord(pc) - 1);
diff --git a/engines/comfy/expr.cpp b/engines/comfy/expr.cpp
index 61e3bd77b0d..d8950a88b56 100644
--- a/engines/comfy/expr.cpp
+++ b/engines/comfy/expr.cpp
@@ -61,23 +61,23 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 
 			uint16 value = 0;
 			if (opcode == 0x10)
-				value = actorReadU32(*actor, kActorXFixed) >> 12;
+				value = (uint32)actor->xFixed >> 12;
 			else if (opcode == 0x11)
-				value = actorReadU32(*actor, kActorYFixed) >> 12;
+				value = (uint32)actor->yFixed >> 12;
 			else if (opcode == 0x12 || opcode == 0x13) {
-				uint offset = opcode == 0x12 ? kActorXFixed : kActorYFixed;
-				int32 position = actorReadU32(*actor, offset);
-				while (actorReadU16(*actor, kActorParent)) {
-					actor = actorGetPtr(actorReadU16(*actor, kActorParent));
+				bool useX = opcode == 0x12;
+				int32 position = useX ? actor->xFixed : actor->yFixed;
+				while (actor->parent) {
+					actor = actorGetPtr(actor->parent);
 					if (!actor)
 						break;
 
-					position += actorReadU32(*actor, offset);
+					position = (int32)((uint32)position + (uint32)(useX ? actor->xFixed : actor->yFixed));
 				}
 
 				value = (uint16)(position >> 12);
 			} else if (opcode == 0x14)
-				value = actorReadU16(*actor, kActorSpriteSelector);
+				value = (uint16)actor->spriteSelector;
 
 			if (_exprStackTop < COMFY_EXPR_STACK_CAPACITY)
 				_exprStack[_exprStackTop++] = value;
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index d0c6e595c93..ccadb2d01e7 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -378,7 +378,9 @@ bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16
 	_midiHandles.resize(handleCount + 1);
 	memset(&_midiHandles[0], 0, _midiHandles.size() * sizeof(uint16));
 	_actors.resize(actorCount + 1);
-	memset(&_actors[0], 0, _actors.size() * sizeof(Actor));
+	for (uint i = 0; i < _actors.size(); i++)
+		_actors[i] = Actor();
+
 	if (!keyBitAllocate(keyBitCount))
 		return false;
 
@@ -391,7 +393,13 @@ bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16
 
 	uint32 stringBytes = _stringTable.size() * sizeof(uint16);
 	uint32 handleBytes = _sceneHandles.size() * sizeof(uint16);
-	uint32 actorBytes = _actors.size() * _actorSize;
+	uint32 actorRecordSize = COMFY_ACTOR_SIZE_V3;
+	if (_engineVersion == 1)
+		actorRecordSize = COMFY_ACTOR_SIZE_V1;
+	else if (_engineVersion == 2)
+		actorRecordSize = COMFY_ACTOR_SIZE_V2;
+
+	uint32 actorBytes = _actors.size() * actorRecordSize;
 	uint32 keyBytes = ((uint32)keyBitCount + 1) / 8 + 1;
 	_sceneMidiInstanceOffset = 0;
 	if (_engineVersion == 3) {
@@ -439,12 +447,12 @@ bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16
 		return false;
 
 	for (uint i = 0; i + 1 < _actors.size(); i++) {
-		actorWriteU16(_actors[i], kActorNextLink, i + 1);
-		actorWriteU16(_actors[i], kActorSceneHandle, 0);
+		_actors[i].nextLink = i + 1;
+		_actors[i].sceneHandle = 0;
 	}
 
-	actorWriteU16(_actors[_actors.size() - 1], kActorNextLink, 0);
-	actorWriteU16(_actors[_actors.size() - 1], kActorSceneHandle, 0);
+	_actors[_actors.size() - 1].nextLink = 0;
+	_actors[_actors.size() - 1].sceneHandle = 0;
 	actorSetFrame(0);
 	return true;
 }
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index 53f75596c26..d145bbf0ad4 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -22,6 +22,7 @@
 #include "comfy/comfy.h"
 
 #include "common/endian.h"
+#include "common/memstream.h"
 
 namespace Comfy {
 
@@ -137,9 +138,71 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 	if (!_sceneHandles.empty())
 		memcpy(&_sceneMemoryBlock[_sceneHandlesOffset], &_sceneHandles[0], _sceneHandles.size() * sizeof(uint16));
 
-	uint32 actorStride = _actorSize;
-	for (uint i = 0; i < _actors.size(); i++)
-		memcpy(&_sceneMemoryBlock[_sceneActorsOffset + i * actorStride], &_actors[i], actorStride);
+	uint32 actorStride = COMFY_ACTOR_SIZE_V3;
+	if (_engineVersion == 1)
+		actorStride = COMFY_ACTOR_SIZE_V1;
+	else if (_engineVersion == 2)
+		actorStride = COMFY_ACTOR_SIZE_V2;
+
+	byte *actorBuffer = (byte *)malloc(actorStride);
+	if (!actorBuffer)
+		error("Unable to allocate Actor serialization buffer");
+
+	for (uint i = 0; i < _actors.size(); i++) {
+		byte *destination = &_sceneMemoryBlock[_sceneActorsOffset + i * actorStride];
+		Actor &actor = _actors[i];
+		Common::MemoryWriteStream actorStream(actorBuffer, actorStride);
+		actorStream.writeUint32LE(actor.currentPc);
+		actorStream.writeUint32LE(actor.callPc);
+		actorStream.writeUint32LE(actor.resetPc);
+		actorStream.writeSint32LE(actor.xFixed);
+		actorStream.writeSint32LE(actor.yFixed);
+		actorStream.writeUint32LE(actor.spriteSelector);
+		actorStream.writeSint32LE(actor.moveDx);
+		actorStream.writeSint32LE(actor.moveDy);
+		actorStream.writeUint32LE(actor.triggerPc);
+		actorStream.writeUint16LE(actor.stringRefs[0]);
+		actorStream.writeUint16LE(actor.stringRefs[1]);
+		actorStream.writeUint16LE(actor.sceneHandle);
+		actorStream.writeByte(actor.visible);
+		actorStream.writeByte(actor.active);
+		actorStream.writeUint16LE(actor.parent);
+		actorStream.writeUint16LE(actor.childTail);
+		actorStream.writeUint16LE(actor.childHead);
+		actorStream.writeUint16LE(actor.siblingHead);
+		actorStream.writeUint16LE(actor.nextLink);
+		actorStream.writeUint16LE(actor.prevLink);
+		actorStream.writeUint16LE(actor.moveTicks);
+		actorStream.writeByte(actor.blockingMove);
+		actorStream.writeUint16LE(actor.completionKey);
+		actorStream.writeUint16LE(actor.triggerKey);
+		actorStream.writeByte(actor.triggerFlags);
+		actorStream.writeUint16LE(actor.waitTarget);
+		actorStream.writeUint16LE(actor.waitAccum);
+		actorStream.writeByte(actor.dirty);
+		actorStream.writeSint16LE(actor.cachedRect.left);
+		actorStream.writeSint16LE(actor.cachedRect.top);
+		actorStream.writeSint16LE(actor.cachedRect.right);
+		actorStream.writeSint16LE(actor.cachedRect.bottom);
+		if (_engineVersion == 1)
+			actorStream.writeUint16LE((uint16)(actor.cachedRect.area & 0xFFFF));
+		else
+			actorStream.writeUint32LE(actor.cachedRect.area);
+
+		actorStream.writeByte(actor.cachedVisible);
+		actorStream.writeUint32LE(actor.cachedSprite);
+		if (_engineVersion == 3)
+			actorStream.writeByte(actor.blitHitMouse);
+
+		if (actorStream.err() || actorStream.pos() != actorStride) {
+			free(actorBuffer);
+			error("Invalid serialized Actor size for engine version %u", _engineVersion);
+		}
+
+		memcpy(destination, actorBuffer, actorStride);
+	}
+
+	free(actorBuffer);
 
 	if (_keyBits && _keyBitsSize)
 		memcpy(&_sceneMemoryBlock[_sceneKeyBitsOffset], _keyBits, _keyBitsSize);
@@ -276,9 +339,72 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 	memcpy(_actorPcTable, &_sceneMemoryBlock[_sceneActorPcOffset], sizeof(_actorPcTable));
 	memcpy(&_stringTable[0], &_sceneMemoryBlock[_sceneStringTableOffset], _stringTable.size() * sizeof(uint16));
 	memcpy(&_sceneHandles[0], &_sceneMemoryBlock[_sceneHandlesOffset], _sceneHandles.size() * sizeof(uint16));
-	uint32 actorStride = _actorSize;
-	for (uint i = 0; i < _actors.size(); i++)
-		memcpy(&_actors[i], &_sceneMemoryBlock[_sceneActorsOffset + i * actorStride], actorStride);
+	uint32 actorStride = COMFY_ACTOR_SIZE_V3;
+	if (_engineVersion == 1)
+		actorStride = COMFY_ACTOR_SIZE_V1;
+	else if (_engineVersion == 2)
+		actorStride = COMFY_ACTOR_SIZE_V2;
+
+	byte *actorBuffer = (byte *)malloc(actorStride);
+	if (!actorBuffer)
+		error("Unable to allocate Actor deserialization buffer");
+
+	for (uint i = 0; i < _actors.size(); i++) {
+		byte *source = &_sceneMemoryBlock[_sceneActorsOffset + i * actorStride];
+		Actor &actor = _actors[i];
+		actor = Actor();
+		memcpy(actorBuffer, source, actorStride);
+		Common::MemoryReadStream actorStream(actorBuffer, actorStride);
+		actor.currentPc = actorStream.readUint32LE();
+		actor.callPc = actorStream.readUint32LE();
+		actor.resetPc = actorStream.readUint32LE();
+		actor.xFixed = actorStream.readSint32LE();
+		actor.yFixed = actorStream.readSint32LE();
+		actor.spriteSelector = actorStream.readUint32LE();
+		actor.moveDx = actorStream.readSint32LE();
+		actor.moveDy = actorStream.readSint32LE();
+		actor.triggerPc = actorStream.readUint32LE();
+		actor.stringRefs[0] = actorStream.readUint16LE();
+		actor.stringRefs[1] = actorStream.readUint16LE();
+		actor.sceneHandle = actorStream.readUint16LE();
+		actor.visible = actorStream.readByte();
+		actor.active = actorStream.readByte();
+		actor.parent = actorStream.readUint16LE();
+		actor.childTail = actorStream.readUint16LE();
+		actor.childHead = actorStream.readUint16LE();
+		actor.siblingHead = actorStream.readUint16LE();
+		actor.nextLink = actorStream.readUint16LE();
+		actor.prevLink = actorStream.readUint16LE();
+		actor.moveTicks = actorStream.readUint16LE();
+		actor.blockingMove = actorStream.readByte();
+		actor.completionKey = actorStream.readUint16LE();
+		actor.triggerKey = actorStream.readUint16LE();
+		actor.triggerFlags = actorStream.readByte();
+		actor.waitTarget = actorStream.readUint16LE();
+		actor.waitAccum = actorStream.readUint16LE();
+		actor.dirty = actorStream.readByte();
+		actor.cachedRect.left = actorStream.readSint16LE();
+		actor.cachedRect.top = actorStream.readSint16LE();
+		actor.cachedRect.right = actorStream.readSint16LE();
+		actor.cachedRect.bottom = actorStream.readSint16LE();
+		if (_engineVersion == 1)
+			actor.cachedRect.area = actorStream.readUint16LE();
+		else
+			actor.cachedRect.area = actorStream.readUint32LE();
+
+		actor.cachedVisible = actorStream.readByte();
+		actor.cachedSprite = actorStream.readUint32LE();
+		if (_engineVersion == 3)
+			actor.blitHitMouse = actorStream.readByte();
+
+		if (actorStream.eos() || actorStream.pos() != actorStride) {
+			free(actorBuffer);
+			error("Invalid serialized Actor size for engine version %u", _engineVersion);
+		}
+	}
+
+	free(actorBuffer);
+
 	if (_keyBits && _keyBitsSize)
 		memcpy(_keyBits, &_sceneMemoryBlock[_sceneKeyBitsOffset], _keyBitsSize);
 
@@ -333,9 +459,9 @@ void ComfyEngine::sceneStartWithMusic(uint16 scene) {
 
 	Actor *root = actorGetPtr(0);
 	if (root) {
-		paletteLoadWithFade(actorReadU16(*root, kActorXFixed), 0);
-		if (actorReadU32(*root, kActorYFixed))
-			paletteApplyBrightness((byte)actorReadU16(*root, kActorYFixed));
+		paletteLoadWithFade((uint16)root->xFixed, 0);
+		if (root->yFixed)
+			paletteApplyBrightness((byte)root->yFixed);
 	}
 
 	if (_keyBits)
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 30ad20e3201..c2517461b9b 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -46,14 +46,14 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			if (!other)
 				error("Script opcode 0x%02X resolved an invalid reference actor", opcode);
 
-			x = (int16)((int32)actorReadU32(*other, kActorXFixed) >> 12);
-			y = (int16)((int32)actorReadU32(*other, kActorYFixed) >> 12);
+			x = (int16)(other->xFixed >> 12);
+			y = (int16)(other->yFixed >> 12);
 		} else if (opcode == 0x01 && x == (int16)0xF448) {
-			x = (int16)(-(int32)actorReadU32(*target, kActorXFixed) >> 12);
+			x = (int16)(-target->xFixed >> 12);
 		}
 
 		if (opcode == 0x01 && y == (int16)0xF448)
-			y = (int16)(-(int32)actorReadU32(*target, kActorYFixed) >> 12);
+			y = (int16)(-target->yFixed >> 12);
 
 		if (randomize) {
 			if (opcode == 0x02 || x != (int16)0xFC18)
@@ -65,13 +65,13 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 		if (opcode == 0x01) {
 			if (x != (int16)0xFC18)
-				actorWriteU32(*target, kActorXFixed, (uint32)((int32)x * 0x1000));
+				target->xFixed = (int32)x * 0x1000;
 
 			if (y != (int16)0xFC18)
-				actorWriteU32(*target, kActorYFixed, (uint32)((int32)y * 0x1000));
+				target->yFixed = (int32)y * 0x1000;
 		} else {
-			actorWriteU32(*target, kActorXFixed, actorReadU32(*target, kActorXFixed) + (uint32)((int32)x * 0x1000));
-			actorWriteU32(*target, kActorYFixed, actorReadU32(*target, kActorYFixed) + (uint32)((int32)y * 0x1000));
+			target->xFixed = (int32)((uint32)target->xFixed + (uint32)((int32)x * 0x1000));
+			target->yFixed = (int32)((uint32)target->yFixed + (uint32)((int32)y * 0x1000));
 		}
 
 		return kScriptContinue;
@@ -84,7 +84,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint16 frame = scriptReadStringIndex(pc);
 		pc += 2;
 		if (target)
-			actorWriteU32(*target, kActorSpriteSelector, (uint32)(int32)(int16)frame);
+			target->spriteSelector = (uint32)(int32)(int16)frame;
 
 		return kScriptContinue;
 	}
@@ -155,7 +155,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		int16 sprite = scriptReadWord(pc);
 		pc += 2;
 		if (!parentSlot)
-			parentSlot = actorReadU16(actor, kActorSceneHandle);
+			parentSlot = actor.sceneHandle;
 
 		actorInit(sceneSlot, parentSlot, (flags & 1) != 0, (flags & 2) != 0,
 			newPc, x, y, sprite, (flags & 4) != 0);
@@ -183,17 +183,17 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 		switch (opcode) {
 		case 0x0A:
-			actorWriteU8(*target, kActorVisible, 1);
+			target->visible = 1;
 			break;
 		case 0x0B:
-			actorWriteU8(*target, kActorVisible, 0);
+			target->visible = 0;
 			break;
 		case 0x0C:
-			actorWriteU8(*target, kActorActive, 1);
+			target->active = 1;
 			break;
 		case 0x0D:
-			actorWriteU16(*target, kActorMoveTicks, 0);
-			actorWriteU8(*target, kActorActive, 0);
+			target->moveTicks = 0;
+			target->active = 0;
 			if (target == &actor)
 				return kScriptYield;
 
@@ -217,7 +217,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		if (!target)
 			error("Script opcode 0x%02X resolved an invalid actor", opcode);
 
-		int16 actual = (int32)actorReadU32(*target, opcode == 0x0E || opcode == 0x10 ? kActorXFixed : kActorYFixed) >> 12;
+		int16 actual = (opcode == 0x0E || opcode == 0x10 ? target->xFixed : target->yFixed) >> 12;
 		bool matched = ((mode & 2) && expected == actual) || ((mode & 4) && expected < actual) || ((mode & 1) && expected > actual);
 		if (matched) {
 			switch (opcode) {
@@ -273,7 +273,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			error("Script opcode 0x14 resolved an invalid actor");
 
 		uint16 targetIndex = (uint16)(target - &_actors[0]);
-		uint16 oldParent = actorReadU16(*target, kActorParent);
+		uint16 oldParent = target->parent;
 		actorUnlink(targetIndex);
 
 		if (mode == 'O')
@@ -330,14 +330,14 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		if (!target)
 			error("Script opcode 0x18 resolved an invalid actor");
 
-		uint32 resetPc = actorReadU32(*target, kActorResetPc);
-		actorWriteU32(*target, kActorCurrentPc, resetPc);
-		actorWriteU8(*target, kActorActive, 1);
-		actorWriteU16(*target, kActorWaitTarget, 0);
-		actorWriteU16(*target, kActorWaitAccum, 0);
-		if (actorReadU16(*target, kActorMoveTicks)) {
-			actorWriteU16(*target, kActorMoveTicks, 0);
-			uint16 completionKey = actorReadU16(*target, kActorCompletionKey);
+		uint32 resetPc = target->resetPc;
+		target->currentPc = resetPc;
+		target->active = 1;
+		target->waitTarget = 0;
+		target->waitAccum = 0;
+		if (target->moveTicks) {
+			target->moveTicks = 0;
+			uint16 completionKey = target->completionKey;
 			if (completionKey)
 				keyBitSet(completionKey);
 		}
@@ -429,13 +429,13 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			error("Script opcode 0x1E resolved an invalid actor");
 
 		if (key != 0xFC18)
-			actorWriteU16(*target, kActorTriggerKey, key);
+			target->triggerKey = key;
 
 		if (triggerPc != 0xFFFFFC18) {
-			actorWriteU32(*target, kActorTriggerPc, triggerPc);
-			actorWriteU8(*target, kActorTriggerFlags, flags);
+			target->triggerPc = triggerPc;
+			target->triggerFlags = flags;
 		} else {
-			actorWriteU8(*target, kActorTriggerFlags, (actorReadU8(*target, kActorTriggerFlags) & 1) | flags);
+			target->triggerFlags = (target->triggerFlags & 1) | flags;
 		}
 
 		return kScriptContinue;
@@ -541,7 +541,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint32 selector = scriptReadDword(pc + 2);
 		pc += 6;
 		if (target)
-			actorWriteU32(*target, kActorSpriteSelector, (selector + 1) | 0xFF000000);
+			target->spriteSelector = (selector + 1) | 0xFF000000;
 
 		return kScriptContinue;
 	}
@@ -638,7 +638,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			uint16 animIndex = scriptReadWord(pc);
 			uint16 frameKey = scriptReadWord(pc + 2);
 			pc += 4;
-			animFileLoadFrame(animIndex, frameKey, actorReadU16(actor, kActorSceneHandle));
+			animFileLoadFrame(animIndex, frameKey, actor.sceneHandle);
 			break;
 		}
 		case 2:
@@ -919,11 +919,11 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 				error("Script opcode 0x%02X resolved an invalid reference actor", opcode);
 
 			if (moveTo) {
-				x = (int16)((int32)actorReadU32(*other, kActorXFixed) >> 12);
-				y = (int16)((int32)actorReadU32(*other, kActorYFixed) >> 12);
+				x = (int16)(other->xFixed >> 12);
+				y = (int16)(other->yFixed >> 12);
 			} else {
-				x = (int16)actorReadU16(*other, kActorXFixed) >> 12;
-				y = (int16)actorReadU16(*other, kActorYFixed) >> 12;
+				x = (int16)(uint16)other->xFixed >> 12;
+				y = (int16)(uint16)other->yFixed >> 12;
 			}
 		}
 
@@ -938,8 +938,8 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		int32 dx = (int32)x * 0x1000;
 		int32 dy = (int32)y * 0x1000;
 		if (moveTo) {
-			dx = x == (int16)0xFC18 ? 0 : dx - (int32)actorReadU32(*target, kActorXFixed);
-			dy = y == (int16)0xFC18 ? 0 : dy - (int32)actorReadU32(*target, kActorYFixed);
+			dx = x == (int16)0xFC18 ? 0 : dx - target->xFixed;
+			dy = y == (int16)0xFC18 ? 0 : dy - target->yFixed;
 		}
 
 		if (opcode == 0x51 || opcode == 0x52 || (moveTo && duration < 0)) {
@@ -954,11 +954,11 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 				duration = 1;
 		}
 
-		actorWriteU32(*target, kActorMoveDx, dx);
-		actorWriteU32(*target, kActorMoveDy, dy);
-		actorWriteU16(*target, kActorMoveTicks, duration);
-		actorWriteU8(*target, kActorBlockingMove, blocking);
-		actorWriteU16(*target, kActorCompletionKey, completionKey);
+		target->moveDx = dx;
+		target->moveDy = dy;
+		target->moveTicks = duration;
+		target->blockingMove = blocking;
+		target->completionKey = completionKey;
 		return blocking && target == &actor ? kScriptYield : kScriptContinue;
 	}
 
@@ -982,9 +982,9 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		if (!target)
 			error("Script opcode 0x53 resolved an invalid actor");
 
-		actorWriteU32(*target, kActorSpriteSelector, (uint32)(int32)(int16)frame);
-		actorWriteU32(*target, kActorMoveDx, 0);
-		actorWriteU32(*target, kActorMoveDy, 0);
+		target->spriteSelector = (uint32)(int32)(int16)frame;
+		target->moveDx = 0;
+		target->moveDy = 0;
 		return kScriptContinue;
 	}
 
@@ -1036,17 +1036,17 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	case 0x72: {
 		uint16 requested = scriptReadStringIndex(pc);
 		pc += 2;
-		uint16 balance = actorReadU16(actor, kActorWaitAccum);
+		uint16 balance = actor.waitAccum;
 		if (!requested)
 			balance = 0;
 
 		if (balance) {
 			uint16 step = balance < 5 ? balance : 5;
 			balance = step < (uint16)(requested - 1) ? step : (uint16)(requested - 1);
-			actorWriteU16(actor, kActorWaitAccum, actorReadU16(actor, kActorWaitAccum) - balance);
+			actor.waitAccum -= balance;
 		}
 
-		actorWriteU16(actor, kActorWaitTarget, requested - balance);
+		actor.waitTarget = requested - balance;
 		return kScriptYield;
 	}
 
@@ -1143,7 +1143,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 		Actor *root = actorGetPtr(0);
 		if (root)
-			actorWriteU8(*root, kActorActive, 0);
+			root->active = 0;
 
 		return kScriptContinue;
 	}
diff --git a/engines/comfy/video.cpp b/engines/comfy/video.cpp
index 54d4559e91e..796cd4d5207 100644
--- a/engines/comfy/video.cpp
+++ b/engines/comfy/video.cpp
@@ -75,12 +75,12 @@ void ComfyEngine::videoShutdown(byte restorePalette) {
 }
 
 void ComfyEngine::videoSetResolution() {
-	VideoRectRecord record;
+	ComfyRect record;
 	record.left = 0;
 	record.top = 0;
 	record.right = _logicalScreenWidth;
 	record.bottom = _logicalScreenHeight;
-	record.area = MIN<uint32>(framebufferBytes(), 0xFFFF);
+	record.area = _engineVersion == 1 ? (uint16)framebufferBytes() : framebufferBytes();
 	videoFindBestMode(record);
 }
 
@@ -101,7 +101,10 @@ void ComfyEngine::renderInvalidateFullFrame() {
 	videoSetResolution();
 }
 
-void ComfyEngine::videoFindBestMode(VideoRectRecord record) {
+void ComfyEngine::videoFindBestMode(ComfyRect record) {
+	if (_engineVersion == 1)
+		record.area = (uint16)record.area;
+
 	record.left = CLIP<int16>(record.left, 0, _logicalScreenWidth);
 	record.top = CLIP<int16>(record.top, 0, _logicalScreenHeight);
 	record.right = CLIP<int16>(record.right, 0, _logicalScreenWidth);
@@ -114,19 +117,21 @@ void ComfyEngine::videoFindBestMode(VideoRectRecord record) {
 	}
 
 	for (int i = _resolutionChangeCount - 1; i >= 0; i--) {
-		VideoRectRecord &existing = _resolutionChanges[i];
+		ComfyRect &existing = _resolutionChanges[i];
 		if (existing.right < record.left && existing.left <= record.right &&
 				existing.bottom >= record.top && existing.top <= record.bottom)
 			continue;
 
-		VideoRectRecord merged;
+		ComfyRect merged;
 		merged.left = MIN(existing.left, record.left) / 2 * 2;
 		merged.right = (MAX(existing.right, record.right) + 1) / 2 * 2;
 		merged.top = MIN(existing.top, record.top) / 2 * 2;
 		merged.bottom = (MAX(existing.bottom, record.bottom) + 1) / 2 * 2;
 		merged.area = (uint32)(merged.right - merged.left) * (merged.bottom - merged.top);
+		if (_engineVersion == 1)
+			merged.area = (uint16)merged.area;
 
-		if ((uint32)existing.area + record.area >= merged.area) {
+		if (existing.area + record.area >= merged.area) {
 			existing = merged;
 			return;
 		}
@@ -173,7 +178,7 @@ void ComfyEngine::videoPresentFrame() {
 				_logicalScreenWidth, _logicalScreenHeight);
 		} else {
 			for (uint i = 0; i < _resolutionChangeCount; i++) {
-				VideoRectRecord &record = _resolutionChanges[i];
+				ComfyRect &record = _resolutionChanges[i];
 				int16 width = record.right - record.left;
 				int16 height = record.bottom - record.top;
 				if (width <= 0 || height <= 0)


Commit: b90a829e050073a5acfdb0b077722e312373b775
    https://github.com/scummvm/scummvm/commit/b90a829e050073a5acfdb0b077722e312373b775
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Fix dirty rects algorithm for later versions

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/anim_file.cpp
    engines/comfy/comfy.h
    engines/comfy/detection.h
    engines/comfy/detection_tables.h
    engines/comfy/video.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index fe8ad824275..cb5ec0558a1 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -485,8 +485,8 @@ void ComfyEngine::backgroundRestoreDirtyRects() {
 	if (_backgroundFramebuf.empty() || !_framebufPtr)
 		return;
 
-	for (uint i = 0; i < _resolutionChangeCount; i++) {
-		ComfyRect &rect = _resolutionChanges[i];
+	for (uint i = 0; i < _dirtyRectCount; i++) {
+		ComfyRect &rect = _dirtyRects[i];
 		int16 width = rect.right - rect.left;
 		int16 height = rect.bottom - rect.top;
 		if (width <= 0 || height <= 0)
@@ -1234,7 +1234,7 @@ uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, ComfyRect &maskRec
 			_keymaskSpriteWord = spriteId;
 		}
 
-		ComfyRect *rect = bitIndex < COMFY_RESOLUTION_CHANGE_CAPACITY ? &rects[bitIndex] : nullptr;
+		ComfyRect *rect = bitIndex < COMFY_KEYMASK_RECT_CAPACITY ? &rects[bitIndex] : nullptr;
 		if (rect) {
 			rect->left = 0;
 			rect->top = 0;
@@ -1294,8 +1294,8 @@ void ComfyEngine::actorEvalFrameSelection(uint16 actorIndex, int16 x, int16 y) {
 	} else if (selector & 0xFF000000) {
 		uint16 last = scriptEvalKeyMask(selector & 0x00FFFFFF, 0, rect, _keymaskInvalidationRects,
 			rect.left, rect.top);
-		if (last != 0xFFFF && last >= COMFY_RESOLUTION_CHANGE_CAPACITY)
-			last = COMFY_RESOLUTION_CHANGE_CAPACITY - 1;
+		if (last != 0xFFFF && last >= COMFY_KEYMASK_RECT_CAPACITY)
+			last = COMFY_KEYMASK_RECT_CAPACITY - 1;
 
 		if (last != 0xFFFF) {
 			for (uint i = 0; i <= last; i++) {
@@ -1494,8 +1494,8 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			_keymaskCurrentRecord.area = 0;
 			currentLastRect = scriptEvalKeyMask(selector & 0x00FFFFFF, 1,
 				_keymaskCurrentRecord, _keymaskRects, drawX, drawY);
-			if (currentLastRect != 0xFFFF && currentLastRect >= COMFY_RESOLUTION_CHANGE_CAPACITY)
-				currentLastRect = COMFY_RESOLUTION_CHANGE_CAPACITY - 1;
+			if (currentLastRect != 0xFFFF && currentLastRect >= COMFY_KEYMASK_RECT_CAPACITY)
+				currentLastRect = COMFY_KEYMASK_RECT_CAPACITY - 1;
 
 			newRect = _keymaskCurrentRecord;
 		} else if (selector) {
@@ -1514,8 +1514,8 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			ComfyRect oldMaskRecord = oldRect;
 			uint16 oldLastRect = scriptEvalKeyMask(oldSelector & 0x00FFFFFF, 0,
 				oldMaskRecord, _keymaskOldRects, oldRect.left, oldRect.top);
-			if (oldLastRect != 0xFFFF && oldLastRect >= COMFY_RESOLUTION_CHANGE_CAPACITY)
-				oldLastRect = COMFY_RESOLUTION_CHANGE_CAPACITY - 1;
+			if (oldLastRect != 0xFFFF && oldLastRect >= COMFY_KEYMASK_RECT_CAPACITY)
+				oldLastRect = COMFY_KEYMASK_RECT_CAPACITY - 1;
 
 			if (oldLastRect != 0xFFFF) {
 				for (uint i = 0; i <= oldLastRect; i++) {
@@ -1563,8 +1563,8 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 					ComfyRect oldMaskRecord = oldRect;
 					uint16 oldLastRect = scriptEvalKeyMask(oldSelector & 0x00FFFFFF, 0,
 						oldMaskRecord, _keymaskOldRects, oldRect.left, oldRect.top);
-					if (oldLastRect != 0xFFFF && oldLastRect >= COMFY_RESOLUTION_CHANGE_CAPACITY)
-						oldLastRect = COMFY_RESOLUTION_CHANGE_CAPACITY - 1;
+					if (oldLastRect != 0xFFFF && oldLastRect >= COMFY_KEYMASK_RECT_CAPACITY)
+						oldLastRect = COMFY_KEYMASK_RECT_CAPACITY - 1;
 
 					if (oldLastRect != 0xFFFF) {
 						for (uint i = 0; i <= oldLastRect; i++)
@@ -1607,8 +1607,8 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			_keymaskCurrentRecord.bottom = 0;
 			_keymaskCurrentRecord.area = 0;
 			scriptedLastRect = scriptEvalKeyMask(pc, 1, _keymaskCurrentRecord, _keymaskRects, drawX, drawY);
-			if (scriptedLastRect != 0xFFFF && scriptedLastRect >= COMFY_RESOLUTION_CHANGE_CAPACITY)
-				scriptedLastRect = COMFY_RESOLUTION_CHANGE_CAPACITY - 1;
+			if (scriptedLastRect != 0xFFFF && scriptedLastRect >= COMFY_KEYMASK_RECT_CAPACITY)
+				scriptedLastRect = COMFY_KEYMASK_RECT_CAPACITY - 1;
 
 			if (_usesAnimFile && visible && scriptedLastRect != 0xFFFF) {
 				for (uint i = 0; i <= scriptedLastRect; i++) {
@@ -1712,8 +1712,8 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			ComfyRect maskRecord = oldRect;
 			oldScriptedLastRect = scriptEvalKeyMask(oldSelector & 0x00FFFFFF, 0, maskRecord,
 				_keymaskOldRects, oldRect.left, oldRect.top);
-			if (oldScriptedLastRect != 0xFFFF && oldScriptedLastRect >= COMFY_RESOLUTION_CHANGE_CAPACITY)
-				oldScriptedLastRect = COMFY_RESOLUTION_CHANGE_CAPACITY - 1;
+			if (oldScriptedLastRect != 0xFFFF && oldScriptedLastRect >= COMFY_KEYMASK_RECT_CAPACITY)
+				oldScriptedLastRect = COMFY_KEYMASK_RECT_CAPACITY - 1;
 		}
 
 		if (changed) {
diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
index 714c9b7c3d3..20a6a6b4c02 100644
--- a/engines/comfy/anim_file.cpp
+++ b/engines/comfy/anim_file.cpp
@@ -562,9 +562,9 @@ bool ComfyEngine::animFrameBlitAt(int16 x, int16 y) {
 	if (!animFrameGetDimensions(frameWidth, frameHeight))
 		return false;
 
-	uint16 rectCount = _resolutionChangeCount;
+	uint16 rectCount = _dirtyRectCount;
 	for (uint i = 0; i < rectCount; i++) {
-		ComfyRect &dirtyRect = _resolutionChanges[i];
+		ComfyRect &dirtyRect = _dirtyRects[i];
 		int16 left = MAX<int16>(dirtyRect.left, x);
 		int16 top = MAX<int16>(dirtyRect.top, y);
 		int16 right = MIN<int16>(dirtyRect.right, x + frameWidth);
@@ -619,8 +619,8 @@ bool ComfyEngine::animFrameCoversPoint(int16 x, int16 y, int16 pointX, int16 poi
 		return false;
 
 	bool dirty = false;
-	for (uint i = 0; i < _resolutionChangeCount; i++) {
-		ComfyRect &dirtyRect = _resolutionChanges[i];
+	for (uint i = 0; i < _dirtyRectCount; i++) {
+		ComfyRect &dirtyRect = _dirtyRects[i];
 		if (pointX >= dirtyRect.left && pointX < dirtyRect.right &&
 				pointY >= dirtyRect.top && pointY < dirtyRect.bottom) {
 			dirty = true;
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index f3185905096..1dc82865008 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -49,7 +49,9 @@ class QueuingAudioStream;
 #define COMFY_PANTHER_SCREEN_HEIGHT 480
 #define COMFY_PIT_INPUT_FREQUENCY 1193182
 #define COMFY_PIT_TIMER_DIVISOR 0x2E9B
-#define COMFY_RESOLUTION_CHANGE_CAPACITY 100
+#define COMFY_DIRTY_RECT_CAPACITY_V1 100
+#define COMFY_DIRTY_RECT_CAPACITY 200
+#define COMFY_KEYMASK_RECT_CAPACITY 100
 #define COMFY_DRAW_COMMAND_CAPACITY 200
 #define COMFY_PALETTE_BYTES 0x300
 #define COMFY_INPUT_QUEUE_CAPACITY 20
@@ -448,8 +450,8 @@ private:
 	uint16 _renderHeight = 0;
 	int16 _viewOffsetX = 0;
 	int16 _viewOffsetY = 0;
-	ComfyRect _resolutionChanges[COMFY_RESOLUTION_CHANGE_CAPACITY];
-	uint16 _resolutionChangeCount = 0;
+	ComfyRect _dirtyRects[COMFY_DIRTY_RECT_CAPACITY];
+	uint16 _dirtyRectCount = 0;
 	uint16 _renderDirtyCount = 0;
 	bool _renderInterleaved = false;
 	Common::SeekableReadStream *_colorDatStream = nullptr;
@@ -553,9 +555,9 @@ private:
 	int16 _keymaskX = 0;
 	int16 _keymaskY = 0;
 	ComfyRect _keymaskCurrentRecord;
-	ComfyRect _keymaskRects[COMFY_RESOLUTION_CHANGE_CAPACITY];
-	ComfyRect _keymaskOldRects[COMFY_RESOLUTION_CHANGE_CAPACITY];
-	ComfyRect _keymaskInvalidationRects[COMFY_RESOLUTION_CHANGE_CAPACITY];
+	ComfyRect _keymaskRects[COMFY_KEYMASK_RECT_CAPACITY];
+	ComfyRect _keymaskOldRects[COMFY_KEYMASK_RECT_CAPACITY];
+	ComfyRect _keymaskInvalidationRects[COMFY_KEYMASK_RECT_CAPACITY];
 	ComfyRect _animFrameDirtyRects[COMFY_ANIM_DIRTY_RECT_CAPACITY];
 	uint16 _animFrameDirtyRectCount = 0;
 	DrawCommand _drawCommands[COMFY_DRAW_COMMAND_CAPACITY];
@@ -748,6 +750,7 @@ private:
 	void videoShutdown(byte restorePalette);
 	void videoSetResolution();
 	void videoFindBestMode(ComfyRect record);
+	void renderAddDirtyRectMerged(ComfyRect record);
 	void videoPresentFrame();
 	void renderSetDirty();
 	void renderFlushDirty();
diff --git a/engines/comfy/detection.h b/engines/comfy/detection.h
index cf3799dd30e..17f07a632e2 100644
--- a/engines/comfy/detection.h
+++ b/engines/comfy/detection.h
@@ -46,6 +46,7 @@ struct ComfyGameDescription {
 	ADGameDescription desc;
 	byte version;
 	byte scriptFeatures;
+	uint16 dirtyRectMergeThreshold;
 };
 
 #define COMFY_SCRIPT_OPCODE_31 (1 << 0)
diff --git a/engines/comfy/detection_tables.h b/engines/comfy/detection_tables.h
index 1146d9769c8..3a9a2eda169 100644
--- a/engines/comfy/detection_tables.h
+++ b/engines/comfy/detection_tables.h
@@ -47,6 +47,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		1,
+		0,
 		0
 	},
 
@@ -65,7 +66,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		3,
-		0
+		0,
+		0x100
 	},
 
 	{
@@ -81,7 +83,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		2,
-		COMFY_SCRIPT_OPCODE_31
+		COMFY_SCRIPT_OPCODE_31,
+		0x100
 	},
 
 	{
@@ -96,7 +99,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		2,
-		COMFY_SCRIPT_OPCODE_31 | COMFY_SCRIPT_OPCODE_33
+		COMFY_SCRIPT_OPCODE_31 | COMFY_SCRIPT_OPCODE_33,
+		0x100
 	},
 
 	{
@@ -111,6 +115,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		1,
+		0,
 		0
 	},
 
@@ -126,7 +131,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		2,
-		0
+		0,
+		0x40
 	},
 
 	{
@@ -142,7 +148,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		3,
-		0
+		0,
+		0x100
 	},
 
 	{
@@ -158,7 +165,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		3,
-		0
+		0,
+		0x100
 	},
 
 	{
@@ -174,7 +182,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
 		},
 		3,
-		0
+		0,
+		0x100
 	},
 
 	{
@@ -190,10 +199,11 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
 		},
 		2,
-		COMFY_SCRIPT_OPCODE_31 | COMFY_SCRIPT_OPCODE_32
+		COMFY_SCRIPT_OPCODE_31 | COMFY_SCRIPT_OPCODE_32,
+		0x40
 	},
 
-	{ AD_TABLE_END_MARKER, 0, 0 }
+	{ AD_TABLE_END_MARKER, 0, 0, 0 }
 };
 
 } // End of namespace Comfy
diff --git a/engines/comfy/video.cpp b/engines/comfy/video.cpp
index 796cd4d5207..3315958cd15 100644
--- a/engines/comfy/video.cpp
+++ b/engines/comfy/video.cpp
@@ -49,7 +49,7 @@ void ComfyEngine::videoInit() {
 		_backgroundFramebuf.resize(framebufferBytes());
 
 	_backgroundFrame = 0;
-	_resolutionChangeCount = 0;
+	_dirtyRectCount = 0;
 	_renderDirtyCount = 0;
 	videoSetResolution();
 	videoPresentFrame();
@@ -69,7 +69,7 @@ void ComfyEngine::videoShutdown(byte restorePalette) {
 	_backgroundFrame = 0;
 	delete _screen;
 	_screen = nullptr;
-	_resolutionChangeCount = 0;
+	_dirtyRectCount = 0;
 	_renderDirtyCount = 0;
 	_videoInitialized = false;
 }
@@ -89,7 +89,7 @@ void ComfyEngine::renderSetDirty() {
 }
 
 void ComfyEngine::renderFlushDirty() {
-	_resolutionChangeCount = 0;
+	_dirtyRectCount = 0;
 	if (_renderDirtyCount) {
 		_renderDirtyCount--;
 		videoSetResolution();
@@ -101,7 +101,117 @@ void ComfyEngine::renderInvalidateFullFrame() {
 	videoSetResolution();
 }
 
+void ComfyEngine::renderAddDirtyRectMerged(ComfyRect record) {
+	int16 alignment = _isPanther ? 4 : 2;
+	uint32 mergeThreshold = _game->dirtyRectMergeThreshold;
+	record.left = CLIP<int16>(record.left, 0, _logicalScreenWidth);
+	record.left = record.left / alignment * alignment;
+	record.top = CLIP<int16>(record.top, 0, _logicalScreenHeight);
+	record.right = CLIP<int16>(record.right, 0, _logicalScreenWidth);
+	record.right = (record.right + alignment - 1) / alignment * alignment;
+	record.right = MIN<int16>(record.right, _logicalScreenWidth);
+	record.bottom = CLIP<int16>(record.bottom, 0, _logicalScreenHeight);
+	record.area = (uint32)((int32)(record.right - record.left) * (record.bottom - record.top));
+	if (!record.area)
+		return;
+
+	if (_dirtyRectCount >= COMFY_DIRTY_RECT_CAPACITY) {
+		renderFlushDirty();
+		videoSetResolution();
+		return;
+	}
+
+	for (int i = _dirtyRectCount - 1; i >= 0; i--) {
+		ComfyRect &existing = _dirtyRects[i];
+		if (existing.right <= record.left || existing.left >= record.right ||
+				existing.bottom <= record.top || existing.top >= record.bottom)
+			continue;
+
+		ComfyRect merged;
+		merged.left = MIN(existing.left, record.left) / alignment * alignment;
+		merged.top = MIN(existing.top, record.top);
+		merged.right = (MAX(existing.right, record.right) + alignment - 1) / alignment * alignment;
+		merged.bottom = MAX(existing.bottom, record.bottom);
+		merged.area = (uint32)((int32)(merged.right - merged.left) * (merged.bottom - merged.top));
+
+		ComfyRect intersection;
+		intersection.left = (MAX(existing.left, record.left) + alignment - 1) / alignment * alignment;
+		intersection.top = MAX(existing.top, record.top);
+		intersection.right = MIN(existing.right, record.right) / alignment * alignment;
+		intersection.bottom = MIN(existing.bottom, record.bottom);
+		intersection.area = (uint32)((int32)(intersection.right - intersection.left) *
+			(intersection.bottom - intersection.top));
+
+		uint32 extraArea = merged.area + intersection.area - record.area - existing.area;
+		if (extraArea < mergeThreshold) {
+			_dirtyRectCount--;
+			_dirtyRects[i] = _dirtyRects[_dirtyRectCount];
+			renderAddDirtyRectMerged(merged);
+			return;
+		}
+
+		if (intersection.area <= mergeThreshold)
+			continue;
+
+		ComfyRect *upperRect;
+		ComfyRect *lowerRect;
+		if (existing.top > record.top) {
+			upperRect = &record;
+			lowerRect = &existing;
+		} else {
+			upperRect = &existing;
+			lowerRect = &record;
+		}
+
+		ComfyRect *bottomRect = existing.bottom < record.bottom ? &record : &existing;
+		ComfyRect upperStrip;
+		upperStrip.left = upperRect->left;
+		upperStrip.top = upperRect->top;
+		upperStrip.right = upperRect->right;
+		upperStrip.bottom = lowerRect->top;
+		upperStrip.area = (uint32)((int32)(upperStrip.right - upperStrip.left) *
+			(upperStrip.bottom - upperStrip.top));
+
+		ComfyRect middleStrip;
+		middleStrip.left = MIN(lowerRect->left, upperRect->left);
+		middleStrip.top = lowerRect->top;
+		middleStrip.right = MAX(lowerRect->right, upperRect->right);
+		middleStrip.bottom = MIN(lowerRect->bottom, upperRect->bottom);
+		middleStrip.area = (uint32)((int32)(middleStrip.right - middleStrip.left) *
+			(middleStrip.bottom - middleStrip.top));
+
+		ComfyRect bottomStrip;
+		bottomStrip.left = bottomRect->left;
+		bottomStrip.top = middleStrip.bottom;
+		bottomStrip.right = bottomRect->right;
+		bottomStrip.bottom = bottomRect->bottom;
+		bottomStrip.area = (uint32)((int32)(bottomStrip.right - bottomStrip.left) *
+			(bottomStrip.bottom - bottomStrip.top));
+
+		_dirtyRectCount--;
+		_dirtyRects[i] = _dirtyRects[_dirtyRectCount];
+		if (upperStrip.area)
+			renderAddDirtyRectMerged(upperStrip);
+
+		if (middleStrip.area)
+			renderAddDirtyRectMerged(middleStrip);
+
+		if (bottomStrip.area)
+			renderAddDirtyRectMerged(bottomStrip);
+
+		return;
+	}
+
+	_dirtyRects[_dirtyRectCount] = record;
+	_dirtyRectCount++;
+}
+
 void ComfyEngine::videoFindBestMode(ComfyRect record) {
+	if (_engineVersion >= 2) {
+		renderAddDirtyRectMerged(record);
+		return;
+	}
+
 	if (_engineVersion == 1)
 		record.area = (uint16)record.area;
 
@@ -110,14 +220,14 @@ void ComfyEngine::videoFindBestMode(ComfyRect record) {
 	record.right = CLIP<int16>(record.right, 0, _logicalScreenWidth);
 	record.bottom = CLIP<int16>(record.bottom, 0, _logicalScreenHeight);
 
-	if (_resolutionChangeCount >= COMFY_RESOLUTION_CHANGE_CAPACITY) {
+	if (_dirtyRectCount >= COMFY_DIRTY_RECT_CAPACITY_V1) {
 		renderFlushDirty();
 		videoSetResolution();
 		return;
 	}
 
-	for (int i = _resolutionChangeCount - 1; i >= 0; i--) {
-		ComfyRect &existing = _resolutionChanges[i];
+	for (int i = _dirtyRectCount - 1; i >= 0; i--) {
+		ComfyRect &existing = _dirtyRects[i];
 		if (existing.right < record.left && existing.left <= record.right &&
 				existing.bottom >= record.top && existing.top <= record.bottom)
 			continue;
@@ -137,8 +247,8 @@ void ComfyEngine::videoFindBestMode(ComfyRect record) {
 		}
 	}
 
-	_resolutionChanges[_resolutionChangeCount] = record;
-	_resolutionChangeCount++;
+	_dirtyRects[_dirtyRectCount] = record;
+	_dirtyRectCount++;
 }
 
 void ComfyEngine::framebufCopyAll(byte *destination, byte *source) {
@@ -169,16 +279,18 @@ void ComfyEngine::videoPresentFrame() {
 			_logicalScreenWidth, _logicalScreenHeight);
 	} else {
 		uint32 dirtyArea = 0;
-		for (uint i = 0; i < _resolutionChangeCount; i++)
-			dirtyArea += _resolutionChanges[i].area;
+		if (_engineVersion == 1) {
+			for (uint i = 0; i < _dirtyRectCount; i++)
+				dirtyArea += _dirtyRects[i].area;
+		}
 
-		if (dirtyArea > framebufferBytes() - 1000) {
+		if (_engineVersion == 1 && dirtyArea > framebufferBytes() - 1000) {
 			framebufCopyAll(_presentBuffer, _framebufPtr);
 			_screen->copyRectToSurface(_presentBuffer, _logicalScreenWidth, 0, 0,
 				_logicalScreenWidth, _logicalScreenHeight);
 		} else {
-			for (uint i = 0; i < _resolutionChangeCount; i++) {
-				ComfyRect &record = _resolutionChanges[i];
+			for (uint i = 0; i < _dirtyRectCount; i++) {
+				ComfyRect &record = _dirtyRects[i];
 				int16 width = record.right - record.left;
 				int16 height = record.bottom - record.top;
 				if (width <= 0 || height <= 0)


Commit: 73cc3da98131ae5babe10b75052c10f3db4edce0
    https://github.com/scummvm/scummvm/commit/73cc3da98131ae5babe10b75052c10f3db4edce0
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Implement original memory allocation and asset reading routines

Changed paths:
  A engines/comfy/memory.cpp
  A engines/comfy/object_file.cpp
    engines/comfy/actor.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/debug.cpp
    engines/comfy/game.cpp
    engines/comfy/midi.cpp
    engines/comfy/module.mk
    engines/comfy/scene.cpp
    engines/comfy/script.cpp
    engines/comfy/script_vm.cpp
    engines/comfy/sound.cpp
    engines/comfy/video.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index cb5ec0558a1..8791bfc11cc 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -160,14 +160,34 @@ void ComfyEngine::objHdrReadFromXms(byte *destination, uint32 base, uint16 size,
 	if (!destination)
 		return;
 
-	uint32 offset = base + (uint32)size * row;
-	if (offset > _headerXmsData.size() || size > _headerXmsData.size() - offset)
+	uint16 transferSize = size + (size & 1);
+	byte *source = (byte *)malloc(transferSize);
+	if (!source)
 		error("Headers move (XMS->memory)");
 
-	memcpy(destination, &_headerXmsData[offset], size);
+	XmsMove move;
+	move.length = transferSize;
+	move.sourceHandle = _xmsHeaderHandle;
+	move.sourceOffset = base + (uint32)size * row;
+	move.destinationMemory = source;
+	if (xmsTransfer(move) < 0) {
+		free(source);
+		error("Headers move (XMS->memory)");
+	}
+
+	memcpy(destination, source, size);
+	free(source);
 }
 
-void ComfyEngine::objHdrRead(SpriteObjectHeader &destination, uint16 index) {
+uint32 ComfyEngine::frameLoaderGetFrameDataSize(SpriteObjectHeader &header) {
+	uint32 size = (uint16)header.dataSize;
+	if (_engineVersion == 3 && (header.reserved & 0x80))
+		size += 0x10000;
+
+	return size;
+}
+
+void ComfyEngine::frameLoaderLoadFrameHeader(SpriteObjectHeader &destination, uint16 index) {
 	byte raw[0x11];
 	memset(raw, 0, sizeof(raw));
 	objHdrReadFromXms(raw, _headerXmsObjectTableBase, sizeof(raw), index);
@@ -179,6 +199,9 @@ void ComfyEngine::objHdrRead(SpriteObjectHeader &destination, uint16 index) {
 	destination.hotspotY = (int16)READ_LE_UINT16(raw + 0x0C);
 	destination.reserved = raw[0x0E];
 	destination.tiledSize = READ_LE_UINT16(raw + 0x0F);
+	if (_engineVersion == 3)
+		destination.dataSize = frameLoaderGetFrameDataSize(destination);
+
 	_spriteLastHeader = destination;
 }
 
@@ -243,11 +266,14 @@ void ComfyEngine::spriteCache(int16 spriteId) {
 	if (spriteId < 0) {
 		uint16 frameId = (uint16)-spriteId;
 		uint32 fileOffset = (uint32)(frameId - 1) * COMFY_TILE_SIZE;
-		if (fileOffset >= _picDataSize || fileOffset >= _comfyObjData.size())
+		if (fileOffset >= _picDataSize || !_comfyObjFile)
+			return;
+
+		uint32 size = MIN<uint32>(COMFY_TILE_SIZE, _picDataSize - fileOffset);
+		byte *source = objFileReadTiled(fileOffset, size, _comfyObjFile);
+		if (!source)
 			return;
 
-		uint32 size = MIN<uint32>(COMFY_TILE_SIZE,
-			MIN<uint32>(_picDataSize - fileOffset, _comfyObjData.size() - fileOffset));
 		uint16 slotSize = (uint16)(size + (size & 1) + 0x0C);
 		scenePoolReserveSlot((uint32)slotSize + 2);
 		if (_scenePoolCursor > _scenePoolData.size() || slotSize > _scenePoolData.size() - _scenePoolCursor)
@@ -256,7 +282,7 @@ void ComfyEngine::spriteCache(int16 spriteId) {
 		byte *entryData = &_scenePoolData[_scenePoolCursor];
 		WRITE_LE_UINT16(entryData, (uint16)spriteId);
 		WRITE_LE_UINT16(entryData + 2, slotSize);
-		memcpy(entryData + 0x0C, &_comfyObjData[fileOffset], size);
+		memcpy(entryData + 0x0C, source, size);
 		_frameSpriteResource.id = frameId;
 		_frameSpriteResource.header = SpriteObjectHeader();
 		_frameSpriteResource.header.dataSize = size;
@@ -287,13 +313,17 @@ void ComfyEngine::spriteCache(int16 spriteId) {
 	spriteInvalidateHostCache(sprite);
 
 	SpriteObjectHeader header;
-	objHdrRead(header, spriteId);
+	frameLoaderLoadFrameHeader(header, spriteId);
 	sprite.header = header;
-	if (!header.dataSize || header.fileOffset > _picFileData.size() ||
-			header.dataSize > _picFileData.size() - header.fileOffset)
+	if (!header.dataSize || !_picFile)
+		return;
+
+	byte *source = _engineVersion == 3 ?
+		frameLoaderReadFrameData(header.fileOffset, header.dataSize, _picFile) :
+		objFileReadTiled(header.fileOffset, header.dataSize, _picFile);
+	if (!source)
 		return;
 
-	byte *source = &_picFileData[header.fileOffset];
 	if (header.width == _logicalScreenWidth && header.height == _logicalScreenHeight) {
 		sprite.pixels.resize(header.dataSize);
 		memcpy(&sprite.pixels[0], source, header.dataSize);
@@ -333,7 +363,7 @@ ComfyEngine::SpriteResource *ComfyEngine::spriteLookup(uint16 spriteId, int16 x,
 	SpriteCacheEntry *entry = spriteId < _objectCacheEntries.size() ? &_objectCacheEntries[spriteId] : nullptr;
 	if (entry && entry->slotSize == 0xFFFF) {
 		SpriteObjectHeader header;
-		objHdrRead(header, spriteId);
+		frameLoaderLoadFrameHeader(header, spriteId);
 		sprite.header = header;
 	}
 
@@ -348,6 +378,11 @@ ComfyEngine::SpriteResource *ComfyEngine::spriteLookup(uint16 spriteId, int16 x,
 	if (entry && entry->slotSize == 0xFFFF && !fullscreen && offscreen) {
 		_objFileOffset = _spriteLastHeader.fileOffset;
 		_objFileStride = _spriteLastHeader.tiledSize;
+		if (_engineVersion == 3)
+			frameLoaderReadFrameData(sprite.header.fileOffset, sprite.header.dataSize, _picFile);
+		else
+			objFileReadTiled(sprite.header.fileOffset, sprite.header.dataSize, _picFile);
+
 		return nullptr;
 	}
 
@@ -400,11 +435,11 @@ void ComfyEngine::spriteGetConvPtr(int16 spriteId) {
 		}
 	} else {
 		SpriteObjectHeader header;
-		objHdrRead(header, (uint16)spriteId);
+		frameLoaderLoadFrameHeader(header, (uint16)spriteId);
 		width = header.width;
-		if (header.fileOffset <= _picFileData.size() &&
-				header.dataSize <= _picFileData.size() - header.fileOffset)
-			payload = &_picFileData[header.fileOffset];
+		payload = _engineVersion == 3 ?
+			frameLoaderReadFrameData(header.fileOffset, header.dataSize, _picFile) :
+			objFileReadTiled(header.fileOffset, header.dataSize, _picFile);
 	}
 
 	if (!payload || width != 0xFFFF)
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index fbd34fb1c0f..482a0e072c6 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -223,7 +223,7 @@ uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
 	hostKeyboardLoadDatMap();
 
 	if (_sceneRunBuffer.empty()) {
-		_sceneRunBuffer.resize(0x10010);
+		_sceneRunBuffer.resize(_isPanther || _engineVersion == 3 ? 0x20010 : 0x10010);
 		memset(&_sceneRunBuffer[0], 0, _sceneRunBuffer.size());
 	}
 
@@ -261,7 +261,7 @@ uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
 	if (exitFlag || shouldStartNext)
 		restorePalette = 0;
 
-	if (_engineVersion == 3)
+	if (_isPanther || _engineVersion == 3)
 		animFileShutdown();
 
 	midiShutdown();
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 1dc82865008..b4efe3e9cd7 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -96,6 +96,7 @@ class QueuingAudioStream;
 #define COMFY_ANM_STATE_BYTES 0x68
 #define COMFY_PANTHER_ANM_STATE_BYTES 0x67
 #define COMFY_ANIM_DIRTY_RECT_CAPACITY 0x3C
+#define COMFY_XMS_HANDLE_CAPACITY 12
 
 namespace Comfy {
 
@@ -180,7 +181,7 @@ private:
 
 	struct SpriteObjectHeader {
 		uint32 fileOffset;
-		uint16 dataSize;
+		uint32 dataSize;
 		uint16 width;
 		uint16 height;
 		int16 hotspotX;
@@ -347,6 +348,83 @@ private:
 		uint32 counterThreshold;
 	};
 
+	struct XmsBlock {
+		byte *data;
+		uint32 size;
+
+		XmsBlock() {
+			data = nullptr;
+			size = 0;
+		}
+	};
+
+	struct XmsMove {
+		uint32 length;
+		uint16 sourceHandle;
+		uint32 sourceOffset;
+		uint16 destinationHandle;
+		uint32 destinationOffset;
+		const byte *sourceMemory;
+		byte *destinationMemory;
+
+		XmsMove() {
+			length = 0;
+			sourceHandle = 0;
+			sourceOffset = 0;
+			destinationHandle = 0;
+			destinationOffset = 0;
+			sourceMemory = nullptr;
+			destinationMemory = nullptr;
+		}
+	};
+
+	struct ObjFileCacheRow {
+		uint16 tileIndex;
+		uint16 frameIndex;
+		uint16 previousIndex;
+		uint16 previousValid;
+		uint16 nextIndex;
+		uint16 nextValid;
+	};
+
+	struct ObjFile {
+		Common::SeekableReadStream *stream;
+		Common::Path path;
+		uint32 fileSize;
+		uint16 cacheXmsHandle;
+		byte *readBuffer;
+		uint32 readBufferSize;
+		byte *tileReadBuffer;
+		uint16 blockSize;
+		uint16 cacheRowCount;
+		uint16 currentBlock;
+		uint16 *tileStatus;
+		uint16 tileStatusCount;
+		ObjFileCacheRow *cacheRows;
+		uint16 tileLruTail;
+		uint16 tileLruTailValid;
+		uint32 trackedSize;
+
+		ObjFile() {
+			stream = nullptr;
+			path = Common::Path();
+			fileSize = 0;
+			cacheXmsHandle = 0;
+			readBuffer = nullptr;
+			readBufferSize = 0;
+			tileReadBuffer = nullptr;
+			blockSize = 0;
+			cacheRowCount = 0;
+			currentBlock = 0;
+			tileStatus = nullptr;
+			tileStatusCount = 0;
+			cacheRows = nullptr;
+			tileLruTail = 0;
+			tileLruTailValid = 0;
+			trackedSize = 0;
+		}
+	};
+
 	// Serialized Actor strides are 0x54 in version 1, 0x56 in version 2, and 0x57 in version 3.
 	// Version 1 stores cachedRect.area as a word; later versions use a dword, and version 3 adds blitHitMouse.
 	// This is a host representation; XMS state serializes each field explicitly instead of copying this layout.
@@ -505,9 +583,10 @@ private:
 	bool _inputKeyboardPulseLatched = false;
 	uint32 _inputKeyboardPulseTime = 0;
 	bool _keyboardUiVisible = true;
-	Common::Array<byte> _comfyObjData;
-	Common::Array<byte> _picFileData;
-	Common::Array<byte> _midiFileData;
+	ObjFile *_comfyObjFile = nullptr;
+	ObjFile *_picFile = nullptr;
+	ObjFile *_vocFile = nullptr;
+	Common::SeekableReadStream *_midiFileStream = nullptr;
 	Common::Array<SpriteObjectHeader> _spriteHeaders;
 	Common::Array<SpriteResource> _spriteResources;
 	SpriteResource _frameSpriteResource;
@@ -534,9 +613,14 @@ private:
 	byte *_sceneRunPtr = nullptr;
 	Common::Array<byte> _scenePoolData;
 	Common::Array<byte> _frameLoaderData;
-	Common::Array<byte> _environmentData;
-	Common::Array<byte> _headerXmsData;
 	Common::Array<byte> _sceneFrameData;
+	XmsBlock _xmsBlocks[COMFY_XMS_HANDLE_CAPACITY];
+	uint16 _xmsBlockCount = 0;
+	uint32 _memAllocTotal = 0;
+	uint32 _tilesRead = 0;
+	uint32 _stripsDrawn = 0;
+	uint16 _xmsEnvHandle = 0;
+	uint16 _xmsHeaderHandle = 0;
 	Common::Array<SpriteCacheEntry> _objectCacheEntries;
 	Common::Array<SpriteCacheEntry> _frameCacheEntries;
 	ResourceLoadList _spriteConversionLoads;
@@ -654,7 +738,6 @@ private:
 	MidiQueue _midiTracks;
 	MidiChannelState _midiChannels[COMFY_MIDI_CHANNEL_COUNT];
 	uint32 _midiInstanceTrackBase = 1;
-	Common::Array<byte> _vocFileData;
 	Common::Array<SoundCue> _soundCues;
 	SoundDecoderState *_soundDecoderState = nullptr;
 	Audio::SoundHandle _soundHandle;
@@ -802,29 +885,61 @@ private:
 	void lptKeyboardDispatchEvents(uint32 scanState);
 	void setKeyboardContact(uint16 contact, bool pressed, bool keymapper);
 	bool readAssetFile(const Common::Path &filename, Common::Array<byte> &data);
+	int32 memAllocTrack(uint16 pages);
+	int32 memAllocTrackFar(uint16 pages);
+	int32 memFreeTrack(uint16 handle);
+	int32 memFreeTrackFar(uint16 handle);
+	uint16 sysGetExtMemKB();
+	uint32 memCompactAndCheck(uint32 minimumBytes);
+	bool memIsReady();
+	uint32 memGetFreeKB();
+	uint32 memGetFreeKBThunk();
+	uint32 memGetXmsLimit();
+	uint32 memGetXmsLimitFar();
+	int32 xmsCopyToConv(XmsMove &move);
+	int32 xmsTransfer(XmsMove &move);
+	void xmsReset();
+	ObjFileCacheRow *tileListEvictTail(ObjFile *objectFile);
+	ObjFileCacheRow *tileListAlloc(ObjFile *objectFile);
+	void tileListRemove(ObjFile *objectFile, uint16 index);
+	uint16 tileListRemoveRange(ObjFile *objectFile, uint16 first, uint16 last);
+	void tileUploadToXms(ObjFile *objectFile, const byte *source, uint16 size, uint32 destinationOffset);
+	void tileCopyXmsPair(ObjFile *objectFile, byte *destination, uint32 sourceOffset, uint32 size);
+	uint16 tileDrawStrip(ObjFile *objectFile, byte *destination, uint16 cacheRow, uint16 sourceColumn, uint32 width);
+	void tileLoadAndDraw(ObjFile *objectFile, const byte *source, uint16 tileId);
+	void frameLoaderLoadTileCore(ObjFile *objectFile, const byte *source, uint16 tileId);
+	void frameLoaderLoadTile(ObjFile *objectFile, uint16 tileId);
+	byte *frameLoaderReadFrameData(uint32 sourceOffset, uint32 byteCount, ObjFile *objectFile);
+	void objFileReadRow(byte *destination, uint16 row, uint16 count, uint16 size, ObjFile *objectFile);
+	void objFileReadFieldCore(byte *destination, uint32 sourceOffset, uint32 byteCount, ObjFile *objectFile);
+	byte *objFileReadTiledCore(uint32 sourceOffset, uint32 byteCount, ObjFile *objectFile);
+	void objFileReadField(byte *destination, uint32 sourceOffset, uint32 byteCount, ObjFile *objectFile);
+	byte *objFileReadTiled(uint32 sourceOffset, uint32 byteCount, ObjFile *objectFile);
+	ObjFile *objFileLoadSoundData(const Common::Path &path, uint16 blockSize, uint32 maximumBytes);
+	void soundBufFree(ObjFile *&objectFile);
 	uint32 assetsAlignEven32(uint32 value);
-	uint16 assetsReadLe16At(Common::Array<byte> &data, uint32 offset);
-	uint32 assetsReadLe32At(Common::Array<byte> &data, uint32 offset);
-	int32 assetsXmsCopy(byte *destination, uint32 destinationSize, uint32 destinationOffset,
-		const byte *source, uint32 sourceSize, uint32 sourceOffset, uint32 size);
+	void stringTableSetCount(uint16 count);
+	uint16 stringTableGetSize();
 	bool selPoolInit();
 	void selPoolFree();
 	bool assetsLoad(uint32 budget, byte *scenePtr);
 	void assetsUnload(byte freeAudio);
 	bool sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount,
 		uint16 handleCount, uint32 &numSprites);
+	bool sceneFrameInitTables(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount,
+		uint16 handleCount, uint32 &numSprites);
 	void midiShutdown();
-	bool comfyObjOpen();
-	bool picFileOpen();
-	bool midiFileOpen();
+	void midiFileGetTileParams(uint16 *entryCount, uint16 *entrySize);
 	void midiFileReadEntries(byte *destination);
 	byte *soundReadTiledData();
 	void soundGetTileParams(uint16 *entryCount, uint16 *entrySize);
+	bool soundOpenVocFile();
 	void spriteCache(int16 spriteId);
 	SpriteResource *spriteLookup(uint16 spriteId, int16 x, int16 y);
 	void spriteInvalidateHostCache(SpriteResource &sprite);
 	void objHdrReadFromXms(byte *destination, uint32 base, uint16 size, uint16 row);
-	void objHdrRead(SpriteObjectHeader &destination, uint16 index);
+	void frameLoaderLoadFrameHeader(SpriteObjectHeader &destination, uint16 index);
+	uint32 frameLoaderGetFrameDataSize(SpriteObjectHeader &header);
 	void scenePoolEvict();
 	void scenePoolReserveSlot(uint32 size);
 	SpriteResource *spriteGetPtr(int16 spriteId);
@@ -847,7 +962,6 @@ private:
 	void sceneGoto(uint16 count);
 	void sceneStop();
 	bool sceneEntryLoad(uint16 descriptor, uint16 index);
-	bool scriptHasRange(uint32 pc, uint32 width);
 	byte scriptReadByte(uint32 pc);
 	uint16 scriptReadWord(uint32 pc);
 	uint32 scriptReadDword(uint32 pc);
diff --git a/engines/comfy/debug.cpp b/engines/comfy/debug.cpp
index 52fbd503425..b80232633c1 100644
--- a/engines/comfy/debug.cpp
+++ b/engines/comfy/debug.cpp
@@ -51,16 +51,16 @@ static ImVec2 debugMapPointToCanvas(const ImVec2 &canvasPos, int16 mapLeft, int1
 }
 
 bool ComfyEngine::debugScriptHasRange(uint32 pc, uint32 width) {
-	uint32 tileOffset = pc % COMFY_TILE_SIZE;
-	uint32 tileBase = pc - tileOffset;
-	uint32 tileSize = tileBase < _picDataSize ? MIN<uint32>(COMFY_TILE_SIZE, _picDataSize - tileBase) : 0;
-
-	return tileBase <= _comfyObjData.size() && tileSize <= _comfyObjData.size() - tileBase &&
-		tileOffset <= tileSize && width <= tileSize - tileOffset;
+	return _comfyObjFile && pc <= _comfyObjFile->fileSize && width <= _comfyObjFile->fileSize - pc;
 }
 
 uint16 ComfyEngine::debugScriptReadWord(uint32 pc) {
-	return debugScriptHasRange(pc, 2) ? READ_LE_UINT16(&_comfyObjData[pc]) : (uint16)0;
+	byte value[2];
+	memset(value, 0, sizeof(value));
+	if (debugScriptHasRange(pc, sizeof(value)))
+		objFileReadField(value, pc, sizeof(value), _comfyObjFile);
+
+	return READ_LE_UINT16(value);
 }
 
 void ComfyEngine::drawActorDebugUi(bool *visible) {
@@ -166,7 +166,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 		}
 	}
 
-	const float margin = 32.0F;
+	float margin = 32.0F;
 	float scale = 1.0F;
 	ImVec2 canvasSize((float)(mapRight - mapLeft) * scale + margin * 2.0F,
 		(float)(mapBottom - mapTop) * scale + margin * 2.0F);
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index ccadb2d01e7..1c3983a81fc 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -253,91 +253,28 @@ bool ComfyEngine::readAssetFile(const Common::Path &filename, Common::Array<byte
 	return true;
 }
 
-bool ComfyEngine::comfyObjOpen() {
-	if (!readAssetFile(Common::Path("COMFY.OBJ"), _comfyObjData) || _comfyObjData.size() < 0x14)
-		return false;
-
-	_stringCount = assetsReadLe16At(_comfyObjData, 0x08);
-	_sceneCount = assetsReadLe16At(_comfyObjData, 0x0A);
-	_keyBitCount = assetsReadLe16At(_comfyObjData, 0x0C);
-	_picDataSize = assetsReadLe32At(_comfyObjData, 0x0E);
-	_resourceHandleCount = assetsReadLe16At(_comfyObjData, 0x12);
-	_usesAnimFile = (_resourceHandleCount & 0x8000) != 0;
-	_resourceHandleCount &= 0x7FFF;
-	_comfyObjOpen = true;
-	return true;
-}
-
-bool ComfyEngine::picFileOpen() {
-	if (!readAssetFile(Common::Path("PICFILE.DAT"), _picFileData) || _picFileData.size() < 4)
-		return false;
-
-	uint16 count = assetsReadLe16At(_picFileData, 0);
-	uint32 tableSize = 2 + (uint32)count * 0x11;
-	if (tableSize > _picFileData.size())
-		return false;
-
-	_spriteHeaders.resize(count);
-	_spriteResources.resize(count);
-	for (uint i = 0; i < count; i++) {
-		_spriteHeaders[i] = SpriteObjectHeader();
-		_spriteResources[i].header = SpriteObjectHeader();
-		_spriteResources[i].id = i;
-		_spriteResources[i].pixels.clear();
-		_spriteResources[i].loaded = false;
-	}
-
-	_picFileDatOpen = true;
-	return true;
-}
-
-bool ComfyEngine::midiFileOpen() {
-	if (!readAssetFile(Common::Path("MIDIFILE.DAT"), _midiFileData) || _midiFileData.size() < 4)
-		return false;
-
-	if (_midiFileData[0] != 'C' || (_midiFileData[1] != 'M' && _midiFileData[1] != 'm'))
-		return false;
-
-	_midiEntryCount = assetsReadLe16At(_midiFileData, 2);
-	_midiFileMode = _midiFileData[1] == 'm' ? 1 : 0;
-	return true;
-}
-
 uint32 ComfyEngine::assetsAlignEven32(uint32 value) {
 	return value + (value & 1);
 }
 
-uint16 ComfyEngine::assetsReadLe16At(Common::Array<byte> &data, uint32 offset) {
-	return offset <= data.size() && 2 <= data.size() - offset ? READ_LE_UINT16(&data[offset]) : 0;
-}
-
-uint32 ComfyEngine::assetsReadLe32At(Common::Array<byte> &data, uint32 offset) {
-	return offset <= data.size() && 4 <= data.size() - offset ? READ_LE_UINT32(&data[offset]) : 0;
-}
-
-int32 ComfyEngine::assetsXmsCopy(byte *destination, uint32 destinationSize, uint32 destinationOffset,
-		const byte *source, uint32 sourceSize, uint32 sourceOffset, uint32 size) {
-	if (!size)
-		return 0;
-
-	if (!destination || !source || destinationOffset > destinationSize || size > destinationSize - destinationOffset ||
-			sourceOffset > sourceSize || size > sourceSize - sourceOffset)
-		return -1;
+void ComfyEngine::midiFileGetTileParams(uint16 *entryCount, uint16 *entrySize) {
+	if (entryCount)
+		*entryCount = _midiEntryCount;
 
-	memcpy(destination + destinationOffset, source + sourceOffset, size);
-	return 0;
+	if (entrySize)
+		*entrySize = 6;
 }
 
 void ComfyEngine::midiFileReadEntries(byte *destination) {
-	if (!destination || _midiFileData.size() <= 4)
+	if (!destination || !_midiFileStream || !_midiFileStream->seek(4))
 		return;
 
 	uint32 size = (uint32)_midiEntryCount * 6;
-	memcpy(destination, &_midiFileData[4], MIN<uint32>(size, _midiFileData.size() - 4));
+	_midiFileStream->read(destination, size);
 }
 
 byte *ComfyEngine::soundReadTiledData() {
-	return _vocFileData.size() > 4 ? &_vocFileData[4] : nullptr;
+	return _vocFile ? objFileReadTiled(4, (uint32)_soundEntryCount * 8, _vocFile) : nullptr;
 }
 
 void ComfyEngine::soundGetTileParams(uint16 *entryCount, uint16 *entrySize) {
@@ -348,6 +285,14 @@ void ComfyEngine::soundGetTileParams(uint16 *entryCount, uint16 *entrySize) {
 		*entrySize = 8;
 }
 
+void ComfyEngine::stringTableSetCount(uint16 count) {
+	_stringCount = count + 1;
+}
+
+uint16 ComfyEngine::stringTableGetSize() {
+	return _stringCount * sizeof(uint16);
+}
+
 bool ComfyEngine::selPoolInit() {
 	if (_selectorPoolInitialized)
 		return true;
@@ -371,7 +316,12 @@ void ComfyEngine::selPoolFree() {
 
 bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount,
 		uint16 handleCount, uint32 &numSprites) {
-	_stringTable.resize(_stringCount + 1);
+	return sceneFrameInitTables(sceneCount, actorCount, keyBitCount, handleCount, numSprites);
+}
+
+bool ComfyEngine::sceneFrameInitTables(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount,
+		uint16 handleCount, uint32 &numSprites) {
+	_stringTable.resize(_stringCount);
 	memset(&_stringTable[0], 0, _stringTable.size() * sizeof(uint16));
 	_sceneHandles.resize(sceneCount + 1);
 	memset(&_sceneHandles[0], 0, _sceneHandles.size() * sizeof(uint16));
@@ -391,7 +341,7 @@ bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16
 	if (0xC7 < ARRAYSIZE(_actorPcTable))
 		_actorPcTable[0xC7] = 0;
 
-	uint32 stringBytes = _stringTable.size() * sizeof(uint16);
+	uint32 stringBytes = stringTableGetSize();
 	uint32 handleBytes = _sceneHandles.size() * sizeof(uint16);
 	uint32 actorRecordSize = COMFY_ACTOR_SIZE_V3;
 	if (_engineVersion == 1)
@@ -434,8 +384,12 @@ bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16
 	_envNumSprites = numSprites;
 	_activeSceneCount = handleCount;
 
-	if (_engineVersion == 3) {
+	if (_isPanther || _engineVersion == 3)
 		midiInitInstanceAt();
+	else
+		midiInitInstance();
+
+	if (_isPanther || _engineVersion == 3) {
 		if (!soundInit())
 			return false;
 
@@ -461,44 +415,94 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	if (!selPoolInit())
 		return false;
 
-	if (!comfyObjOpen() || !picFileOpen() || !midiFileOpen()) {
+	if (!memCompactAndCheck(0x200000))
 		return false;
+
+	uint32 comfyCacheBytes = _engineVersion == 3 ? 0x32000 : 0xA000;
+	_comfyObjFile = objFileLoadSoundData(Common::Path("COMFY.OBJ"), 0x0800, comfyCacheBytes);
+	if (!_comfyObjFile)
+		return false;
+
+	byte value[4];
+	objFileReadField(value, 0x08, 2, _comfyObjFile);
+	stringTableSetCount(READ_LE_UINT16(value));
+	objFileReadField(value, 0x0A, 2, _comfyObjFile);
+	_sceneCount = READ_LE_UINT16(value);
+	objFileReadField(value, 0x0C, 2, _comfyObjFile);
+	_keyBitCount = READ_LE_UINT16(value);
+	objFileReadField(value, 0x0E, 4, _comfyObjFile);
+	_picDataSize = READ_LE_UINT32(value);
+	objFileReadField(value, 0x12, 2, _comfyObjFile);
+	_resourceHandleCount = READ_LE_UINT16(value);
+	_usesAnimFile = (_resourceHandleCount & 0x8000) != 0;
+	_resourceHandleCount &= 0x7FFF;
+	_comfyObjOpen = true;
+	_numFrames = (uint16)(_picDataSize / COMFY_TILE_SIZE + (_picDataSize % COMFY_TILE_SIZE ? 2 : 1));
+	if (_engineVersion == 3) {
+		uint16 preloadCount = MIN<uint16>(_numFrames, 0x64);
+		for (uint16 i = 0; i < preloadCount; i++)
+			objFileReadTiled((uint32)i << 11, 8, _comfyObjFile);
 	}
 
-	if (_engineVersion != 3 && !soundInit())
+	_picFile = objFileLoadSoundData(Common::Path("PICFILE.DAT"), 0x0800, 0x5000);
+	if (!_picFile)
 		return false;
 
-	_picFileMapped = true;
+	byte objectCount[2];
+	objFileReadField(objectCount, 0, sizeof(objectCount), _picFile);
+	_numObjects = READ_LE_UINT16(objectCount);
+	soundBufFree(_picFile);
+
+	if (!_isPanther && _engineVersion != 3 && !soundInit())
+		return false;
 
-	_numFrames = _picDataSize / COMFY_TILE_SIZE + (_picDataSize % COMFY_TILE_SIZE ? 2 : 1);
-	_numObjects = _spriteHeaders.size();
+	_picFileMapped = true;
 	uint32 numSprites = 0;
 	if (!sceneLoadAndInit(_sceneCount, 0x78, _keyBitCount, _resourceHandleCount, numSprites))
 		return false;
 
 	_soundLoaded = true;
+	if (!memIsReady())
+		return false;
 
-	uint32 environmentBytes = ((_envNumSprites * 5 + 0x3FF) / 0x400) * 0x400;
-	_environmentData.resize(environmentBytes);
-	if (environmentBytes)
-		memset(&_environmentData[0], 0, environmentBytes);
-	_xmsEnvAllocated = !_environmentData.empty();
+	uint16 environmentPages = (uint16)((_envNumSprites * 5 + 0x3FF) / 0x400);
+	int32 environmentHandle = memAllocTrackFar(environmentPages);
+	if (environmentHandle < 0)
+		return false;
+
+	_xmsEnvHandle = (uint16)environmentHandle;
+	_xmsEnvAllocated = true;
 
-	uint32 midiHeaderBytes = assetsAlignEven32((uint32)_midiEntryCount * 6);
+	uint16 midiEntryCount = 0;
+	uint16 midiEntrySize = 0;
+	midiFileGetTileParams(&midiEntryCount, &midiEntrySize);
+	uint32 midiHeaderBytes = assetsAlignEven32((uint32)midiEntryCount * midiEntrySize);
 	uint16 soundEntryCount = 0;
 	uint16 soundEntrySize = 0;
 	soundGetTileParams(&soundEntryCount, &soundEntrySize);
 	uint32 soundHeaderBytes = assetsAlignEven32((uint32)soundEntryCount * soundEntrySize);
 	uint32 objectTableBytes = assetsAlignEven32((uint32)_numObjects * 0x11);
 	uint32 headerTotalBytes = midiHeaderBytes + soundHeaderBytes + objectTableBytes;
-	uint16 headerPages = (headerTotalBytes + 0x400) / 0x400;
-	_headerXmsData.resize((uint32)headerPages * 0x400);
-	if (!_headerXmsData.empty())
-		memset(&_headerXmsData[0], 0, _headerXmsData.size());
+	uint16 headerPages = (uint16)((headerTotalBytes + 0x400) / 0x400);
+	int32 headerHandle = memAllocTrackFar(headerPages);
+	if (headerHandle < 0)
+		return false;
+
+	_xmsHeaderHandle = (uint16)headerHandle;
 
 	videoInit();
 
-	_objectCacheEntries.resize(_spriteHeaders.size());
+	_spriteHeaders.resize(_numObjects);
+	_spriteResources.resize(_numObjects);
+	for (uint i = 0; i < _numObjects; i++) {
+		_spriteHeaders[i] = SpriteObjectHeader();
+		_spriteResources[i].header = SpriteObjectHeader();
+		_spriteResources[i].id = i;
+		_spriteResources[i].pixels.clear();
+		_spriteResources[i].loaded = false;
+	}
+
+	_objectCacheEntries.resize(_numObjects);
 	_frameCacheEntries.resize(_numFrames + 1);
 	if (!_objectCacheEntries.empty())
 		memset(&_objectCacheEntries[0], 0xFF, _objectCacheEntries.size() * sizeof(SpriteCacheEntry));
@@ -511,7 +515,14 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	for (uint i = 0; i < _spriteResources.size(); i++)
 		spriteInvalidateHostCache(_spriteResources[i]);
 
-	if (_engineVersion != 3 && _usesAnimFile && !animFileOpen())
+	// Panther hardcodes the original background-buffer flag to one; WCOMFY v3 hardcodes it to zero.
+	if (_isPanther) {
+		_backgroundFramebuf.resize(framebufferBytes());
+		memset(&_backgroundFramebuf[0], 0, _backgroundFramebuf.size());
+		_backgroundFrame = 0;
+	}
+
+	if (!_isPanther && _engineVersion != 3 && _usesAnimFile && !animFileOpen())
 		return false;
 
 	if (_usesAnimFile) {
@@ -519,7 +530,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 		memset(&_animFrameBuffer[0], 0, _animFrameBuffer.size());
 	}
 
-	uint32 xmsLimit = _engineVersion == 3 ? 0x7D000 : 0x0800 << 10;
+	uint32 xmsLimit = memGetXmsLimitFar();
 	_scenePoolSize = xmsLimit > budget ? xmsLimit - budget : 0;
 	_scenePoolSize &= 0xFFFFFFFE;
 	_scenePoolData.resize(_scenePoolSize);
@@ -531,6 +542,22 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	if (_engineVersion != 3 && _scenePoolSize >= 2)
 		WRITE_LE_UINT16(&_scenePoolData[0], 0x8000);
 
+	uint32 freeKB = memGetFreeKBThunk();
+	if (!_isPanther && _engineVersion != 3 && freeKB < 0x12C)
+		freeKB = memGetFreeKBThunk() * 0x5A / 0x64;
+
+	if (freeKB <= 0x12C)
+		return false;
+
+	uint32 picCacheBytes = freeKB << 10;
+	if (_isPanther || _engineVersion == 3)
+		picCacheBytes = (freeKB - 1) << 10;
+
+	_picFile = objFileLoadSoundData(Common::Path("PICFILE.DAT"), 0x8000, picCacheBytes);
+	if (!_picFile)
+		return false;
+
+	_picFileDatOpen = true;
 	uint32 xmsOffset = 0;
 	uint32 fileOffset = 2;
 	uint32 remaining = objectTableBytes;
@@ -538,8 +565,16 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	_headerXmsObjectTableBytes = objectTableBytes;
 	while (remaining) {
 		uint32 chunk = MIN<uint32>(remaining, 0x8000);
-		if (assetsXmsCopy(&_headerXmsData[0], _headerXmsData.size(), xmsOffset,
-				&_picFileData[0], _picFileData.size(), fileOffset, chunk) < 0)
+		byte *source = objFileReadTiled(fileOffset, chunk, _picFile);
+		if (!source)
+			return false;
+
+		XmsMove move;
+		move.length = chunk;
+		move.destinationHandle = _xmsHeaderHandle;
+		move.destinationOffset = xmsOffset;
+		move.sourceMemory = source;
+		if (xmsTransfer(move) < 0)
 			return false;
 
 		xmsOffset += chunk;
@@ -549,12 +584,19 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 
 	_headerXmsMidiEntriesBase = xmsOffset;
 	_headerXmsMidiEntriesBytes = midiHeaderBytes;
-	if (midiHeaderBytes && scenePtr) {
+	if (midiHeaderBytes) {
+		if (!scenePtr)
+			return false;
+
 		memset(scenePtr, 0, midiHeaderBytes);
 		midiFileReadEntries(scenePtr);
 
-		if (assetsXmsCopy(&_headerXmsData[0], _headerXmsData.size(), xmsOffset,
-				scenePtr, midiHeaderBytes, 0, midiHeaderBytes) < 0)
+		XmsMove move;
+		move.length = midiHeaderBytes;
+		move.destinationHandle = _xmsHeaderHandle;
+		move.destinationOffset = xmsOffset;
+		move.sourceMemory = scenePtr;
+		if (xmsTransfer(move) < 0)
 			return false;
 
 		xmsOffset += midiHeaderBytes;
@@ -564,9 +606,15 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	_headerXmsSoundHeadersBytes = soundHeaderBytes;
 	if (soundHeaderBytes) {
 		byte *soundTiledData = soundReadTiledData();
-		uint32 available = _vocFileData.size() > 4 ? MIN<uint32>(soundHeaderBytes, _vocFileData.size() - 4) : 0;
-		if (available && assetsXmsCopy(&_headerXmsData[0], _headerXmsData.size(), xmsOffset,
-				soundTiledData, available, 0, available) < 0)
+		if (!soundTiledData)
+			return false;
+
+		XmsMove move;
+		move.length = soundHeaderBytes;
+		move.destinationHandle = _xmsHeaderHandle;
+		move.destinationOffset = xmsOffset;
+		move.sourceMemory = soundTiledData;
+		if (xmsTransfer(move) < 0)
 			return false;
 
 		xmsOffset += soundHeaderBytes;
@@ -582,54 +630,38 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 }
 
 void ComfyEngine::assetsUnload(byte freeAudio) {
-	if (_engineVersion == 3) {
-		_objectCacheEntries.clear();
-		_frameCacheEntries.clear();
-		_scenePoolData.clear();
-		spriteInvalidateHostCache(_frameSpriteResource);
-		_frameSpriteResource.id = 0;
-		_environmentData.clear();
-		_headerXmsData.clear();
+	_objectCacheEntries.clear();
+	_frameCacheEntries.clear();
+	_scenePoolData.clear();
+	spriteInvalidateHostCache(_frameSpriteResource);
+	_frameSpriteResource.id = 0;
+	if (!_backgroundFramebuf.empty()) {
+		_backgroundFramebuf.clear();
+		_backgroundFrame = 0;
+	}
 
-		if (_picFileMapped)
-			soundShutdown();
+	if (_xmsEnvAllocated)
+		memFreeTrackFar(_xmsEnvHandle);
 
-		_picFileData.clear();
-		_comfyObjData.clear();
+	if (_xmsHeaderHandle)
+		memFreeTrackFar(_xmsHeaderHandle);
 
-		if (_sceneOpen)
-			sceneShutdown();
+	if (_picFileMapped)
+		soundShutdown();
 
+	if (_picFileDatOpen)
+		soundBufFree(_picFile);
+
+	if (_comfyObjOpen)
+		soundBufFree(_comfyObjFile);
+
+	if (_soundLoaded)
+		sceneShutdown();
+
+	if (_usesAnimFile && (_isPanther || _engineVersion == 3))
 		animFileShutdown();
-		selPoolFree();
-	} else {
-		animFileShutdown();
-		_spriteHeaders.clear();
-		_spriteResources.clear();
-		_stringTable.clear();
-		_sceneHandles.clear();
-		_midiHandles.clear();
-		_actors.clear();
-		_sceneMemoryBlock.clear();
-		keyBitFree();
-		_objectCacheEntries.clear();
-		_frameCacheEntries.clear();
-		_scenePoolData.clear();
-		_environmentData.clear();
-		_headerXmsData.clear();
-
-		if (_picFileMapped)
-			soundShutdown();
-
-		_picFileData.clear();
-		_comfyObjData.clear();
-
-		if (_soundLoaded && _sceneOpen)
-			sceneShutdown();
-
-		selPoolFree();
-	}
 
+	selPoolFree();
 	_spriteHeaders.clear();
 	_spriteResources.clear();
 	_stringTable.clear();
@@ -638,7 +670,12 @@ void ComfyEngine::assetsUnload(byte freeAudio) {
 	_actors.clear();
 	_sceneMemoryBlock.clear();
 	keyBitFree();
-	_midiFileData.clear();
+	soundBufFree(_vocFile);
+	soundBufFree(_picFile);
+	soundBufFree(_comfyObjFile);
+	delete _midiFileStream;
+	_midiFileStream = nullptr;
+	xmsReset();
 	_spriteConversionLoads = ResourceLoadList();
 	memset(_sceneEntryOffsets, 0, sizeof(_sceneEntryOffsets));
 	memset(_actorPcTable, 0, sizeof(_actorPcTable));
@@ -654,6 +691,8 @@ void ComfyEngine::assetsUnload(byte freeAudio) {
 	_picFileDatOpen = false;
 	_comfyObjOpen = false;
 	_xmsEnvAllocated = false;
+	_xmsEnvHandle = 0;
+	_xmsHeaderHandle = 0;
 	_soundLoaded = false;
 	_picFileMapped = false;
 	_numFrames = 0;
diff --git a/engines/comfy/memory.cpp b/engines/comfy/memory.cpp
new file mode 100644
index 00000000000..b15d768c804
--- /dev/null
+++ b/engines/comfy/memory.cpp
@@ -0,0 +1,173 @@
+/* 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 "comfy/comfy.h"
+
+namespace Comfy {
+
+uint16 ComfyEngine::sysGetExtMemKB() {
+	// The original reads CMOS extended-memory registers. The compatibility layer exposes
+	// the 4000 KB configuration that selects the engine's normal high-memory paths.
+	return 0x0FA0;
+}
+
+uint32 ComfyEngine::memCompactAndCheck(uint32 minimumBytes) {
+	uint32 availableBytes = (uint32)sysGetExtMemKB() << 10;
+	if (availableBytes < minimumBytes)
+		return 0;
+
+	return availableBytes >> 10;
+}
+
+bool ComfyEngine::memIsReady() {
+	return true;
+}
+
+uint32 ComfyEngine::memGetFreeKB() {
+	uint32 allocatedBytes = _memAllocTotal + _scenePoolSize + 4 + framebufferBytes() + 4;
+	if (!_backgroundFramebuf.empty())
+		allocatedBytes += _backgroundFramebuf.size() + 4;
+
+	if (!_animFrameBuffer.empty())
+		allocatedBytes += _animFrameBuffer.size() + 4;
+
+	if (!_sceneMemoryBlock.empty())
+		allocatedBytes += _sceneMemoryBlock.size() + 4;
+
+	if (!_objectCacheEntries.empty())
+		allocatedBytes += _objectCacheEntries.size() * (_engineVersion == 3 ? 8 : 6) + 4;
+
+	if (!_frameCacheEntries.empty())
+		allocatedBytes += _frameCacheEntries.size() * (_engineVersion == 3 ? 8 : 6) + 4;
+
+	uint32 extendedKB = sysGetExtMemKB();
+	uint32 allocatedKB = allocatedBytes >> 10;
+	if (extendedKB <= 0x0400 + allocatedKB)
+		return 0x0E;
+
+	return (extendedKB - 0x0400 - allocatedKB) / 2 + 0x0E;
+}
+
+uint32 ComfyEngine::memGetFreeKBThunk() {
+	return memGetFreeKB();
+}
+
+uint32 ComfyEngine::memGetXmsLimit() {
+	uint32 limit = 0x7D000;
+	if (sysGetExtMemKB() < 0x0FA0)
+		limit -= 0x25800;
+
+	return limit;
+}
+
+uint32 ComfyEngine::memGetXmsLimitFar() {
+	return memGetXmsLimit();
+}
+
+int32 ComfyEngine::memAllocTrack(uint16 pages) {
+	if (_xmsBlockCount + 1 > COMFY_XMS_HANDLE_CAPACITY)
+		return -1;
+
+	uint16 handle = 1;
+	while (handle < COMFY_XMS_HANDLE_CAPACITY && _xmsBlocks[handle].data)
+		handle++;
+
+	if (handle >= COMFY_XMS_HANDLE_CAPACITY)
+		return -3;
+
+	uint32 size = (uint32)pages << 10;
+	byte *data = (byte *)malloc(size ? size : 1);
+	if (!data)
+		return -2;
+
+	memset(data, 0, size);
+	_xmsBlocks[handle].data = data;
+	_xmsBlocks[handle].size = size;
+	_xmsBlockCount++;
+	_memAllocTotal += size + 4;
+	return handle;
+}
+
+int32 ComfyEngine::memAllocTrackFar(uint16 pages) {
+	return memAllocTrack(pages);
+}
+
+int32 ComfyEngine::memFreeTrack(uint16 handle) {
+	if (!handle || handle >= COMFY_XMS_HANDLE_CAPACITY || !_xmsBlocks[handle].data)
+		return -1;
+
+	_memAllocTotal -= _xmsBlocks[handle].size + 4;
+	free(_xmsBlocks[handle].data);
+	_xmsBlocks[handle].data = nullptr;
+	_xmsBlocks[handle].size = 0;
+	_xmsBlockCount--;
+	return 0;
+}
+
+int32 ComfyEngine::memFreeTrackFar(uint16 handle) {
+	return memFreeTrack(handle);
+}
+
+int32 ComfyEngine::xmsCopyToConv(XmsMove &move) {
+	byte *source = (byte *)move.sourceMemory;
+	byte *destination = move.destinationMemory;
+	uint32 sourceSize = UINT32_MAX;
+	uint32 destinationSize = UINT32_MAX;
+
+	if (move.sourceHandle) {
+		if (move.sourceHandle >= COMFY_XMS_HANDLE_CAPACITY || !_xmsBlocks[move.sourceHandle].data)
+			return -1;
+
+		source = _xmsBlocks[move.sourceHandle].data;
+		sourceSize = _xmsBlocks[move.sourceHandle].size;
+	}
+
+	if (move.destinationHandle) {
+		if (move.destinationHandle >= COMFY_XMS_HANDLE_CAPACITY || !_xmsBlocks[move.destinationHandle].data)
+			return -1;
+
+		destination = _xmsBlocks[move.destinationHandle].data;
+		destinationSize = _xmsBlocks[move.destinationHandle].size;
+	}
+
+	if (!source || !destination || move.sourceOffset > sourceSize || move.length > sourceSize - move.sourceOffset ||
+			move.destinationOffset > destinationSize || move.length > destinationSize - move.destinationOffset)
+		return -1;
+
+	memcpy(destination + move.destinationOffset, source + move.sourceOffset, move.length);
+	return 0;
+}
+
+int32 ComfyEngine::xmsTransfer(XmsMove &move) {
+	return xmsCopyToConv(move);
+}
+
+void ComfyEngine::xmsReset() {
+	for (uint16 handle = 1; handle < COMFY_XMS_HANDLE_CAPACITY; handle++) {
+		if (_xmsBlocks[handle].data)
+			memFreeTrack(handle);
+	}
+
+	_xmsEnvHandle = 0;
+	_xmsHeaderHandle = 0;
+	_memAllocTotal = 0;
+}
+
+} // End of namespace Comfy
diff --git a/engines/comfy/midi.cpp b/engines/comfy/midi.cpp
index b3dd40578db..add652c924d 100644
--- a/engines/comfy/midi.cpp
+++ b/engines/comfy/midi.cpp
@@ -381,6 +381,9 @@ void ComfyEngine::midiStopAll() {
 }
 
 void ComfyEngine::midiShutdown() {
+	if (_usesAnimFile && _engineVersion == 2 && !_isPanther)
+		animFileShutdown();
+
 	_midiHandles.clear();
 	_sceneMemoryBlock.clear();
 	_sceneMidiInstanceOffset = 0;
diff --git a/engines/comfy/module.mk b/engines/comfy/module.mk
index 9a64926547f..75faaf4bc84 100644
--- a/engines/comfy/module.mk
+++ b/engines/comfy/module.mk
@@ -11,9 +11,11 @@ MODULE_OBJS = \
 	game.o \
 	input.o \
 	keybits.o \
+	memory.o \
 	metaengine.o \
 	midi.o \
 	midiplyr/midiplyr.o \
+	object_file.o \
 	palette.o \
 	scene.o \
 	script.o \
diff --git a/engines/comfy/object_file.cpp b/engines/comfy/object_file.cpp
new file mode 100644
index 00000000000..a9ed5d0314d
--- /dev/null
+++ b/engines/comfy/object_file.cpp
@@ -0,0 +1,503 @@
+/* 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 "comfy/comfy.h"
+
+namespace Comfy {
+
+ComfyEngine::ObjFileCacheRow *ComfyEngine::tileListEvictTail(ObjFile *objectFile) {
+	if (!objectFile || !objectFile->cacheRows || objectFile->tileLruTail >= objectFile->cacheRowCount)
+		return nullptr;
+
+	ObjFileCacheRow *row = &objectFile->cacheRows[objectFile->tileLruTail];
+	objectFile->tileLruTail = row->previousIndex;
+	objectFile->tileLruTailValid = row->previousValid;
+	if (objectFile->tileStatus && row->frameIndex < objectFile->tileStatusCount)
+		objectFile->tileStatus[row->frameIndex] = 0xFFFF;
+
+	return row;
+}
+
+ComfyEngine::ObjFileCacheRow *ComfyEngine::tileListAlloc(ObjFile *objectFile) {
+	if (!objectFile || !objectFile->cacheRows)
+		return nullptr;
+
+	ObjFileCacheRow *row = nullptr;
+	uint16 rowIndex = objectFile->currentBlock;
+	if (objectFile->currentBlock < objectFile->cacheRowCount) {
+		row = &objectFile->cacheRows[rowIndex];
+		if (!objectFile->currentBlock) {
+			objectFile->tileLruTail = rowIndex;
+			objectFile->tileLruTailValid = 1;
+			row->nextIndex = rowIndex;
+			row->nextValid = 1;
+			row->previousIndex = rowIndex;
+			row->previousValid = 1;
+		}
+
+		objectFile->currentBlock++;
+		if (objectFile->tileLruTailValid && objectFile->tileLruTail < objectFile->cacheRowCount) {
+			ObjFileCacheRow *tail = &objectFile->cacheRows[objectFile->tileLruTail];
+			row->nextIndex = tail->nextIndex;
+			row->nextValid = tail->nextValid;
+			row->previousIndex = objectFile->tileLruTail;
+			row->previousValid = 1;
+			if (row->nextIndex < objectFile->cacheRowCount) {
+				objectFile->cacheRows[row->nextIndex].previousIndex = rowIndex;
+				objectFile->cacheRows[row->nextIndex].previousValid = 1;
+			}
+
+			tail->nextIndex = rowIndex;
+			tail->nextValid = 1;
+		}
+	} else {
+		row = tileListEvictTail(objectFile);
+	}
+
+	return row;
+}
+
+void ComfyEngine::tileListRemove(ObjFile *objectFile, uint16 index) {
+	if (!objectFile || !objectFile->cacheRows || index >= objectFile->cacheRowCount)
+		return;
+
+	ObjFileCacheRow *row = &objectFile->cacheRows[index];
+	if (objectFile->tileLruTailValid && objectFile->tileLruTail == index) {
+		objectFile->tileLruTail = row->previousIndex;
+		objectFile->tileLruTailValid = row->previousValid;
+		return;
+	}
+
+	if (row->nextIndex < objectFile->cacheRowCount) {
+		objectFile->cacheRows[row->nextIndex].previousIndex = row->previousIndex;
+		objectFile->cacheRows[row->nextIndex].previousValid = row->previousValid;
+	}
+
+	if (row->previousIndex < objectFile->cacheRowCount) {
+		objectFile->cacheRows[row->previousIndex].nextIndex = row->nextIndex;
+		objectFile->cacheRows[row->previousIndex].nextValid = row->nextValid;
+	}
+
+	if (objectFile->tileLruTailValid && objectFile->tileLruTail < objectFile->cacheRowCount) {
+		ObjFileCacheRow *tail = &objectFile->cacheRows[objectFile->tileLruTail];
+		row->nextIndex = tail->nextIndex;
+		row->nextValid = tail->nextValid;
+		row->previousIndex = objectFile->tileLruTail;
+		row->previousValid = 1;
+		if (row->nextIndex < objectFile->cacheRowCount) {
+			objectFile->cacheRows[row->nextIndex].previousIndex = index;
+			objectFile->cacheRows[row->nextIndex].previousValid = 1;
+		}
+
+		tail->nextIndex = index;
+		tail->nextValid = 1;
+	}
+}
+
+uint16 ComfyEngine::tileListRemoveRange(ObjFile *objectFile, uint16 first, uint16 last) {
+	if (!objectFile || !objectFile->tileStatus)
+		return 0;
+
+	uint16 removed = 0;
+	uint16 row = first;
+	while (row <= last && row < objectFile->tileStatusCount && objectFile->tileStatus[row] != 0xFFFF) {
+		removed++;
+		row++;
+	}
+
+	row++;
+	while (row <= last && row < objectFile->tileStatusCount) {
+		uint16 tile = objectFile->tileStatus[row];
+		if (tile != 0xFFFF) {
+			tileListRemove(objectFile, tile);
+			removed++;
+		}
+
+		row++;
+	}
+
+	return removed;
+}
+
+void ComfyEngine::tileUploadToXms(ObjFile *objectFile, const byte *source, uint16 size, uint32 destinationOffset) {
+	if (!objectFile || !source)
+		return;
+
+	XmsMove move;
+	move.length = size;
+	move.destinationHandle = objectFile->cacheXmsHandle;
+	move.destinationOffset = destinationOffset;
+	move.sourceMemory = source;
+	if (xmsTransfer(move) < 0)
+		error("Unable to upload object-file tile to XMS");
+}
+
+void ComfyEngine::tileCopyXmsPair(ObjFile *objectFile, byte *destination, uint32 sourceOffset, uint32 size) {
+	if (!objectFile || !destination)
+		return;
+
+	if (size == 1)
+		size = 2;
+
+	if (size & 1) {
+		tileCopyXmsPair(objectFile, destination + 1, sourceOffset + 1, size - 1);
+		tileCopyXmsPair(objectFile, destination, sourceOffset, 2);
+		return;
+	}
+
+	XmsMove move;
+	move.length = size;
+	move.sourceHandle = objectFile->cacheXmsHandle;
+	move.sourceOffset = sourceOffset;
+	move.destinationMemory = destination;
+	if (xmsTransfer(move) < 0)
+		error("Unable to read object-file tile from XMS");
+}
+
+uint16 ComfyEngine::tileDrawStrip(ObjFile *objectFile, byte *destination, uint16 cacheRow,
+		uint16 sourceColumn, uint32 width) {
+	if (!objectFile || !destination || !objectFile->blockSize)
+		return 0;
+
+	uint16 drawWidth = (uint16)width;
+	uint16 remainingColumns = (uint16)(objectFile->blockSize - sourceColumn);
+	if (remainingColumns < drawWidth)
+		drawWidth = remainingColumns;
+
+	uint32 sourceOffset = (uint32)cacheRow * objectFile->blockSize + sourceColumn;
+	tileCopyXmsPair(objectFile, destination, sourceOffset, drawWidth);
+	tileListRemove(objectFile, cacheRow);
+	_stripsDrawn++;
+	return drawWidth;
+}
+
+void ComfyEngine::tileLoadAndDraw(ObjFile *objectFile, const byte *source, uint16 tileId) {
+	ObjFileCacheRow *row = tileListAlloc(objectFile);
+	if (!objectFile || !row)
+		return;
+
+	uint16 frameIndex = row->tileIndex;
+	row->frameIndex = tileId;
+	if (objectFile->tileStatus && tileId < objectFile->tileStatusCount)
+		objectFile->tileStatus[tileId] = frameIndex;
+
+	tileUploadToXms(objectFile, source, objectFile->blockSize, (uint32)frameIndex * objectFile->blockSize);
+	tileListRemove(objectFile, frameIndex);
+}
+
+void ComfyEngine::frameLoaderLoadTileCore(ObjFile *objectFile, const byte *source, uint16 tileId) {
+	tileLoadAndDraw(objectFile, source, tileId);
+}
+
+void ComfyEngine::frameLoaderLoadTile(ObjFile *objectFile, uint16 tileId) {
+	if (!objectFile || !objectFile->tileReadBuffer)
+		return;
+
+	objFileReadRow(objectFile->tileReadBuffer, tileId, 1, objectFile->blockSize, objectFile);
+	frameLoaderLoadTileCore(objectFile, objectFile->tileReadBuffer, tileId);
+}
+
+void ComfyEngine::objFileReadRow(byte *destination, uint16 row, uint16 count, uint16 size, ObjFile *objectFile) {
+	if (!destination || !objectFile || !objectFile->stream || !size)
+		return;
+
+	uint32 offset = (uint32)row * size;
+	if (!objectFile->stream->seek(offset))
+		return;
+
+	uint32 total = (uint32)size * count;
+	if (total == 0x10000) {
+		objectFile->stream->read(destination, size);
+		objectFile->stream->read(destination + size, (uint32)size * (count - 1));
+	} else {
+		objectFile->stream->read(destination, total);
+	}
+
+	_tilesRead += count;
+}
+
+void ComfyEngine::objFileReadFieldCore(byte *destination, uint32 sourceOffset, uint32 byteCount, ObjFile *objectFile) {
+	if (!destination || !objectFile || !objectFile->blockSize || !byteCount)
+		return;
+
+	uint16 firstRow = (uint16)(sourceOffset / objectFile->blockSize);
+	uint16 lastRow = (uint16)((sourceOffset + byteCount - 1) / objectFile->blockSize);
+	uint16 row = firstRow;
+	uint16 column = (uint16)(sourceOffset % objectFile->blockSize);
+	byte *output = destination;
+	uint32 remaining = byteCount;
+	tileListRemoveRange(objectFile, firstRow, lastRow);
+
+	while (row <= lastRow && remaining) {
+		uint16 copied = 0;
+		if (row < objectFile->tileStatusCount && objectFile->tileStatus[row] == 0xFFFF &&
+				(_isPanther || _engineVersion == 3))
+			frameLoaderLoadTile(objectFile, row);
+
+		if (row < objectFile->tileStatusCount && objectFile->tileStatus[row] != 0xFFFF) {
+			copied = tileDrawStrip(objectFile, output, objectFile->tileStatus[row], column, remaining);
+		} else {
+			uint16 missingRows = 0;
+			uint16 probe = row;
+			while (probe <= lastRow && probe < objectFile->tileStatusCount &&
+					objectFile->tileStatus[probe] == 0xFFFF) {
+				if ((uint32)(missingRows + 1) * objectFile->blockSize > 0x10000)
+					break;
+
+				missingRows++;
+				probe++;
+			}
+
+			if (!missingRows)
+				return;
+
+			bool bounce = column || (uint32)missingRows * objectFile->blockSize > remaining;
+			byte *readDestination = bounce ? objectFile->readBuffer : output;
+			if (!readDestination)
+				return;
+
+			objFileReadRow(readDestination, row, missingRows, objectFile->blockSize, objectFile);
+			for (uint16 i = 0; i < missingRows; i++) {
+				byte *tileSource = readDestination + (uint32)i * objectFile->blockSize;
+				uint16 size = objectFile->blockSize;
+				if (bounce) {
+					size = objectFile->blockSize - column;
+					if (size > remaining)
+						size = (uint16)remaining;
+
+					if (size)
+						memcpy(output, tileSource + column, size);
+				}
+
+				tileLoadAndDraw(objectFile, tileSource, (uint16)(row + i));
+				column = 0;
+				remaining -= size;
+				output += size;
+			}
+
+			row += missingRows;
+			continue;
+		}
+
+		if (!copied)
+			return;
+
+		remaining -= copied;
+		output += copied;
+		row++;
+		column = 0;
+	}
+}
+
+byte *ComfyEngine::objFileReadTiledCore(uint32 sourceOffset, uint32 byteCount, ObjFile *objectFile) {
+	if (!objectFile || !objectFile->stream || !objectFile->blockSize || sourceOffset >= objectFile->fileSize || !byteCount)
+		return nullptr;
+
+	if (byteCount > objectFile->fileSize - sourceOffset)
+		byteCount = objectFile->fileSize - sourceOffset;
+
+	if (!objectFile->readBuffer)
+		return nullptr;
+
+	if (_isPanther || _engineVersion == 3) {
+		if (byteCount > objectFile->readBufferSize)
+			return nullptr;
+
+		objFileReadFieldCore(objectFile->readBuffer, sourceOffset, byteCount, objectFile);
+		return objectFile->readBuffer;
+	}
+
+	uint16 blockSize = objectFile->blockSize;
+	uint16 firstRow = (uint16)(sourceOffset / blockSize);
+	uint16 lastRow = (uint16)((sourceOffset + byteCount - 1) / blockSize);
+	uint16 firstColumn = (uint16)(sourceOffset % blockSize);
+	bool firstCached = firstRow < objectFile->tileStatusCount && objectFile->tileStatus[firstRow] != 0xFFFF;
+	bool lastCached = lastRow < objectFile->tileStatusCount && objectFile->tileStatus[lastRow] != 0xFFFF;
+	uint32 windowSize;
+
+	if (firstRow == lastRow) {
+		windowSize = firstCached ? byteCount : blockSize;
+	} else {
+		uint32 headSize = blockSize;
+		uint32 tailSize = blockSize;
+		if (firstCached)
+			headSize -= firstColumn;
+
+		if (lastCached)
+			tailSize = (sourceOffset + byteCount) % blockSize;
+
+		windowSize = (uint32)(lastRow - firstRow - 1) * blockSize + headSize + tailSize;
+	}
+
+	if (windowSize <= 0x10000) {
+		uint32 windowOffset = sourceOffset;
+		if (!firstCached)
+			windowOffset -= firstColumn;
+
+		objFileReadFieldCore(objectFile->readBuffer, windowOffset, windowSize, objectFile);
+		return objectFile->readBuffer + (firstCached ? 0 : firstColumn);
+	}
+
+	tileListRemoveRange(objectFile, firstRow, lastRow);
+	uint16 missing = 0;
+	uint16 row = firstRow;
+	while (row <= lastRow && row < objectFile->tileStatusCount && objectFile->tileStatus[row] == 0xFFFF) {
+		missing++;
+		row++;
+	}
+
+	if ((uint32)missing * blockSize > 0x10000)
+		missing = 0x10000 / blockSize;
+
+	if (missing) {
+		objFileReadRow(objectFile->readBuffer, firstRow, missing, blockSize, objectFile);
+		for (uint16 i = 0; i < missing; i++)
+			tileLoadAndDraw(objectFile, objectFile->readBuffer + (uint32)i * blockSize, (uint16)(firstRow + i));
+	}
+
+	missing = 0;
+	row = lastRow;
+	while (row >= firstRow && row < objectFile->tileStatusCount && objectFile->tileStatus[row] == 0xFFFF) {
+		missing++;
+		if (row == firstRow)
+			break;
+
+		row--;
+	}
+
+	if ((uint32)missing * blockSize > 0x10000)
+		missing = 0x10000 / blockSize;
+
+	if (missing) {
+		uint16 readRow = (uint16)(lastRow - missing + 1);
+		objFileReadRow(objectFile->readBuffer, readRow, missing, blockSize, objectFile);
+		for (uint16 i = missing; i != 0; i--) {
+			uint16 tileId = (uint16)(lastRow - i + 1);
+			uint16 bufferRow = (uint16)(missing - i);
+			tileLoadAndDraw(objectFile, objectFile->readBuffer + (uint32)bufferRow * blockSize, tileId);
+		}
+	}
+
+	objFileReadFieldCore(objectFile->readBuffer, sourceOffset, byteCount, objectFile);
+	return objectFile->readBuffer;
+}
+
+void ComfyEngine::objFileReadField(byte *destination, uint32 sourceOffset, uint32 byteCount, ObjFile *objectFile) {
+	objFileReadFieldCore(destination, sourceOffset, byteCount, objectFile);
+}
+
+byte *ComfyEngine::objFileReadTiled(uint32 sourceOffset, uint32 byteCount, ObjFile *objectFile) {
+	return objFileReadTiledCore(sourceOffset, byteCount, objectFile);
+}
+
+byte *ComfyEngine::frameLoaderReadFrameData(uint32 sourceOffset, uint32 byteCount, ObjFile *objectFile) {
+	if (_engineVersion != 3 || byteCount <= 0x10000)
+		return objFileReadTiled(sourceOffset, byteCount, objectFile);
+
+	if (!objectFile || !objectFile->readBuffer || byteCount > objectFile->readBufferSize)
+		return nullptr;
+
+	byte *data = objFileReadTiled(sourceOffset, 0x10000, objectFile);
+	if (!data)
+		return nullptr;
+
+	objFileReadFieldCore(objectFile->readBuffer + 0x10000, sourceOffset + 0x10000,
+		byteCount - 0x10000, objectFile);
+	return data;
+}
+
+ComfyEngine::ObjFile *ComfyEngine::objFileLoadSoundData(const Common::Path &path, uint16 blockSize,
+		uint32 maximumBytes) {
+	Common::SeekableReadStream *stream = pathFOpen(path, true);
+	if (!stream || stream->size() < 0 || (uint64)stream->size() > UINT32_MAX || !blockSize) {
+		delete stream;
+		return nullptr;
+	}
+
+	if (blockSize & 0x07FF)
+		blockSize += 0x0800 - (blockSize & 0x07FF);
+
+	uint32 fileSize = (uint32)stream->size();
+	uint16 fileBlocks = (uint16)((fileSize + blockSize - 1) / blockSize);
+	uint16 maximumBlocks = (uint16)(maximumBytes / blockSize);
+	uint16 cacheRows = MAX<uint16>(MIN<uint16>(maximumBlocks, fileBlocks), 4);
+	uint32 cacheBytes = (uint32)cacheRows * blockSize;
+	uint16 cachePages = (uint16)((cacheBytes + 0x03FF) / 0x0400);
+	uint16 controlSize = (_isPanther || _engineVersion == 3) ? 0x56 : 0x54;
+
+	ObjFile *objectFile = new ObjFile();
+	objectFile->stream = stream;
+	objectFile->path = path;
+	objectFile->fileSize = fileSize;
+	objectFile->blockSize = blockSize;
+	objectFile->cacheRowCount = cacheRows;
+	objectFile->tileStatusCount = (uint16)fileBlocks;
+	objectFile->trackedSize = (uint32)((uint32)fileBlocks * sizeof(uint16) + (uint32)cacheRows * 0x0C + controlSize + 4);
+	_memAllocTotal += objectFile->trackedSize;
+	objectFile->readBufferSize = _isPanther || _engineVersion == 3 ? 0x20010 : 0x10010;
+	objectFile->readBuffer = (byte *)malloc(objectFile->readBufferSize);
+	objectFile->tileReadBuffer = (byte *)malloc(blockSize);
+	objectFile->tileStatus = (uint16 *)malloc((fileBlocks ? fileBlocks : 1) * sizeof(uint16));
+	objectFile->cacheRows = (ObjFileCacheRow *)malloc((cacheRows ? cacheRows : 1) * sizeof(ObjFileCacheRow));
+	int32 cacheHandle = memAllocTrack((uint16)(cachePages + 1));
+	if (!objectFile->readBuffer || !objectFile->tileReadBuffer || !objectFile->tileStatus ||
+			!objectFile->cacheRows || cacheHandle < 0) {
+		if (cacheHandle >= 0)
+			memFreeTrack((uint16)cacheHandle);
+
+		soundBufFree(objectFile);
+		return nullptr;
+	}
+
+	objectFile->cacheXmsHandle = (uint16)cacheHandle;
+	for (uint32 i = 0; i < fileBlocks; i++)
+		objectFile->tileStatus[i] = 0xFFFF;
+
+	for (uint16 i = 0; i < cacheRows; i++) {
+		objectFile->cacheRows[i].tileIndex = i;
+		objectFile->cacheRows[i].frameIndex = 0;
+		objectFile->cacheRows[i].previousIndex = 0;
+		objectFile->cacheRows[i].previousValid = 0;
+		objectFile->cacheRows[i].nextIndex = 0;
+		objectFile->cacheRows[i].nextValid = 0;
+	}
+
+	return objectFile;
+}
+
+void ComfyEngine::soundBufFree(ObjFile *&objectFile) {
+	if (!objectFile)
+		return;
+
+	if (objectFile->cacheXmsHandle)
+		memFreeTrack(objectFile->cacheXmsHandle);
+
+	_memAllocTotal -= objectFile->trackedSize;
+
+	delete objectFile->stream;
+	free(objectFile->readBuffer);
+	free(objectFile->tileReadBuffer);
+	free(objectFile->tileStatus);
+	free(objectFile->cacheRows);
+	delete objectFile;
+	objectFile = nullptr;
+}
+
+} // End of namespace Comfy
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index d145bbf0ad4..444613a6813 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -216,22 +216,27 @@ void ComfyEngine::envConvToXms(byte *source, uint16 index) {
 		error("Invalid environment XMS destination %u", (uint)index);
 
 	sceneBlockPackRuntimeState();
-	uint32 offset = (uint32)(index - 1) * _sceneMemoryBlock.size();
-	if (offset > _environmentData.size() || _sceneMemoryBlock.size() > _environmentData.size() - offset)
+	XmsMove move;
+	move.length = _sceneMemoryBlock.size();
+	move.destinationHandle = _xmsEnvHandle;
+	move.destinationOffset = (uint32)(index - 1) * _sceneMemoryBlock.size();
+	move.sourceMemory = source;
+	if (xmsTransfer(move) < 0)
 		error("Environment XMS destination %u is outside the allocated block", (uint)index);
-
-	memcpy(&_environmentData[offset], source, _sceneMemoryBlock.size());
 }
 
 bool ComfyEngine::envXmsToConv(byte *destination, uint16 index) {
 	if (!index || _sceneMemoryBlock.empty())
 		error("Invalid environment XMS source %u", (uint)index);
 
-	uint32 offset = (uint32)(index - 1) * _sceneMemoryBlock.size();
-	if (offset > _environmentData.size() || _sceneMemoryBlock.size() > _environmentData.size() - offset)
+	XmsMove move;
+	move.length = _sceneMemoryBlock.size();
+	move.sourceHandle = _xmsEnvHandle;
+	move.sourceOffset = (uint32)(index - 1) * _sceneMemoryBlock.size();
+	move.destinationMemory = destination;
+	if (xmsTransfer(move) < 0)
 		error("Environment XMS source %u is outside the allocated block", (uint)index);
 
-	memcpy(destination, &_environmentData[offset], _sceneMemoryBlock.size());
 	sceneBlockUnpackRuntimeState();
 	return true;
 }
@@ -478,11 +483,12 @@ bool ComfyEngine::sceneEntryLoad(uint16 descriptor, uint16 index) {
 	uint16 size = READ_LE_UINT16(header);
 	uint32 fileOffset = READ_LE_UINT32(header + 2);
 	uint32 destinationOffset = (uint32)_sceneEntryFrameSize * index;
-	if (fileOffset > _midiFileData.size() || size > _midiFileData.size() - fileOffset ||
-			destinationOffset > _sceneFrameData.size() || size > _sceneFrameData.size() - destinationOffset)
+	if (!_midiFileStream || destinationOffset > _sceneFrameData.size() ||
+			size > _sceneFrameData.size() - destinationOffset || !_midiFileStream->seek(fileOffset))
 		return false;
 
-	memcpy(&_sceneFrameData[destinationOffset], &_midiFileData[fileOffset], size);
+	if (_midiFileStream->read(&_sceneFrameData[destinationOffset], size) != size)
+		return false;
 	if (index < COMFY_SCENE_ENTRY_OFFSET_CAPACITY)
 		_sceneEntryOffsets[index] = descriptor;
 
@@ -516,14 +522,14 @@ byte *ComfyEngine::spriteLoadFromFile(uint16 fileOffset, uint16 index) {
 		return nullptr;
 
 	byte *destination = sceneFrameGetPtr(index, size);
-	if (!destination || position > _midiFileData.size() || size > _midiFileData.size() - position) {
+	if (!destination || !_midiFileStream || !_midiFileStream->seek(position) ||
+			_midiFileStream->read(destination, size) != size) {
 		if (index < COMFY_MIDI_CHANNEL_COUNT)
 			_midiChannels[index].loadedFrameSize = 0;
 
 		return nullptr;
 	}
 
-	memcpy(destination, &_midiFileData[position], size);
 	return destination;
 }
 
@@ -573,14 +579,23 @@ bool ComfyEngine::sceneOpen(uint32 sceneEntryListOffset) {
 		memset(&_sceneFrameData[0], 0, _sceneFrameData.size());
 	}
 
-	if (_midiFileData.empty() || !midiPlyrStart())
+	delete _midiFileStream;
+	_midiFileStream = pathFOpen(Common::Path("MIDIFILE.DAT"), true);
+	if (!_midiFileStream)
+		return false;
+
+	byte header[4];
+	if (_midiFileStream->read(header, sizeof(header)) != sizeof(header) ||
+			header[0] != 'C' || (header[1] != 'M' && header[1] != 'm'))
+		return false;
+
+	_midiFileMode = header[1] == 'm' ? 1 : 0;
+	_midiEntryCount = READ_LE_UINT16(header + 2);
+	if (!midiPlyrStart())
 		return false;
 
 	_sceneOpen = true;
 	memset(_sceneEntryOffsets, 0, sizeof(_sceneEntryOffsets));
-	if (_engineVersion != 3)
-		midiInitInstance();
-
 	midiInitChannels();
 	return true;
 }
@@ -590,6 +605,8 @@ void ComfyEngine::sceneShutdown() {
 		return;
 
 	midiPlyrStop();
+	delete _midiFileStream;
+	_midiFileStream = nullptr;
 	_sceneFrameData.clear();
 	if (_engineVersion == 3) {
 		_wcomfy99VocState2 = 0xFF;
diff --git a/engines/comfy/script.cpp b/engines/comfy/script.cpp
index 6f477d80b29..0a74207ed27 100644
--- a/engines/comfy/script.cpp
+++ b/engines/comfy/script.cpp
@@ -27,29 +27,67 @@
 
 namespace Comfy {
 
-bool ComfyEngine::scriptHasRange(uint32 pc, uint32 width) {
-	uint32 tileOffset = pc % COMFY_TILE_SIZE;
-	uint32 tileBase = pc - tileOffset;
-	uint32 tileSize = tileBase < _picDataSize ? MIN<uint32>(COMFY_TILE_SIZE, _picDataSize - tileBase) : 0;
-	if (tileBase > _comfyObjData.size() || tileSize > _comfyObjData.size() - tileBase ||
-			tileOffset > tileSize || width > tileSize - tileOffset) {
+byte ComfyEngine::scriptReadByte(uint32 pc) {
+	uint16 tileIndex = (uint16)(pc / COMFY_TILE_SIZE);
+	uint16 tileOffset = (uint16)(pc % COMFY_TILE_SIZE);
+	int16 spriteId = (int16)(-(int16)tileIndex - 1);
+	SpriteResource *sprite = spriteGetPtr(spriteId);
+	uint16 frameId = (uint16)-spriteId;
+	if (!sprite || frameId >= _frameCacheEntries.size()) {
 		_scriptFault = true;
-		return false;
+		return 0;
 	}
 
-	return true;
-}
+	SpriteCacheEntry &entry = _frameCacheEntries[frameId];
+	uint32 offset = entry.poolOffset + 0x0C + tileOffset;
+	if (entry.slotSize == 0xFFFF || offset >= _scenePoolData.size()) {
+		_scriptFault = true;
+		return 0;
+	}
 
-byte ComfyEngine::scriptReadByte(uint32 pc) {
-	return scriptHasRange(pc, 1) ? _comfyObjData[pc] : 0;
+	return _scenePoolData[offset];
 }
 
 uint16 ComfyEngine::scriptReadWord(uint32 pc) {
-	return scriptHasRange(pc, 2) ? READ_LE_UINT16(&_comfyObjData[pc]) : 0;
+	uint16 tileIndex = (uint16)(pc / COMFY_TILE_SIZE);
+	uint16 tileOffset = (uint16)(pc % COMFY_TILE_SIZE);
+	int16 spriteId = (int16)(-(int16)tileIndex - 1);
+	SpriteResource *sprite = spriteGetPtr(spriteId);
+	uint16 frameId = (uint16)-spriteId;
+	if (!sprite || frameId >= _frameCacheEntries.size()) {
+		_scriptFault = true;
+		return 0;
+	}
+
+	SpriteCacheEntry &entry = _frameCacheEntries[frameId];
+	uint32 offset = entry.poolOffset + 0x0C + tileOffset;
+	if (entry.slotSize == 0xFFFF || offset > _scenePoolData.size() || 2 > _scenePoolData.size() - offset) {
+		_scriptFault = true;
+		return 0;
+	}
+
+	return READ_LE_UINT16(&_scenePoolData[offset]);
 }
 
 uint32 ComfyEngine::scriptReadDword(uint32 pc) {
-	return scriptHasRange(pc, 4) ? READ_LE_UINT32(&_comfyObjData[pc]) : 0;
+	uint16 tileIndex = (uint16)(pc / COMFY_TILE_SIZE);
+	uint16 tileOffset = (uint16)(pc % COMFY_TILE_SIZE);
+	int16 spriteId = (int16)(-(int16)tileIndex - 1);
+	SpriteResource *sprite = spriteGetPtr(spriteId);
+	uint16 frameId = (uint16)-spriteId;
+	if (!sprite || frameId >= _frameCacheEntries.size()) {
+		_scriptFault = true;
+		return 0;
+	}
+
+	SpriteCacheEntry &entry = _frameCacheEntries[frameId];
+	uint32 offset = entry.poolOffset + 0x0C + tileOffset;
+	if (entry.slotSize == 0xFFFF || offset > _scenePoolData.size() || 4 > _scenePoolData.size() - offset) {
+		_scriptFault = true;
+		return 0;
+	}
+
+	return READ_LE_UINT32(&_scenePoolData[offset]);
 }
 
 uint16 ComfyEngine::scriptReadStringIndex(uint32 pc) {
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index c2517461b9b..ff0bbdc44a0 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -996,10 +996,10 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		pc += 4;
 		uint32 size = endPc >= pc ? endPc - pc : 0;
 		size = MIN<uint32>(size, COMFY_FRAME_LOADER_DATA_BYTES);
-		if (pc <= _comfyObjData.size() && size <= _comfyObjData.size() - pc) {
+		if (_comfyObjFile && pc <= _comfyObjFile->fileSize && size <= _comfyObjFile->fileSize - pc) {
 			_frameLoaderData.resize(COMFY_FRAME_LOADER_DATA_BYTES);
 			if (size)
-				memcpy(&_frameLoaderData[0], &_comfyObjData[pc], size);
+				objFileReadField(&_frameLoaderData[0], pc, size, _comfyObjFile);
 		} else {
 			error("Script opcode 0x54 references data outside COMFY.OBJ");
 		}
diff --git a/engines/comfy/sound.cpp b/engines/comfy/sound.cpp
index 26fc81b7355..1620fc54ab3 100644
--- a/engines/comfy/sound.cpp
+++ b/engines/comfy/sound.cpp
@@ -35,6 +35,8 @@ namespace Comfy {
 
 struct SoundDecoderState {
 public:
+	// soundPrepareDecoderState() collects an embedded ANM sound into one temporary buffer.
+	// This constructor copies those bytes, so decoding no longer needs the engine or a file.
 	SoundDecoderState(const byte *data, uint32 size, bool compressed) {
 		_data.resize(size);
 		if (size)
@@ -42,6 +44,7 @@ public:
 
 		_compressed = compressed;
 		_end = size;
+		_windowEnd = size;
 		if (_compressed) {
 			if (size < 5) {
 				_fault = true;
@@ -57,7 +60,40 @@ public:
 		}
 	}
 
+	// A regular VOC entry remains in VOCFILE.DAT. This constructor retains the engine and
+	// file object so loadSourceWindow() can read each block through objFileReadTiledCore().
+	SoundDecoderState(ComfyEngine *engine, ComfyEngine::ObjFile *objectFile,
+			uint32 sourceBase, uint32 size, bool compressed) {
+		_engine = engine;
+		_objectFile = objectFile;
+		_sourceBase = sourceBase;
+		_compressed = compressed;
+		_end = size;
+		if (!loadSourceWindow(6)) {
+			_fault = true;
+			return;
+		}
+
+		if (_compressed) {
+			if (size < 5) {
+				_fault = true;
+				return;
+			}
+
+			setSample(sourceByte(4));
+			_position = 5;
+		} else if (size >= 6 && sourceByte(0) == 1) {
+			setSample(sourceByte(4));
+		} else {
+			setSample(_sample);
+		}
+	}
+
 	uint32 decode(byte *buffer, uint32 size) {
+		_decodeBlockSize = size;
+		if (_objectFile && !_started && !loadSourceWindow(size))
+			return 0;
+
 		uint32 written = 0;
 		while (written < size && !_fault && !_finished) {
 			byte sample = 0x80;
@@ -71,7 +107,6 @@ public:
 	}
 
 	uint32 getRate() { return _sampleRate; }
-	bool finished() { return _finished; }
 
 	void copyCues(Common::Array<ComfyEngine::SoundCue> &cues) {
 		cues = _cues;
@@ -149,7 +184,7 @@ public:
 		_position = READ_LE_UINT32(packedState + 0x41);
 		_loopPosition = READ_LE_UINT32(packedState + 0x45);
 		uint32 packedEnd = READ_LE_UINT32(packedState + 0x49);
-		if (_position > _data.size() || _loopPosition > _data.size() || packedEnd > _data.size())
+		if (_position > _end || _loopPosition > _end || packedEnd > _end)
 			return false;
 
 		_end = packedEnd;
@@ -196,6 +231,69 @@ private:
 		bool started = false;
 	};
 
+	bool loadSourceWindow(uint32 size) {
+		if (!_objectFile)
+			return true;
+
+		if (!_engine || _position > _end)
+			return false;
+
+		uint32 remaining = _end - _position;
+		uint32 readSize = MIN<uint32>(size, remaining);
+		if (!_compressed)
+			readSize += 0xC8;
+
+		uint32 fileOffset = _sourceBase + _position;
+		if (fileOffset > _objectFile->fileSize)
+			return false;
+
+		if (readSize > _objectFile->fileSize - fileOffset)
+			readSize = _objectFile->fileSize - fileOffset;
+
+		if (!readSize) {
+			_data.clear();
+			_windowStart = _position;
+			_windowEnd = _position;
+			return true;
+		}
+
+		byte *source = _engine->objFileReadTiledCore(fileOffset, readSize, _objectFile);
+		if (!source)
+			return false;
+
+		_data.resize(readSize);
+		memcpy(&_data[0], source, readSize);
+		_windowStart = _position;
+		_windowEnd = _position + readSize;
+		return true;
+	}
+
+	byte sourceByte(uint32 position) {
+		if (position >= _end) {
+			_fault = true;
+			return 0;
+		}
+
+		if (_objectFile && (position < _windowStart || position >= _windowEnd)) {
+			uint32 savedPosition = _position;
+			_position = position;
+			bool loaded = loadSourceWindow(_decodeBlockSize ? _decodeBlockSize : 6);
+			_position = savedPosition;
+			if (!loaded) {
+				_fault = true;
+				return 0;
+			}
+		}
+
+		uint32 offset = position - _windowStart;
+		if (offset >= _data.size()) {
+			_fault = true;
+			return 0;
+		}
+
+		return _data[offset];
+	}
+
 	static uint32 calcSampleRate(byte sample) {
 		uint32 denominator = 0x100 - sample;
 		uint32 rate = denominator ? 0x0F4240 / denominator : 0x2B11;
@@ -295,6 +393,8 @@ private:
 	void seekToLoop() {
 		_position = _loopPosition;
 		_bitOffset = _loopBitOffset;
+		if (_objectFile && !loadSourceWindow(_decodeBlockSize))
+			_fault = true;
 	}
 
 	uint16 parseCommand() {
@@ -305,15 +405,15 @@ private:
 				return 0;
 			}
 
-			uint16 command = _data[_position++];
+			uint16 command = sourceByte(_position++);
 			if (command) {
 				if (_end - _position < 3) {
 					_fault = true;
 					return 0;
 				}
 
-				_eventArgument = (uint32)_data[_position] | ((uint32)_data[_position + 1] << 8) |
-					((uint32)_data[_position + 2] << 16);
+				_eventArgument = (uint32)sourceByte(_position) | ((uint32)sourceByte(_position + 1) << 8) |
+					((uint32)sourceByte(_position + 2) << 16);
 				_position += 3;
 			}
 
@@ -359,7 +459,7 @@ private:
 		}
 
 		_eventRemaining -= 2;
-		setSample(_data[_position]);
+		setSample(sourceByte(_position));
 		_position += 2;
 	}
 
@@ -385,7 +485,7 @@ private:
 				return false;
 			}
 
-			sample = _data[_position++];
+			sample = sourceByte(_position++);
 			_history.push_back(sample);
 			return true;
 		}
@@ -434,7 +534,7 @@ private:
 				return value;
 			}
 
-			value |= (uint32)((_data[_position] >> _bitOffset) & 1) << bit;
+			value |= (uint32)((sourceByte(_position) >> _bitOffset) & 1) << bit;
 			_bitOffset++;
 			if (_bitOffset == 8) {
 				_bitOffset = 0;
@@ -472,7 +572,7 @@ private:
 			return 0;
 		}
 
-		uint16 value = READ_LE_UINT16(&_data[_position]);
+		uint16 value = (uint16)(sourceByte(_position) | ((uint16)sourceByte(_position + 1) << 8));
 		_position += 2;
 		return value;
 	}
@@ -483,7 +583,7 @@ private:
 			return 0;
 		}
 
-		return _data[_position++];
+		return sourceByte(_position++);
 	}
 
 	void pushCue(uint16 value) {
@@ -500,6 +600,12 @@ private:
 	Common::Array<byte> _data;
 	Common::Array<byte> _history;
 	Common::Array<ComfyEngine::SoundCue> _cues;
+	ComfyEngine *_engine = nullptr;
+	ComfyEngine::ObjFile *_objectFile = nullptr;
+	uint32 _sourceBase = 0;
+	uint32 _windowStart = 0;
+	uint32 _windowEnd = 0;
+	uint32 _decodeBlockSize = 0;
 	uint32 _end = 0;
 	uint32 _position = 0;
 	uint32 _streamPosition = 0;
@@ -608,16 +714,34 @@ void ComfyEngine::wcomfy99RestoreHostStateAfterSceneStart() {
 	}
 }
 
-bool ComfyEngine::soundInit() {
-	if (!readAssetFile(Common::Path("VOCFILE.DAT"), _vocFileData) || _vocFileData.size() < 4)
+bool ComfyEngine::soundOpenVocFile() {
+	soundBufFree(_vocFile);
+	uint32 maximumBytes = 0x40000;
+	if (sysGetExtMemKB() < 0x0FA0)
+		maximumBytes /= 2;
+
+	_vocFile = objFileLoadSoundData(Common::Path("VOCFILE.DAT"), 0x8000, maximumBytes);
+	if (!_vocFile)
 		return false;
 
-	if (_vocFileData[0] != 'C' || (_vocFileData[1] != 'V' && _vocFileData[1] != 'W'))
+	byte header[4];
+	memset(header, 0, sizeof(header));
+	objFileReadFieldCore(header, 0, sizeof(header), _vocFile);
+	if (header[0] != 'C' || (header[1] != 'V' && header[1] != 'W')) {
+		soundBufFree(_vocFile);
 		return false;
+	}
 
-	_soundCompressed = _vocFileData[1] == 'W';
+	_soundCompressed = header[1] == 'W';
 	_soundUsesAnimData = false;
-	_soundEntryCount = assetsReadLe16At(_vocFileData, 2);
+	_soundEntryCount = READ_LE_UINT16(header + 2);
+	return true;
+}
+
+bool ComfyEngine::soundInit() {
+	if (!soundOpenVocFile())
+		return false;
+
 	_soundEventIndex = 0;
 	_soundEventMaximum = 0;
 	_soundEventSubIndex = 0xFFFF;
@@ -645,7 +769,7 @@ void ComfyEngine::soundShutdown() {
 	delete _soundDecoderState;
 	_soundDecoderState = nullptr;
 	_soundCues.clear();
-	_vocFileData.clear();
+	soundBufFree(_vocFile);
 	_soundEntryCount = 0;
 	_soundNextCue = 0;
 	_soundPaused = false;
@@ -704,12 +828,13 @@ bool ComfyEngine::soundLoadEntry(uint16 index) {
 	soundHdrReadFromXms(header, index, sizeof(header));
 	uint32 size = READ_LE_UINT32(header);
 	uint32 offset = READ_LE_UINT32(header + 4);
-	return offset <= _vocFileData.size() && size <= _vocFileData.size() - offset;
+	return _vocFile && offset <= _vocFile->fileSize && size <= _vocFile->fileSize - offset;
 }
 
 bool ComfyEngine::soundPrepareDecoderState(uint16 index) {
 	Common::Array<byte> animationSoundData;
 	byte *data = nullptr;
+	ObjFile *objectFile = nullptr;
 	uint32 fileSize = 0;
 	uint32 dataSize = 0;
 	uint32 dataOffset = 0;
@@ -778,8 +903,11 @@ bool ComfyEngine::soundPrepareDecoderState(uint16 index) {
 		soundHdrReadFromXms(header, index, sizeof(header));
 		dataSize = READ_LE_UINT32(header);
 		dataOffset = READ_LE_UINT32(header + 4);
-		data = &_vocFileData[0];
-		fileSize = _vocFileData.size();
+		if (!_vocFile || dataOffset > _vocFile->fileSize || dataSize > _vocFile->fileSize - dataOffset)
+			return false;
+
+		objectFile = _vocFile;
+		fileSize = _vocFile->fileSize;
 		_soundUsesAnimData = false;
 	}
 
@@ -787,7 +915,11 @@ bool ComfyEngine::soundPrepareDecoderState(uint16 index) {
 		return false;
 
 	delete _soundDecoderState;
-	_soundDecoderState = new SoundDecoderState(data + dataOffset, dataSize, compressed);
+	if (objectFile)
+		_soundDecoderState = new SoundDecoderState(this, objectFile, dataOffset, dataSize, compressed);
+	else
+		_soundDecoderState = new SoundDecoderState(data + dataOffset, dataSize, compressed);
+
 	if (_soundDecoderState->fault()) {
 		delete _soundDecoderState;
 		_soundDecoderState = nullptr;
diff --git a/engines/comfy/video.cpp b/engines/comfy/video.cpp
index 3315958cd15..6f03642bc52 100644
--- a/engines/comfy/video.cpp
+++ b/engines/comfy/video.cpp
@@ -45,9 +45,6 @@ void ComfyEngine::videoInit() {
 	_screen = new Graphics::Screen(_logicalScreenWidth, _logicalScreenHeight);
 	_framebufPtr = new byte[framebufferBytes()]();
 	_presentBuffer = new byte[framebufferBytes()]();
-	if (_isPanther)
-		_backgroundFramebuf.resize(framebufferBytes());
-
 	_backgroundFrame = 0;
 	_dirtyRectCount = 0;
 	_renderDirtyCount = 0;


Commit: 1c12b6c51191f1fea39dec2acdfcc32c7e6cdad1
    https://github.com/scummvm/scummvm/commit/1c12b6c51191f1fea39dec2acdfcc32c7e6cdad1
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Make ImGui virtual keyboard toggleable in the options

Also improve handling of toggleable keymapper keys

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/comfy_keyboard_ui.cpp
    engines/comfy/detection.h
    engines/comfy/detection_tables.h
    engines/comfy/input.cpp
    engines/comfy/metaengine.cpp
    engines/comfy/metaengine.h
    engines/comfy/midi.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 482a0e072c6..b219d0863bc 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -47,16 +47,14 @@ void onImGuiRender() {
 	if (!_state || !_state->_engine || _state->_engine->shouldQuit())
 		return;
 
-	if (!_state->_engine->_keyboardUiInitialized)
-		return;
-
 	bool actorDebugEnabled = debugChannelSet(-1, kDebugImGui);
 	if (actorDebugEnabled)
 		_state->_engine->drawActorDebugUi(&_state->_actorDebugVisible);
 	else
 		_state->_actorDebugVisible = false;
 
-	drawComfyKeyboardUi(actorDebugEnabled);
+	if (ConfMan.getBool("use_imgui_keyboard"))
+		drawComfyKeyboardUi(actorDebugEnabled);
 }
 
 void onImGuiCleanup() {
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index b4efe3e9cd7..75fde704974 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -45,6 +45,9 @@ class QueuingAudioStream;
 
 #define COMFY_SCREEN_WIDTH 320
 #define COMFY_SCREEN_HEIGHT 200
+#define COMFY_KEYBOARD_ON_CONTACT 7
+#define COMFY_KEYBOARD_HANDSET_CONTACT 13
+#define COMFY_KEYBOARD_TOGGLE_MASK ((uint32)(1 << COMFY_KEYBOARD_ON_CONTACT) | (uint32)(1 << COMFY_KEYBOARD_HANDSET_CONTACT))
 #define COMFY_PANTHER_SCREEN_WIDTH 640
 #define COMFY_PANTHER_SCREEN_HEIGHT 480
 #define COMFY_PIT_INPUT_FREQUENCY 1193182
diff --git a/engines/comfy/comfy_keyboard_ui.cpp b/engines/comfy/comfy_keyboard_ui.cpp
index 820fa5194d2..19c9086a774 100644
--- a/engines/comfy/comfy_keyboard_ui.cpp
+++ b/engines/comfy/comfy_keyboard_ui.cpp
@@ -157,7 +157,7 @@ void drawComfyKeyboardUi(bool actorDebugEnabled) {
 		draw->AddRect(origin, ImVec2(origin.x + 700, origin.y + 390), keyboardColor(110, 110, 105), 20, 0, 2);
 
 		ImGui::SetCursorPos(ImVec2(24, 46));
-		keyboardDrawToggle("HANDSET", 13, ImVec2(92, 258), handset, keyboardColor(248, 70, 54));
+		keyboardDrawToggle("HANDSET", COMFY_KEYBOARD_HANDSET_CONTACT, ImVec2(92, 258), handset, keyboardColor(248, 70, 54));
 
 		static const char *phoneLabels[] = {"SNAILY", "BUDDY", "JUMPY", "FEELY", "COMFY"};
 		static const uint phoneBits[] = {4, 16, 10, 22, 20};
@@ -174,7 +174,7 @@ void drawComfyKeyboardUi(bool actorDebugEnabled) {
 		keyboardDrawMomentary("STOP", 12, ImVec2(58, 58), blueDark);
 
 		ImGui::SetCursorPos(ImVec2(702, 82));
-		keyboardDrawToggle("ON\nOFF", 7, ImVec2(22, 78), keyboardColor(86, 91, 95), keyboardColor(40, 160, 72));
+		keyboardDrawToggle("ON\nOFF", COMFY_KEYBOARD_ON_CONTACT, ImVec2(22, 78), keyboardColor(86, 91, 95), keyboardColor(40, 160, 72));
 
 		ImGui::SetCursorPos(ImVec2(604, 132));
 		keyboardDrawMomentary("SUN", 0, ImVec2(80, 42), blue);
diff --git a/engines/comfy/detection.h b/engines/comfy/detection.h
index 17f07a632e2..ef143843007 100644
--- a/engines/comfy/detection.h
+++ b/engines/comfy/detection.h
@@ -59,6 +59,7 @@ extern const ComfyGameDescription gameDescriptions[];
 
 #define GAMEOPTION_FORCE_LANGUAGE_SETUP GUIO_GAMEOPTIONS1
 #define GAMEOPTION_SKIP_INTRO           GUIO_GAMEOPTIONS2
+#define GAMEOPTION_USE_IMGUI_KEYBOARD   GUIO_GAMEOPTIONS3
 
 } // End of namespace Comfy
 
diff --git a/engines/comfy/detection_tables.h b/engines/comfy/detection_tables.h
index 3a9a2eda169..1ad0e65d214 100644
--- a/engines/comfy/detection_tables.h
+++ b/engines/comfy/detection_tables.h
@@ -44,7 +44,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
+			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		1,
 		0,
@@ -63,7 +64,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
+			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		3,
 		0,
@@ -80,7 +82,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
+			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		2,
 		COMFY_SCRIPT_OPCODE_31,
@@ -96,7 +99,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
+			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		2,
 		COMFY_SCRIPT_OPCODE_31 | COMFY_SCRIPT_OPCODE_33,
@@ -112,7 +116,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
+			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		1,
 		0,
@@ -128,7 +133,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
+			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		2,
 		0,
@@ -145,7 +151,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
+			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		3,
 		0,
@@ -162,7 +169,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
+			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		3,
 		0,
@@ -179,7 +187,8 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
+			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		3,
 		0,
@@ -196,7 +205,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		2,
 		COMFY_SCRIPT_OPCODE_31 | COMFY_SCRIPT_OPCODE_32,
diff --git a/engines/comfy/input.cpp b/engines/comfy/input.cpp
index b29b727fa71..90e2862168a 100644
--- a/engines/comfy/input.cpp
+++ b/engines/comfy/input.cpp
@@ -199,6 +199,13 @@ void ComfyEngine::setKeyboardContact(uint16 contact, bool pressed, bool keymappe
 	uint32 mask = 1 << contact;
 	uint32 *activeMask = keymapper ? &_keymapperActiveMask : &_toyKeyboardActiveMask;
 	uint32 *latchedMask = keymapper ? &_keymapperLatchedMask : &_toyKeyboardLatchedMask;
+	if (keymapper && (contact == COMFY_KEYBOARD_ON_CONTACT || contact == COMFY_KEYBOARD_HANDSET_CONTACT)) {
+		if (pressed)
+			*activeMask ^= mask;
+
+		return;
+	}
+
 	if (pressed) {
 		*activeMask |= mask;
 		*latchedMask &= ~mask;
@@ -221,7 +228,7 @@ uint32 ComfyEngine::lptKeyboardScan() {
 	if (_engineVersion == 3 && _inputDeviceMode == 2) {
 		_keyboardActiveMask |= _keymapperActiveMask;
 		_keyboardLatchedMask |= _keymapperLatchedMask;
-		_keymapperActiveMask = 0;
+		_keymapperActiveMask &= COMFY_KEYBOARD_TOGGLE_MASK;
 		_keymapperLatchedMask = 0;
 	}
 
diff --git a/engines/comfy/metaengine.cpp b/engines/comfy/metaengine.cpp
index 89fc8fac483..f591f9d68b0 100644
--- a/engines/comfy/metaengine.cpp
+++ b/engines/comfy/metaengine.cpp
@@ -20,6 +20,7 @@
  */
 
 #include "common/translation.h"
+#include "common/config-manager.h"
 
 #include "backends/keymapper/action.h"
 #include "backends/keymapper/keymap.h"
@@ -53,6 +54,17 @@ static const ADExtraGuiOptionsMap optionsList[] = {
 			0
 		}
 	},
+	{
+		GAMEOPTION_USE_IMGUI_KEYBOARD,
+		{
+			_s("Use ImGui based virtual keyboard"),
+			_s("Show the interactive virtual Comfy keyboard implemented with ImGui"),
+			"use_imgui_keyboard",
+			true,
+			0,
+			0
+		}
+	},
 	AD_EXTRA_GUI_OPTIONS_TERMINATOR
 };
 
@@ -66,6 +78,11 @@ const ADExtraGuiOptionsMap *ComfyMetaEngine::getAdvancedExtraGuiOptions() const
 	return Comfy::optionsList;
 }
 
+void ComfyMetaEngine::registerDefaultSettings(const Common::String &) const {
+	for (const ADExtraGuiOptionsMap *entry = Comfy::optionsList; entry->guioFlag; ++entry)
+		ConfMan.registerDefault(entry->option.configOption, entry->option.defaultState);
+}
+
 Common::Error ComfyMetaEngine::createInstance(OSystem *syst, Engine **engine, const Comfy::ComfyGameDescription *desc) const {
 	*engine = new Comfy::ComfyEngine(syst, desc);
 	return Common::kNoError;
@@ -85,7 +102,7 @@ Common::KeymapArray ComfyMetaEngine::initKeymaps(const char *target) const {
 	};
 	static const char *actionNames[COMFY_KEYBOARD_CONTACT_COUNT] = {
 		_s("Sun"), _s("Rolling cylinder"), _s("Red"), _s("Drum"), _s("Snaily phone"), _s("Purple"),
-		_s("Piano"), _s("Power"), _s("Orange"), _s("Moon"), _s("Jumpy phone"), _s("Yellow"),
+		_s("Piano"), _s("On / off"), _s("Orange"), _s("Moon"), _s("Jumpy phone"), _s("Yellow"),
 		_s("Stop"), _s("Handset"), _s("Blue"), _s("Trumpet"), _s("Buddy phone"), _s("Green"),
 		_s("Flute"), _s("Keyboard contact 19"), _s("Comfy phone"), _s("Rainy cloud"),
 		_s("Feely phone"), _s("Music")
diff --git a/engines/comfy/metaengine.h b/engines/comfy/metaengine.h
index 806d34be914..9514535ce43 100644
--- a/engines/comfy/metaengine.h
+++ b/engines/comfy/metaengine.h
@@ -38,6 +38,7 @@ public:
 	bool hasFeature(MetaEngineFeature f) const override;
 
 	const ADExtraGuiOptionsMap *getAdvancedExtraGuiOptions() const override;
+	void registerDefaultSettings(const Common::String &target) const override;
 	Common::KeymapArray initKeymaps(const char *target) const override;
 };
 
diff --git a/engines/comfy/midi.cpp b/engines/comfy/midi.cpp
index add652c924d..70238f48717 100644
--- a/engines/comfy/midi.cpp
+++ b/engines/comfy/midi.cpp
@@ -73,8 +73,8 @@ uint16 ComfyEngine::midiTick() {
 
 			_system->delayMillis(1);
 		}
-	} while ((_engineVersion == 3 && _midiTimeCounter <= previousCounter) ||
-		(_engineVersion != 3 && _midiTimeCounter == previousCounter));
+	} while (!shouldQuit() && ((_engineVersion == 3 && _midiTimeCounter <= previousCounter) ||
+		(_engineVersion != 3 && _midiTimeCounter == previousCounter)));
 
 	_midiInstanceEventTime = _midiTimeCounter;
 	_midiEventBaseTime = (int32)_midiInstanceEventTime;


Commit: a8cfb38daa6e70e6d60260425a45095c92b70238
    https://github.com/scummvm/scummvm/commit/a8cfb38daa6e70e6d60260425a45095c92b70238
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Fix exit handling

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/comfy_keyboard_ui.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index b219d0863bc..a3e36dddada 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -31,6 +31,11 @@
 #include "engines/util.h"
 #include "graphics/paletteman.h"
 
+#ifdef USE_IMGUI
+#include "backends/imgui/imgui.h"
+#include "gui/gui-manager.h"
+#endif
+
 namespace Comfy {
 
 ComfyEngine *g_engine;
@@ -44,9 +49,17 @@ void onImGuiInit() {
 }
 
 void onImGuiRender() {
-	if (!_state || !_state->_engine || _state->_engine->shouldQuit())
+	if (!_state || !_state->_engine || _state->_closing || _state->_engine->shouldQuit())
 		return;
 
+	ImGuiIO &io = ImGui::GetIO();
+	if (GUI::GuiManager::instance().isActive()) {
+		io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange | ImGuiConfigFlags_NoMouse;
+		return;
+	}
+
+	io.ConfigFlags &= ~(ImGuiConfigFlags_NoMouseCursorChange | ImGuiConfigFlags_NoMouse);
+
 	bool actorDebugEnabled = debugChannelSet(-1, kDebugImGui);
 	if (actorDebugEnabled)
 		_state->_engine->drawActorDebugUi(&_state->_actorDebugVisible);
@@ -170,14 +183,26 @@ Common::Error ComfyEngine::gameInit() {
 
 	gameShutdown();
 
-#ifdef USE_IMGUI
-	_system->setImGuiCallbacks(ImGuiCallbacks());
-#endif
-
 	return Common::kNoError;
 }
 
 void ComfyEngine::gameShutdown() {
+#ifdef USE_IMGUI
+	// Submit an empty ImGui frame so the backend releases detached platform windows.
+	if (_state) {
+		_state->_closing = true;
+		ImGuiIO &io = ImGui::GetIO();
+		// Ignore the last Comfy window's cursor state while clearing input capture.
+		io.ConfigFlags |= ImGuiConfigFlags_NoMouse;
+		ImGui::SetNextFrameWantCaptureMouse(false);
+		ImGui::SetNextFrameWantCaptureKeyboard(false);
+		_system->updateScreen();
+		io.ConfigFlags &= ~ImGuiConfigFlags_NoMouse;
+	}
+
+	_system->setImGuiCallbacks(ImGuiCallbacks());
+#endif
+
 	if (_lptKeyboardInitialized) {
 		lptKeyboardShutdown();
 		midiShutdown();
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 75fde704974..ab7086446cb 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -116,6 +116,7 @@ typedef struct ImGuiState {
 	uint16 _actorDebugLastScene = 0xFFFF;
 	uint32 _actorDebugLastSceneGeneration = 0xFFFFFFFF;
 	bool _visible = true;
+	bool _closing = false;
 	bool _actorDebugVisible = false;
 	bool _actorDebugTreeView = false;
 } ImGuiState;
diff --git a/engines/comfy/comfy_keyboard_ui.cpp b/engines/comfy/comfy_keyboard_ui.cpp
index 19c9086a774..74eae2b7099 100644
--- a/engines/comfy/comfy_keyboard_ui.cpp
+++ b/engines/comfy/comfy_keyboard_ui.cpp
@@ -120,7 +120,7 @@ static void keyboardDrawToggle(const char *label, uint bit, ImVec2 size, ImU32 o
 }
 
 void drawComfyKeyboardUi(bool actorDebugEnabled) {
-	if (!_state->_engine->_keyboardUiInitialized)
+	if (!_state->_engine || !_state->_engine->_keyboardUiInitialized)
 		return;
 
 	if (!_state->_visible) {
@@ -159,7 +159,8 @@ void drawComfyKeyboardUi(bool actorDebugEnabled) {
 		ImGui::SetCursorPos(ImVec2(24, 46));
 		keyboardDrawToggle("HANDSET", COMFY_KEYBOARD_HANDSET_CONTACT, ImVec2(92, 258), handset, keyboardColor(248, 70, 54));
 
-		static const char *phoneLabels[] = {"SNAILY", "BUDDY", "JUMPY", "FEELY", "COMFY"};
+		
+		const char *phoneLabels[] = {"SNAILY", "BUDDY", "JUMPY", "FEELY", "COMFY"};
 		static const uint phoneBits[] = {4, 16, 10, 22, 20};
 
 		for (uint i = 0; i < ARRAYSIZE(phoneBits); i++) {


Commit: 51d8a8dea7126053b23bdca82bb23e007be5d18f
    https://github.com/scummvm/scummvm/commit/51d8a8dea7126053b23bdca82bb23e007be5d18f
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Great clean-up pass

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/anim_file.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/debug.cpp
    engines/comfy/expr.cpp
    engines/comfy/game.cpp
    engines/comfy/memory.cpp
    engines/comfy/midi.cpp
    engines/comfy/object_file.cpp
    engines/comfy/scene.cpp
    engines/comfy/script.cpp
    engines/comfy/script_vm.cpp
    engines/comfy/sound.cpp
    engines/comfy/timer.cpp
    engines/comfy/video.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index 8791bfc11cc..bd102dfd43c 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -481,7 +481,7 @@ void ComfyEngine::spriteBlitRle(byte *destination, const byte *source, uint32 so
 }
 
 void ComfyEngine::backgroundTransitionFrames(uint16 frame, uint16 previousFrame) {
-	if (_isPanther) {
+	if (_backgroundBufferEnabled) {
 		if (frame == previousFrame || !frame || _backgroundFramebuf.empty())
 			return;
 
@@ -513,7 +513,7 @@ void ComfyEngine::backgroundTransitionFrames(uint16 frame, uint16 previousFrame)
 		framebufClear(_framebufPtr, color);
 	}
 
-	videoSetResolution();
+	renderAddFullFrameDirtyRect();
 }
 
 void ComfyEngine::backgroundRestoreDirtyRects() {
@@ -542,7 +542,7 @@ void ComfyEngine::spriteBlitClipped(int16 spriteId, int16 x, int16 y) {
 	SpriteResource &sprite = *loadedSprite;
 	if (sprite.header.width == _logicalScreenWidth && sprite.header.height == _logicalScreenHeight) {
 		spriteBlitRle(_framebufPtr, &sprite.pixels[0], sprite.pixels.size());
-		renderSetDirty();
+		renderRequestFullFrameInvalidation();
 		return;
 	}
 
@@ -584,7 +584,7 @@ void ComfyEngine::spriteBlitClipped(int16 spriteId, int16 x, int16 y) {
 		rowPos += rowSize;
 	}
 
-	renderSetDirty();
+	renderRequestFullFrameInvalidation();
 }
 
 bool ComfyEngine::spriteCoversPoint(int16 spriteId, int16 x, int16 y, int16 pointX, int16 pointY) {
@@ -641,6 +641,53 @@ bool ComfyEngine::spriteCoversPoint(int16 spriteId, int16 x, int16 y, int16 poin
 	return false;
 }
 
+bool ComfyEngine::actorTestMouseHit(Actor &actor, bool useBlitHit) {
+	int32 xFixed = actor.xFixed;
+	int32 yFixed = actor.yFixed;
+	Actor *currentActor = &actor;
+	uint32 selector = actor.spriteSelector;
+
+	if (useBlitHit)
+		return actor.blitHitMouse != 0;
+
+	if ((selector & 0xFF000000) || !selector)
+		return false;
+
+	while (currentActor->parent) {
+		currentActor = actorGetPtr(currentActor->parent);
+		if (!currentActor)
+			return false;
+
+		xFixed = (int32)((uint32)xFixed + (uint32)currentActor->xFixed);
+		yFixed = (int32)((uint32)yFixed + (uint32)currentActor->yFixed);
+	}
+
+	int16 x = (int16)(xFixed >> 12);
+	int16 y = (int16)(yFixed >> 12);
+	int16 right;
+	int16 bottom;
+	if (selector == 0x00FFFFFF) {
+		uint16 width = 0;
+		uint16 height = 0;
+		if (!animFrameGetDimensions(width, height))
+			return false;
+
+		right = (int16)(x + width);
+		bottom = (int16)(y + height);
+	} else {
+		SpriteResource *sprite = spriteLookup((uint16)selector, x, y);
+		if (!sprite)
+			return false;
+
+		x -= sprite->header.hotspotX;
+		right = (int16)(x + sprite->header.width);
+		y -= sprite->header.hotspotY;
+		bottom = (int16)(y + sprite->header.height);
+	}
+
+	return _mouseX >= x && _mouseX < right && _mouseY >= y && _mouseY < bottom;
+}
+
 ComfyEngine::Actor *ComfyEngine::actorGetPtr(uint16 actorIndex) {
 	return actorIndex < _actors.size() ? &_actors[actorIndex] : nullptr;
 }
@@ -885,7 +932,7 @@ void ComfyEngine::actorFreeTreePc(uint16 actorIndex) {
 		return;
 
 	if (!_usesAnimFile && _videoMode == 2)
-		videoFindBestMode(actor->cachedRect);
+		renderAddDirtyRect(actor->cachedRect);
 
 	actorFreePcChain(*actor);
 
@@ -911,7 +958,7 @@ void ComfyEngine::actorFreeTreePc(uint16 actorIndex) {
 			if (selector & 0xFF000000) {
 				renderInvalidateFullFrame();
 			} else if (selector != 0x00FFFFFF) {
-				videoFindBestMode(actor->cachedRect);
+			renderAddDirtyRect(actor->cachedRect);
 			}
 		}
 
@@ -1115,7 +1162,7 @@ bool ComfyEngine::actorTickTree(uint16 actorIndex) {
 
 void ComfyEngine::actorDrawList(uint16 actorIndex, int16 x, int16 y, bool visible) {
 	while (actorIndex) {
-		if (_usesAnimFile)
+		if (_engineVersion == 3 || _usesAnimFile)
 			actorDrawInternal(actorIndex, x, y, visible);
 		else
 			actorDraw(actorIndex, x, y);
@@ -1144,7 +1191,7 @@ void ComfyEngine::renderQueueDrawCommand(int16 x, int16 y, uint32 selector, byte
 }
 
 void ComfyEngine::renderFlushDrawCommands() {
-	if ((_isPanther || _engineVersion == 3) && actorGetFrame())
+	if (_backgroundBufferEnabled && actorGetFrame())
 		backgroundRestoreDirtyRects();
 
 	for (uint i = 0; i < _drawCommandCount; i++) {
@@ -1166,7 +1213,7 @@ void ComfyEngine::renderFlushDrawCommands() {
 					dirtyRect.right = nextCommand.x + nextSprite->header.width;
 					dirtyRect.bottom = nextCommand.y + nextSprite->header.height;
 					dirtyRect.area = (uint32)nextSprite->header.width * nextSprite->header.height;
-					videoFindBestMode(dirtyRect);
+					renderAddDirtyRect(dirtyRect);
 				}
 			}
 
@@ -1200,7 +1247,7 @@ void ComfyEngine::renderFlushDrawCommands() {
 			dirtyRect.right = command.x + sprite->header.width;
 			dirtyRect.bottom = command.y + sprite->header.height;
 			dirtyRect.area = (uint32)sprite->header.width * sprite->header.height;
-			videoFindBestMode(dirtyRect);
+			renderAddDirtyRect(dirtyRect);
 		}
 	}
 
@@ -1209,7 +1256,7 @@ void ComfyEngine::renderFlushDrawCommands() {
 
 void ComfyEngine::renderFlushCachedDirtyRects() {
 	for (uint i = 0; i < _animFrameDirtyRectCount; i++)
-		videoFindBestMode(_animFrameDirtyRects[i]);
+		renderAddDirtyRect(_animFrameDirtyRects[i]);
 }
 
 uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, ComfyRect &maskRecord,
@@ -1340,11 +1387,11 @@ void ComfyEngine::actorEvalFrameSelection(uint16 actorIndex, int16 x, int16 y) {
 				if (_engineVersion == 1)
 					dirtyRect.area = (uint16)dirtyRect.area;
 
-				videoFindBestMode(dirtyRect);
+				renderAddDirtyRect(dirtyRect);
 			}
 		}
 	} else {
-		videoFindBestMode(rect);
+		renderAddDirtyRect(rect);
 	}
 
 	actor->cachedSprite = 0;
@@ -1388,18 +1435,17 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 	}
 
 	animFrameRecordVocCounter(1);
-	bool queuedActorDraw = _usesAnimFile && (_isPanther || _engineVersion == 3) && (_videoMode == 2 || _videoMode == 4);
+	bool queuedActorDraw = (_isPanther || _engineVersion == 3) && (_videoMode == 2 || _videoMode == 4);
 	if ((_isPanther || _engineVersion == 3) && !queuedActorDraw)
 		actorDrawLegacyInternal(actorIndex, x, y);
 	else
 		actorDrawInternal(actorIndex, x, y, true);
 
-	if (_usesAnimFile) {
-		if (queuedActorDraw)
-			renderFlushDrawCommands();
+	if (queuedActorDraw)
+		renderFlushDrawCommands();
 
+	if (_usesAnimFile || _isPanther || _engineVersion == 3)
 		animFrameRecordVocCounter(2);
-	}
 
 	return animFrameShouldDraw(2);
 }
@@ -1562,7 +1608,7 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 						currentRect.bottom == previousRect.bottom &&
 						currentRect.area == previousRect.area;
 					if (!equal)
-						videoFindBestMode(previousRect);
+						renderAddDirtyRect(previousRect);
 
 					renderQueueDrawCommand(currentRect.left, currentRect.top,
 						currentRect.area, equal ? 1 : 0, actorIndex);
@@ -1603,10 +1649,10 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 
 					if (oldLastRect != 0xFFFF) {
 						for (uint i = 0; i <= oldLastRect; i++)
-							videoFindBestMode(_keymaskOldRects[i]);
+								renderAddDirtyRect(_keymaskOldRects[i]);
 					}
 				} else {
-					videoFindBestMode(oldRect);
+						renderAddDirtyRect(oldRect);
 				}
 			}
 
@@ -1770,7 +1816,7 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 							if (_engineVersion == 1)
 								dirtyRect.area = (uint16)dirtyRect.area;
 
-							videoFindBestMode(dirtyRect);
+							renderAddDirtyRect(dirtyRect);
 						}
 
 						if (newItem) {
@@ -1780,7 +1826,7 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 							if (_engineVersion == 1)
 								dirtyRect.area = (uint16)dirtyRect.area;
 
-							videoFindBestMode(dirtyRect);
+							renderAddDirtyRect(dirtyRect);
 						}
 					}
 				}
@@ -1794,10 +1840,10 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 					if (_engineVersion == 1)
 						dirtyRect.area = (uint16)dirtyRect.area;
 
-					videoFindBestMode(dirtyRect);
+					renderAddDirtyRect(dirtyRect);
 				}
 			} else if (!newScripted && selector != 0x00FFFFFF) {
-				videoFindBestMode(newRect);
+				renderAddDirtyRect(newRect);
 			}
 
 			if (!comparedScriptRects) {
@@ -1809,12 +1855,12 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 						if (_engineVersion == 1)
 							dirtyRect.area = (uint16)dirtyRect.area;
 
-						videoFindBestMode(dirtyRect);
+						renderAddDirtyRect(dirtyRect);
 					}
 				} else if (oldSelector == 0x00FFFFFF) {
 					animFrameInvalidateRects(oldRect.left, oldRect.top, 0);
 				} else if (!oldScripted) {
-					videoFindBestMode(oldRect);
+					renderAddDirtyRect(oldRect);
 				}
 			}
 		}
diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
index 20a6a6b4c02..540098b0d19 100644
--- a/engines/comfy/anim_file.cpp
+++ b/engines/comfy/anim_file.cpp
@@ -460,7 +460,7 @@ void ComfyEngine::animFileTickCommands() {
 					animDecompressRle(payload, payloadSize, &_animFrameBuffer[0], _animFrameBuffer.size());
 					if (_framebufPtr) {
 						memcpy(_framebufPtr, &_animFrameBuffer[0], COMFY_ANMFRAME_BYTES);
-						renderSetDirty();
+						renderRequestFullFrameInvalidation();
 					}
 				}
 			}
@@ -664,7 +664,7 @@ void ComfyEngine::animFrameInvalidateRects(int16 x, int16 y, byte mode) {
 
 		if (i < splitIndex) {
 			if (!mode)
-				videoFindBestMode(rect);
+				renderAddDirtyRect(rect);
 
 			continue;
 		}
@@ -684,7 +684,7 @@ void ComfyEngine::animFrameInvalidateRects(int16 x, int16 y, byte mode) {
 		}
 
 		if (mode)
-			videoFindBestMode(rect);
+			renderAddDirtyRect(rect);
 	}
 }
 
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index a3e36dddada..f3c9d359462 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -40,6 +40,17 @@ namespace Comfy {
 
 ComfyEngine *g_engine;
 
+void ComfyEngine::configRunPendingCommand() {
+	if (!_v3ConfigCommandPending)
+		return;
+
+	_v3ConfigCommandPending = false;
+
+	// The original starts the stored command with WinExec or ShellExecute, which has no engine-side equivalent.
+	warning("configRunPendingCommand reached, this is probably a dev path! Values: command=%u value=%u text=%s",
+		_v3ConfigCommandSubop, _v3ConfigCommandValue, _v3ConfigCommandText.c_str());
+}
+
 #ifdef USE_IMGUI
 ImGuiState *_state = nullptr;
 
@@ -83,6 +94,7 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ComfyGameDescription *gameDesc) :
 	_randomSource("Comfy"),
 	_logicalScreenWidth(!strcmp(gameDesc->desc.gameId, "panther") ? COMFY_PANTHER_SCREEN_WIDTH : COMFY_SCREEN_WIDTH),
 	_logicalScreenHeight(!strcmp(gameDesc->desc.gameId, "panther") ? COMFY_PANTHER_SCREEN_HEIGHT : COMFY_SCREEN_HEIGHT) {
+
 	memset(_paletteFadeSource, 0, sizeof(_paletteFadeSource));
 	memset(_paletteTarget, 0, sizeof(_paletteTarget));
 	memset(_paletteDisplay, 0, sizeof(_paletteDisplay));
@@ -96,8 +108,13 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ComfyGameDescription *gameDesc) :
 	memset(_animStorageChunkFileOffsets, 0, sizeof(_animStorageChunkFileOffsets));
 	memset(_animStorageChunkOffsets, 0, sizeof(_animStorageChunkOffsets));
 	memset(_animStorageChunkSizes, 0, sizeof(_animStorageChunkSizes));
+	memset(_actorPcTable, 0, sizeof(_actorPcTable));
+	memset(_exprStack, 0, sizeof(_exprStack));
+	memset(_sceneEntryOffsets, 0, sizeof(_sceneEntryOffsets));
+
 	if (!strcmp(gameDesc->desc.gameId, "panther")) {
 		_isPanther = true;
+		_backgroundBufferEnabled = true;
 		_vocQueueCapacity = COMFY_PANTHER_VOC_QUEUE_CAPACITY;
 	}
 
@@ -138,9 +155,11 @@ Common::Error ComfyEngine::gameInit() {
 	_gameInitialized = true;
 	_currentScene = _language;
 	uint16 chooserScene = 2;
+
 	if (_multiLanguage && (ConfMan.getBool("force_language_setup") ||
 			!ConfMan.getBool("comfy_language_chosen"))) {
-		if (!iniGetGameDataPath(99)) {
+		if (!iniSelectGameDataPath(99)) {
+			configRunPendingCommand();
 			gameShutdown();
 			return Common::kNoGameDataFoundError;
 		}
@@ -149,23 +168,25 @@ Common::Error ComfyEngine::gameInit() {
 		if (selectedLanguage) {
 			_currentScene = selectedLanguage;
 			chooserScene = selectedLanguage;
-			iniWriteLanguage(selectedLanguage);
+			iniWriteLanguageSelection(selectedLanguage);
 		}
 
 		ConfMan.setBool("comfy_language_chosen", true);
 		ConfMan.flushToDisk();
 	}
 
-	if (!_introDirectory.empty() && !ConfMan.getBool("skip_intro") && iniGetGameDataPath(0)) {
+	if (!_introDirectory.empty() && !ConfMan.getBool("skip_intro") && iniSelectGameDataPath(0)) {
 		sceneRun(_currentScene, false, true);
 		if (shouldQuit()) {
+			configRunPendingCommand();
 			gameShutdown();
 			return Common::kNoError;
 		}
 	}
 
 	while (_currentScene && !shouldQuit()) {
-		if (!iniGetGameDataPath(_currentScene)) {
+		if (!iniSelectGameDataPath(_currentScene)) {
+			configRunPendingCommand();
 			gameShutdown();
 			return Common::kNoGameDataFoundError;
 		}
@@ -178,9 +199,10 @@ Common::Error ComfyEngine::gameInit() {
 		}
 
 		if (_currentScene && _currentScene != 99)
-			iniWriteLanguage(_currentScene);
+			iniWriteLanguageSelection(_currentScene);
 	}
 
+	configRunPendingCommand();
 	gameShutdown();
 
 	return Common::kNoError;
@@ -188,11 +210,12 @@ Common::Error ComfyEngine::gameInit() {
 
 void ComfyEngine::gameShutdown() {
 #ifdef USE_IMGUI
-	// Submit an empty ImGui frame so the backend releases detached platform windows.
+	// Submit an empty ImGui frame so the backend releases detached platform windows...
 	if (_state) {
 		_state->_closing = true;
 		ImGuiIO &io = ImGui::GetIO();
-		// Ignore the last Comfy window's cursor state while clearing input capture.
+
+		// Ignore the last Comfy Keyboard window's cursor state while clearing input capture...
 		io.ConfigFlags |= ImGuiConfigFlags_NoMouse;
 		ImGui::SetNextFrameWantCaptureMouse(false);
 		ImGui::SetNextFrameWantCaptureKeyboard(false);
@@ -224,17 +247,6 @@ void ComfyEngine::gameShutdown() {
 	_gameInitialized = false;
 }
 
-void ComfyEngine::timerInit() {
-	if (_timerInitialized)
-		return;
-
-	_timerInitialized = true;
-}
-
-void ComfyEngine::timerShutdown() {
-	_timerInitialized = false;
-}
-
 uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
 	byte restorePalette = 1;
 	byte shouldStartNext = 0;
@@ -271,10 +283,10 @@ uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
 		nextScene = sceneId;
 		_languageSessionRestartRequested = false;
 	} else if (checkNext) {
-		if (sceneGetActiveCount() > 1 && _midiHandles.size() > 1)
-			nextScene = midiGetHandle(1);
+		if (sceneGetActiveCount() > 1 && _scriptVariables.size() > 1)
+			nextScene = scriptVariableGet(1);
 
-		if ((int16)nextScene > 0 && (int16)nextScene < 0x65 && nextScene != sceneId)
+		if ((int16)nextScene > 0 && (int16)nextScene < 101 && nextScene != sceneId)
 			shouldStartNext = 1;
 
 		if (_engineVersion == 3)
@@ -290,6 +302,7 @@ uint16 ComfyEngine::sceneRun(uint16 sceneId, bool checkNext, bool exitFlag) {
 	midiShutdown();
 	assetsUnload(0);
 	inputQueueReset();
+
 	if (_engineVersion != 3) {
 		_sceneRunBuffer.clear();
 		_sceneRunPtr = nullptr;
@@ -314,25 +327,29 @@ void ComfyEngine::processEvents() {
 		case Common::EVENT_CUSTOM_ENGINE_ACTION_START:
 			if (event.customType >= kActionKeyboardContact0 && event.customType <= kActionKeyboardContactLast)
 				setKeyboardContact(event.customType - kActionKeyboardContact0, true, true);
+
 			break;
 		case Common::EVENT_CUSTOM_ENGINE_ACTION_END:
 			if (event.customType >= kActionKeyboardContact0 && event.customType <= kActionKeyboardContactLast)
 				setKeyboardContact(event.customType - kActionKeyboardContact0, false, true);
+
 			break;
 		case Common::EVENT_KEYDOWN:
 			if (!event.kbdRepeat) {
 				hostKeyboardSetKeyState(hostKeyboardVirtualKey(event.kbd.keycode), true);
-				if (event.kbd.keycode == Common::KEYCODE_UP)
+				if (event.kbd.keycode == Common::KEYCODE_UP) {
 					inputQueuePushKey(0x48);
-				else if (event.kbd.keycode == Common::KEYCODE_DOWN)
+				} else if (event.kbd.keycode == Common::KEYCODE_DOWN) {
 					inputQueuePushKey(0x50);
-				else if (event.kbd.keycode == Common::KEYCODE_LEFT)
+				} else if (event.kbd.keycode == Common::KEYCODE_LEFT) {
 					inputQueuePushKey(0x4B);
-				else if (event.kbd.keycode == Common::KEYCODE_RIGHT)
+				} else if (event.kbd.keycode == Common::KEYCODE_RIGHT) {
 					inputQueuePushKey(0x4D);
-				else if (event.kbd.ascii)
+				} else if (event.kbd.ascii) {
 					inputQueuePushChar(event.kbd.ascii);
+				}
 			}
+
 			break;
 		case Common::EVENT_KEYUP:
 			hostKeyboardSetKeyState(hostKeyboardVirtualKey(event.kbd.keycode), false);
@@ -342,26 +359,31 @@ void ComfyEngine::processEvents() {
 				_mouseX = CLIP<int16>((int32)event.mouse.x * 320 / _logicalScreenWidth, 0, 319);
 				_mouseY = CLIP<int16>((int32)event.mouse.y * 200 / _logicalScreenHeight, 0, 199);
 			}
+
 			break;
 		case Common::EVENT_LBUTTONDOWN:
 			if (_engineVersion == 3) {
 				_mouseLeftButton = true;
 				_mouseLeftButtonEdge = false;
 			}
+
 			break;
 		case Common::EVENT_LBUTTONUP:
 			if (_engineVersion == 3)
 				_mouseLeftButtonEdge = true;
+
 			break;
 		case Common::EVENT_RBUTTONDOWN:
 			if (_engineVersion == 3) {
 				_mouseRightButton = true;
 				_mouseRightButtonEdge = false;
 			}
+
 			break;
 		case Common::EVENT_RBUTTONUP:
 			if (_engineVersion == 3)
 				_mouseRightButtonEdge = true;
+
 			break;
 		default:
 			break;
@@ -430,7 +452,8 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 	if (_engineVersion == 3)
 		midiInitInstance();
 
-	actorInit(1, 0, 1, 1, 0x14, 0, 0, 0, 1);
+	actorInit(1, 0, 1, 1, 20, 0, 0, 0, 1);
+
 	if (_engineVersion == 3)
 		mouseSetActor(nullptr);
 
@@ -440,11 +463,13 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 
 	uint16 rootIndex = sceneGetHandle(1);
 	Actor *mainLoopActor = actorGetPtr(rootIndex);
+
 	paletteLoadWithFade(0, 0);
 	paletteVsyncFlip();
 	paletteVsyncFlip();
-	if (sceneGetActiveCount() && _midiHandles.size() > 1)
-		midiHandleAddTo(1, argument);
+
+	if (sceneGetActiveCount() && _scriptVariables.size() > 1)
+		scriptVariableAddTo(1, argument);
 
 	while (keepRunning && !shouldQuit()) {
 		_pendingScene = 0;
@@ -455,6 +480,7 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 		midiTrackTickAndRemove();
 		animFileTickCommands();
 		sceneTickEvent();
+
 		if (!_musicEnabled)
 			midiPollChannels(ticks);
 
@@ -462,6 +488,7 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 		lptKeyboardScanAndProcess();
 		lptKeyToFlags(lastKey);
 		actorTickTree(rootIndex);
+
 		if (_engineVersion == 3) {
 			mouseClearButtonEdges();
 			mouseUpdateCursor();
@@ -480,7 +507,7 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 			videoPresentFrame();
 			animFrameRecordVocCounter(4);
 		} else {
-			renderSetDirty();
+			renderRequestFullFrameInvalidation();
 		}
 
 		if (_engineVersion == 3)
@@ -491,10 +518,11 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 			lastKey = lptReadKeyOrNext();
 
 		_lastKey = lastKey;
-		if (lastKey == 0x0101)
+		if (lastKey == 0x0101) {
 			keepRunning = 0;
-		else if (mainLoopActor)
+		} else if (mainLoopActor) {
 			keepRunning = mainLoopActor->active;
+		}
 
 		processEvents();
 		if (shouldQuit())
@@ -516,13 +544,13 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 					_animShutdownBeforeSceneStart = false;
 
 				uint16 track = 1;
-				for (;;) {
+				while (true) {
 					_musicEventMask = (uint16)((int16)_musicEventMask >> 1);
 					if (!_musicEventMask)
 						break;
 
 					if (_musicEventMask & 1)
-						envConvToXms(&_sceneMemoryBlock[_sceneMidiInstanceOffset], track);
+						environmentPackToXms(&_sceneMemoryBlock[_sceneMidiInstanceOffset], track);
 
 					track++;
 				}
@@ -530,6 +558,7 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 		}
 
 		keyBitClear(0x42);
+
 		if (_pendingScene) {
 			bool animFrameReady = animFrameIsReady();
 			if (_engineVersion == 3 && _animShutdownBeforeSceneStart)
@@ -545,6 +574,7 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 				vocQueuePlayAll();
 
 			keyBitSet(0x42);
+
 			frame = actorGetFrame();
 			if (frame)
 				backgroundTransitionFrames(frame, _backgroundFrame);
@@ -563,7 +593,8 @@ void ComfyEngine::gameMainLoop(uint16 argument) {
 void ComfyEngine::midiTrackTickAndRemove() {
 	_midiTracks.baseTime++;
 	_midiInstanceTrackBase = _midiTracks.baseTime;
-	while (_midiTracks.nextIndex != 0x03E7 && _midiTracks.baseTime >= _midiTracks.nextTime) {
+
+	while (_midiTracks.nextIndex != 999 && _midiTracks.baseTime >= _midiTracks.nextTime) {
 		keyBitSet(_midiTracks.entries[_midiTracks.nextIndex].id);
 		_midiTracks.count--;
 		_midiTracks.entries[_midiTracks.nextIndex] = _midiTracks.entries[_midiTracks.count];
@@ -572,14 +603,14 @@ void ComfyEngine::midiTrackTickAndRemove() {
 }
 
 void ComfyEngine::sceneTickEvent() {
-	soundAdvanceTick();
 	if (_soundEventIndex == _soundEventMaximum)
 		return;
 
 	if (_engineVersion == 3) {
-		VocQueueEntry1999 &entry = _vocQueue1999[_soundEventIndex];
+		VocQueueEntryV3 &entry = _vocQueueV3[_soundEventIndex];
 		bool started = false;
 		uint16 currentSubIndex = _soundEventSubIndex;
+
 		if (entry.state == 0xFFFF && (entry.soundId != 0xFFFF || !animFrameIsReady())) {
 			entry.state = 0;
 			_soundEventSubIndex = 0xFFFF;
@@ -592,8 +623,7 @@ void ComfyEngine::sceneTickEvent() {
 			currentSubIndex = 0xFFFF;
 		}
 
-		if (!started && currentSubIndex != 0xFFFF &&
-				currentSubIndex != _soundEventPreviousSubIndex) {
+		if (!started && currentSubIndex != 0xFFFF && currentSubIndex != _soundEventPreviousSubIndex) {
 			if (!currentSubIndex) {
 				if (entry.argumentCount)
 					keyBitSet(entry.arguments[0]);
@@ -630,14 +660,17 @@ void ComfyEngine::sceneTickEvent() {
 
 	VocQueueEntry &entry = _vocQueue[_soundEventIndex % _vocQueueCapacity];
 	uint16 currentSubIndex = _soundEventSubIndex;
+
 	if (entry.state == 0xFFFF && (entry.soundId != 0xFFFF || !animFrameIsReady())) {
 		entry.state = 0;
 		_soundEventSubIndex = 0xFFFF;
 		soundPlayEntry(entry.soundId);
+
 		keyBitSet(1);
 		keyBitSet(4);
 		keyBitClear(2);
 		keyBitClear(3);
+
 		currentSubIndex = 0xFFFF;
 	} else if (currentSubIndex != 0xFFFF && currentSubIndex != _soundEventPreviousSubIndex) {
 		if (!currentSubIndex) {
@@ -707,28 +740,24 @@ void ComfyEngine::midiPollChannels(uint16 ticks) {
 bool ComfyEngine::vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc) {
 	uint16 next = (_soundEventMaximum + 1) % _vocQueueCapacity;
 	if (next == _soundEventIndex) {
-		debug(5, "COMFY VOC: queue full; rejected id=%u args=%u index=%u maximum=%u",
-			soundId, argumentCount, _soundEventIndex, _soundEventMaximum);
 		return false;
 	}
-
-	debug(5, "COMFY VOC: queue id=%u args=%u slot=%u next=%u version=%u",
-		soundId, argumentCount, _soundEventMaximum, next, _engineVersion);
-
 	if (_engineVersion == 3) {
-		VocQueueEntry1999 &entry = _vocQueue1999[_soundEventMaximum];
+		VocQueueEntryV3 &entry = _vocQueueV3[_soundEventMaximum];
 		entry.clearArgumentKeys = (argumentCount & 0x80) != 0;
 		argumentCount &= 0x3F;
 		entry.soundId = soundId;
-		entry.argumentCount = MIN<uint16>(argumentCount, COMFY_VOC_ARG_CAPACITY_1999);
+		entry.argumentCount = MIN<uint16>(argumentCount, COMFY_VOC_ARG_CAPACITY_V3);
 		entry.state = 0xFFFF;
-		for (uint i = 0; i < COMFY_VOC_ARG_CAPACITY_1999; i++)
+
+		for (uint i = 0; i < COMFY_VOC_ARG_CAPACITY_V3; i++)
 			entry.arguments[i] = 0;
 
 		for (uint i = 0; i < entry.argumentCount; i++)
 			entry.arguments[i] = scriptReadWord(pc + i * 2);
 
 		_soundEventMaximum = next;
+
 		keyBitSet(1);
 		keyBitSet(4);
 		keyBitClear(2);
@@ -740,15 +769,18 @@ bool ComfyEngine::vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc)
 	entry.soundId = soundId;
 	entry.argumentCount = MIN<uint16>(argumentCount, COMFY_VOC_ARG_CAPACITY);
 	entry.state = 0xFFFF;
+
 	memset(entry.arguments, 0, sizeof(entry.arguments));
 	for (uint i = 0; i < entry.argumentCount; i++)
 		entry.arguments[i] = scriptReadWord(pc + i * 2);
 
 	_soundEventMaximum = next;
+
 	keyBitSet(1);
 	keyBitSet(4);
 	keyBitClear(2);
 	keyBitClear(3);
+
 	return true;
 }
 
@@ -763,7 +795,8 @@ void ComfyEngine::vocQueuePlayAll() {
 	if (_engineVersion == 3) {
 		uint16 slot = _soundEventIndex;
 		while (slot != _soundEventMaximum) {
-			VocQueueEntry1999 &entry = _vocQueue1999[slot];
+			VocQueueEntryV3 &entry = _vocQueueV3[slot];
+
 			for (uint i = 0; i < entry.argumentCount; i++)
 				keyBitSet(entry.arguments[i]);
 
@@ -777,6 +810,7 @@ void ComfyEngine::vocQueuePlayAll() {
 		keyBitClear(4);
 		keyBitSet(3);
 		keyBitSet(2);
+
 		return;
 	}
 
@@ -790,6 +824,7 @@ void ComfyEngine::vocQueuePlayAll() {
 	}
 
 	_soundEventMaximum = _soundEventIndex;
+
 	keyBitClear(1);
 	keyBitClear(4);
 	keyBitSet(3);
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index ab7086446cb..b9e3e6683a2 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -59,7 +59,6 @@ class QueuingAudioStream;
 #define COMFY_PALETTE_BYTES 0x300
 #define COMFY_INPUT_QUEUE_CAPACITY 20
 #define COMFY_KEYBOARD_CONTACT_COUNT 24
-#define COMFY_ACTOR_SIZE_V1 0x54
 #define COMFY_ACTOR_COUNT 0x79
 #define COMFY_EXPR_STACK_CAPACITY 64
 #define COMFY_ACTOR_PC_TABLE_COUNT 200
@@ -71,6 +70,7 @@ class QueuingAudioStream;
 #define COMFY_SCENE_MIDI_VERSION_BYTES_CLASSIC 0x167
 #define COMFY_SCENE_VOC_STATE_BYTES_V3 0x24D
 #define COMFY_SCENE_STATE_BYTES_V3 0x17F
+#define COMFY_ACTOR_SIZE_V1 0x54
 #define COMFY_ACTOR_SIZE_V2 0x56
 #define COMFY_ACTOR_SIZE_V3 0x57
 #define COMFY_SCENE_ACTOR_PC_BYTES 0x320
@@ -83,7 +83,7 @@ class QueuingAudioStream;
 #define COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES 0x3E80
 #define COMFY_SOUND_PITCH_COUNT_LIMIT 0x13
 #define COMFY_FRAME_LOADER_DATA_BYTES 0x6000
-#define COMFY_VOC_ARG_CAPACITY_1999 12
+#define COMFY_VOC_ARG_CAPACITY_V3 12
 #define COMFY_MIDI_QUEUE_CAPACITY 32
 #define COMFY_MIDI_CHANNEL_COUNT 2
 #define COMFY_SCENE_MUSIC_CHANNEL_COUNT 6
@@ -250,20 +250,20 @@ private:
 		}
 	};
 
-	struct VocQueueEntry1999 {
+	struct VocQueueEntryV3 {
 		uint16 soundId;
 		uint16 argumentCount;
 		uint16 state;
-		uint16 arguments[COMFY_VOC_ARG_CAPACITY_1999];
+		uint16 arguments[COMFY_VOC_ARG_CAPACITY_V3];
 		bool clearArgumentKeys;
 
-		VocQueueEntry1999() {
+		VocQueueEntryV3() {
 			soundId = 0;
 			argumentCount = 0;
 			state = 0;
 			clearArgumentKeys = false;
 
-			for (uint i = 0; i < COMFY_VOC_ARG_CAPACITY_1999; i++)
+			for (uint i = 0; i < COMFY_VOC_ARG_CAPACITY_V3; i++)
 				arguments[i] = 0;
 		}
 	};
@@ -508,12 +508,14 @@ private:
 	const ComfyGameDescription *_game;
 	byte _engineVersion;
 	bool _isPanther = false;
+	bool _backgroundBufferEnabled = false;
 	uint16 _vocQueueCapacity = COMFY_VOC_QUEUE_CAPACITY;
 	Common::Path _gameDirectory;
 	Common::Path _introDirectory;
 	Common::Path _gameDataPath;
 	bool _hasDataPath = false;
 	Common::Path _languageDirectories[16];
+	Common::String _v3LanguageDataSubdirectory;
 	uint16 _language = 2;
 	bool _multiLanguage = true;
 	Common::RandomSource _randomSource;
@@ -551,6 +553,8 @@ private:
 	int16 _timer0 = 1;
 	int16 _timer1 = 1;
 	int16 _timer2 = 1;
+	uint64 _timerPitPhase = 0;
+	uint32 _timerLastMillis = 0;
 	uint32 _midiTimeCounter = 0;
 	uint32 _midiInstanceEventTime = 0;
 	int32 _midiEventBaseTime = 0;
@@ -610,7 +614,7 @@ private:
 	bool _sceneEntryListActive = false;
 	Common::Array<uint16> _stringTable;
 	Common::Array<uint16> _sceneHandles;
-	Common::Array<uint16> _midiHandles;
+	Common::Array<uint16> _scriptVariables;
 	Common::Array<Actor> _actors;
 	Common::Array<byte> _sceneMemoryBlock;
 	Common::Array<byte> _sceneRunBuffer;
@@ -691,7 +695,6 @@ private:
 	uint16 _musicEventMask = 0;
 	byte _musicEventFlag = 0;
 	bool _musicEnabled = false;
-	bool _usesWcomfy99ScriptOps = false;
 	bool _languageSessionRestartRequested = false;
 	int16 _mouseX = 0;
 	int16 _mouseY = 0;
@@ -705,35 +708,35 @@ private:
 	uint16 _mouseCursorSpriteId = 0;
 	uint16 _mouseFlags = 0;
 	bool _waveOutputActive = false;
-	byte _wcomfy99VocState0 = 0;
-	byte _wcomfy99VocState1 = 0;
-	byte _wcomfy99VocState2 = 0;
-	byte _wcomfy99VocState3 = 0;
-	byte _wcomfy99VocState6 = 0;
-	bool _wcomfy99HostMediaValueAvailable = false;
-	uint16 _wcomfy99HostMediaValue = 0;
-	uint16 _wcomfy99HostMediaProgress = 0;
-	uint16 _wcomfy99Sensitivity = 0;
-	bool _wcomfy99RecordHostEnabled = false;
-	uint16 _wcomfy99SubsystemWord = 0;
-	uint16 _wcomfy99MixedHostFirstWord = 0;
-	uint16 _wcomfy99MixedHostSecondWord = 0;
-	uint16 _wcomfy99MixedHostThirdWord = 0;
-	uint16 _wcomfy99MixedHostFourthWord = 0;
-	uint16 _wcomfy99HostWordA = 0;
-	uint16 _wcomfy99HostWordB = 0;
-	uint16 _wcomfy99WaveVolumePercent = 0;
-	uint16 _wcomfy99WaveLeftPercent = 0;
-	uint16 _wcomfy99WaveRightPercent = 0;
-	uint16 _wcomfy99MixerVolumePercent = 0;
-	uint16 _wcomfy99MixerAltPercent = 0;
-	uint16 _wcomfy99RangeHostStart = 0;
-	uint16 _wcomfy99RangeHostEnd = 0;
-	uint16 _wcomfy99RangeHostCount = 0;
+	byte _v3SceneWaveBalancePercent = 0;
+	byte _v3SceneHostMediaModeEnabled = 0;
+	byte _v3SceneWaveLeftPercent = 0;
+	byte _v3SceneWaveRightPercent = 0;
+	byte _v3SceneMixerVolumePercent = 0;
+	bool _v3HostMediaValueAvailable = false;
+	uint16 _v3HostMediaValue = 0;
+	uint16 _v3HostMediaProgress = 0;
+	uint16 _v3Sensitivity = 0;
+	bool _v3ConfigCommandPending = false;
+	byte _v3ConfigCommandSubop = 0;
+	uint16 _v3ConfigCommandValue = 0;
+	Common::String _v3ConfigCommandText;
+	bool _v3HostMediaRecording = false;
+	uint16 _v3HostMediaRecordingArg0 = 0;
+	uint16 _v3HostMediaRecordingArg1 = 0;
+	uint16 _v3HostMediaRecordingArg2 = 0;
+	uint16 _v3HostMediaRecordingArg3 = 0;
+	uint16 _v3AnimIndexOffset = 0;
+	uint16 _v3AnimActorSceneHandle = 0;
+	uint16 _v3WaveBalancePercent = 0;
+	uint16 _v3WaveLeftPercent = 0;
+	uint16 _v3WaveRightPercent = 0;
+	uint16 _v3MixerVolumePercent = 0;
+	uint16 _v3MixerAltPercent = 0;
 	bool _actorDestroyedCurrent = false;
 	uint16 _lastKey = 0xFFFF;
 	VocQueueEntry _vocQueue[COMFY_VOC_QUEUE_CAPACITY];
-	VocQueueEntry1999 _vocQueue1999[COMFY_VOC_QUEUE_CAPACITY];
+	VocQueueEntryV3 _vocQueueV3[COMFY_VOC_QUEUE_CAPACITY];
 	uint16 _soundEventIndex = 0;
 	uint16 _soundEventMaximum = 0;
 	uint16 _soundEventSubIndex = 0xFFFF;
@@ -827,19 +830,21 @@ private:
 	void gameConfigInit();
 	void findLanguageDirectories();
 	bool iniReadGameConfig();
-	bool iniGetGameDataPath(uint16 sceneId);
-	void iniWriteLanguage(uint16 language);
+	bool iniSelectGameDataPath(uint16 sceneId);
+	void iniWriteLanguageSelection(uint16 language);
+	uint16 languageSetDataSubdirectory(Common::String text);
+	void configRunPendingCommand();
 	Common::Path getLanguageDirectory(uint16 language);
 	void pathSetGameDataDir(const Common::Path &path);
 	Common::Path pathBuild(const Common::Path &filename, bool useGamePath);
 	Common::SeekableReadStream *pathFOpen(const Common::Path &filename, bool useGamePath);
 	void videoInit();
 	void videoShutdown(byte restorePalette);
-	void videoSetResolution();
-	void videoFindBestMode(ComfyRect record);
+	void renderAddFullFrameDirtyRect();
+	void renderAddDirtyRect(ComfyRect record);
 	void renderAddDirtyRectMerged(ComfyRect record);
 	void videoPresentFrame();
-	void renderSetDirty();
+	void renderRequestFullFrameInvalidation();
 	void renderFlushDirty();
 	void renderInvalidateFullFrame();
 	void framebufCopyAll(byte *destination, byte *source);
@@ -858,11 +863,11 @@ private:
 	void paletteConvertRgbToLogical(byte *source, byte *destination);
 	void paletteRealize(byte *rawPalette);
 	uint16 midiTick();
-	void midiHandleAddTo(uint16 handleIndex, int16 delta);
-	void midiHandleCopy(uint16 destination, uint16 source);
-	void midiHandleSet(uint16 handleIndex, uint16 value);
-	uint16 midiGetHandle(uint16 handleIndex);
-	uint16 midiGetVersion();
+	void scriptVariableAddTo(uint16 variableIndex, int16 delta);
+	void scriptVariableCopy(uint16 destination, uint16 source);
+	void scriptVariableSet(uint16 variableIndex, uint16 value);
+	uint16 scriptVariableGet(uint16 variableIndex);
+	uint16 midiGetInstanceStateSize();
 	void midiSetTimeScale(int16 delta);
 	int16 midiGetCounterAdjustment();
 	bool midiPlyrStart();
@@ -900,17 +905,16 @@ private:
 	uint32 memGetFreeKBThunk();
 	uint32 memGetXmsLimit();
 	uint32 memGetXmsLimitFar();
-	int32 xmsCopyToConv(XmsMove &move);
 	int32 xmsTransfer(XmsMove &move);
 	void xmsReset();
 	ObjFileCacheRow *tileListEvictTail(ObjFile *objectFile);
 	ObjFileCacheRow *tileListAlloc(ObjFile *objectFile);
-	void tileListRemove(ObjFile *objectFile, uint16 index);
-	uint16 tileListRemoveRange(ObjFile *objectFile, uint16 first, uint16 last);
+	void tileListTouch(ObjFile *objectFile, uint16 index);
+	uint16 tileListTouchRange(ObjFile *objectFile, uint16 first, uint16 last);
 	void tileUploadToXms(ObjFile *objectFile, const byte *source, uint16 size, uint32 destinationOffset);
 	void tileCopyXmsPair(ObjFile *objectFile, byte *destination, uint32 sourceOffset, uint32 size);
 	uint16 tileDrawStrip(ObjFile *objectFile, byte *destination, uint16 cacheRow, uint16 sourceColumn, uint32 width);
-	void tileLoadAndDraw(ObjFile *objectFile, const byte *source, uint16 tileId);
+	void tileLoadAndCache(ObjFile *objectFile, const byte *source, uint16 tileId);
 	void frameLoaderLoadTileCore(ObjFile *objectFile, const byte *source, uint16 tileId);
 	void frameLoaderLoadTile(ObjFile *objectFile, uint16 tileId);
 	byte *frameLoaderReadFrameData(uint32 sourceOffset, uint32 byteCount, ObjFile *objectFile);
@@ -919,8 +923,8 @@ private:
 	byte *objFileReadTiledCore(uint32 sourceOffset, uint32 byteCount, ObjFile *objectFile);
 	void objFileReadField(byte *destination, uint32 sourceOffset, uint32 byteCount, ObjFile *objectFile);
 	byte *objFileReadTiled(uint32 sourceOffset, uint32 byteCount, ObjFile *objectFile);
-	ObjFile *objFileLoadSoundData(const Common::Path &path, uint16 blockSize, uint32 maximumBytes);
-	void soundBufFree(ObjFile *&objectFile);
+	ObjFile *objFileOpen(const Common::Path &path, uint16 blockSize, uint32 maximumBytes);
+	void objFileClose(ObjFile *&objectFile);
 	uint32 assetsAlignEven32(uint32 value);
 	void stringTableSetCount(uint16 count);
 	uint16 stringTableGetSize();
@@ -929,14 +933,14 @@ private:
 	bool assetsLoad(uint32 budget, byte *scenePtr);
 	void assetsUnload(byte freeAudio);
 	bool sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount,
-		uint16 handleCount, uint32 &numSprites);
+		uint16 scriptVariableCount, uint32 &numSprites);
 	bool sceneFrameInitTables(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount,
-		uint16 handleCount, uint32 &numSprites);
+		uint16 scriptVariableCount, uint32 &numSprites);
 	void midiShutdown();
-	void midiFileGetTileParams(uint16 *entryCount, uint16 *entrySize);
+	void midiFileGetEntryTableParams(uint16 *entryCount, uint16 *entrySize);
 	void midiFileReadEntries(byte *destination);
-	byte *soundReadTiledData();
-	void soundGetTileParams(uint16 *entryCount, uint16 *entrySize);
+	byte *soundReadHeaderTable();
+	void soundGetHeaderTableParams(uint16 *entryCount, uint16 *entrySize);
 	bool soundOpenVocFile();
 	void spriteCache(int16 spriteId);
 	SpriteResource *spriteLookup(uint16 spriteId, int16 x, int16 y);
@@ -961,10 +965,10 @@ private:
 	void sceneBlockUnpackRuntimeState();
 	uint16 sceneGetHandle(uint16 sceneIndex);
 	uint16 sceneGetActiveCount();
-	bool envXmsToConv(byte *destination, uint16 index);
-	void envConvToXms(byte *source, uint16 index);
-	void sceneGoto(uint16 count);
-	void sceneStop();
+	bool environmentUnpackFromXms(byte *destination, uint16 index);
+	void environmentPackToXms(byte *source, uint16 index);
+	void sceneEntryInit(uint16 count);
+	void sceneEntryStop();
 	bool sceneEntryLoad(uint16 descriptor, uint16 index);
 	byte scriptReadByte(uint32 pc);
 	uint16 scriptReadWord(uint32 pc);
@@ -1000,6 +1004,7 @@ private:
 	void actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool visible);
 	bool actorDrawLegacyInternal(uint16 actorIndex, int16 x, int16 y);
 	void actorDrawList(uint16 actorIndex, int16 x, int16 y, bool visible);
+	bool actorTestMouseHit(Actor &actor, bool useBlitHit);
 	void renderQueueDrawCommand(int16 x, int16 y, uint32 selector, byte mode, uint16 actorIndex);
 	void renderFlushDrawCommands();
 	void renderFlushCachedDirtyRects();
@@ -1063,18 +1068,18 @@ private:
 	void midiRemoveTrack(uint16 id);
 	void midiAddTrackEntry(uint16 channel, uint16 songId, uint16 completionKey, byte loadFlag,
 		uint16 frameCount, uint16 *frames);
-	void midiClearChannel(uint16 channel);
+	void midiClearLoadedSong(uint16 channel);
 	void midiFireClearMarker(uint16 channel, int16 marker);
 	void midiPollSceneEntries();
 	void midiResumeAll();
-	void midiStopChannel(uint16 channel);
-	void midiStopAll();
+	void midiStartChannel(uint16 channel);
+	void midiRestartChannels();
 	void midiStopSong(uint16 channel);
 	void midiPlaySongAtFrame(uint16 channel, uint16 frame);
 	void sceneEntrySetVolume(uint16 channel, uint16 volume);
 	void midiFinishChannel(uint16 channel);
 	void midiStopAndFireKeys(uint16 channel);
-	void midiStopAndRemove(uint16 channel);
+	void midiStopAndAdvanceChannel(uint16 channel);
 	void midiSetChannelParam(uint16 channel, byte parameter, uint16 value, uint16 ticks);
 	int16 midiApproachTarget(int16 current, int16 target, int16 &ticksLeft, int16 ticks);
 	void musicSetEnabled(byte value);
@@ -1083,16 +1088,16 @@ private:
 	bool vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc);
 	void vocQueuePlayAll();
 	bool vocQueueIsIdle();
-	void wcomfy99SetWaveBalancePercent(uint16 value);
-	void wcomfy99SetWaveLeftPercent(uint16 value);
-	void wcomfy99SetWaveRightPercent(uint16 value);
-	void wcomfy99SetMixerVolumePercent(uint16 value);
-	void wcomfy99SetHostMediaRangePercent(uint16 value);
-	void wcomfy99SetHostMediaMode(byte mode);
-	void wcomfy99RestoreHostStateAfterSceneStart();
+	void setWaveBalancePercent(uint16 value);
+	void setWaveLeftPercent(uint16 value);
+	void setWaveRightPercent(uint16 value);
+	void setMixerVolumePercent(uint16 value);
+	void setMediaRangePercent(uint16 value);
+	void setMediaMode(byte mode);
+	void restoreWaveStateAfterSceneStart();
 	bool soundInit();
 	void soundShutdown();
-	void soundHdrReadFromXms(byte *destination, uint16 index, uint16 size);
+	void soundHeaderReadFromXms(byte *destination, uint16 index, uint16 size);
 	void soundUpdateVocTiming();
 	void soundServiceWaveBuffers();
 	bool soundLoadEntry(uint16 index);
diff --git a/engines/comfy/debug.cpp b/engines/comfy/debug.cpp
index b80232633c1..a98a52bd5bc 100644
--- a/engines/comfy/debug.cpp
+++ b/engines/comfy/debug.cpp
@@ -360,7 +360,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 			ImGui::SameLine(520.0F);
 			if (ImGui::Checkbox("Visible", &visibleActor)) {
 				actor.visible = visibleActor ? 1 : 0;
-				renderSetDirty();
+				renderRequestFullFrameInvalidation();
 			}
 			ImGui::SameLine();
 			if (ImGui::Checkbox("Active", &activeActor))
@@ -453,7 +453,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 			ImGui::PushID((int)i * 2);
 			if (ImGui::Checkbox("", &visibleActor)) {
 				actor.visible = visibleActor ? 1 : 0;
-				renderSetDirty();
+				renderRequestFullFrameInvalidation();
 			}
 			ImGui::PopID();
 			ImGui::TableSetColumnIndex(8);
diff --git a/engines/comfy/expr.cpp b/engines/comfy/expr.cpp
index d8950a88b56..515b1be9fd8 100644
--- a/engines/comfy/expr.cpp
+++ b/engines/comfy/expr.cpp
@@ -102,15 +102,15 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 			else if (opcode == 0x18)
 				value = _mouseY;
 			else if (opcode == 0x19)
-				value = _wcomfy99VocState0;
+				value = _v3SceneWaveBalancePercent;
 			else if (opcode == 0x1A)
-				value = _wcomfy99HostMediaValueAvailable ? _wcomfy99HostMediaValue : 0;
+				value = _v3HostMediaValueAvailable ? _v3HostMediaValue : 0;
 			else if (opcode == 0x1B)
 				pushValue = false;
 			else if (opcode == 0x1C)
-				value = _wcomfy99VocState2;
+				value = _v3SceneWaveLeftPercent;
 			else if (opcode == 0x1D)
-				value = _wcomfy99VocState3;
+				value = _v3SceneWaveRightPercent;
 			else if (opcode == 0x1E) {
 				if (_exprStackTop) {
 					uint16 dimension = _exprStack[_exprStackTop - 1];
@@ -124,9 +124,9 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 
 				pushValue = false;
 			} else if (opcode == 0x1F || opcode == 0x20) {
-				value = _wcomfy99HostMediaProgress;
+				value = _v3HostMediaProgress;
 			} else if (opcode == 0x21) {
-				value = _wcomfy99VocState6;
+				value = _v3SceneMixerVolumePercent;
 			}
 
 			if (pushValue && _exprStackTop < COMFY_EXPR_STACK_CAPACITY)
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index 1c3983a81fc..89f42777275 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -176,12 +176,12 @@ bool ComfyEngine::iniReadGameConfig() {
 		_inputDeviceMode = 0;
 
 	_inputDevicePreference = _inputDeviceMode;
-	_wcomfy99Sensitivity = ConfMan.hasKey("SENSITIVITY") ? ConfMan.getInt("SENSITIVITY") : 0;
+	_v3Sensitivity = ConfMan.hasKey("SENSITIVITY") ? ConfMan.getInt("SENSITIVITY") : 0;
 
 	return !_gameDirectory.empty();
 }
 
-bool ComfyEngine::iniGetGameDataPath(uint16 sceneId) {
+bool ComfyEngine::iniSelectGameDataPath(uint16 sceneId) {
 	if (sceneId == 0) {
 		if (_introDirectory.empty())
 			return false;
@@ -190,7 +190,7 @@ bool ComfyEngine::iniGetGameDataPath(uint16 sceneId) {
 		return true;
 	}
 
-	if (sceneId == 0x63) {
+	if (sceneId == 99) {
 		pathSetGameDataDir(_gameDirectory.join("SETLANG"));
 		return true;
 	}
@@ -199,16 +199,59 @@ bool ComfyEngine::iniGetGameDataPath(uint16 sceneId) {
 	if (languageDirectory.empty())
 		return false;
 
-	pathSetGameDataDir(_gameDirectory.join(languageDirectory));
+	Common::Path gameDataPath = _gameDirectory.join(languageDirectory);
+	if (_engineVersion == 3 && !_v3LanguageDataSubdirectory.empty() && _v3LanguageDataSubdirectory != ".")
+		gameDataPath = gameDataPath.join(Common::Path(_v3LanguageDataSubdirectory, '/'));
+
+	pathSetGameDataDir(gameDataPath);
 	return true;
 }
 
-void ComfyEngine::iniWriteLanguage(uint16 language) {
+void ComfyEngine::iniWriteLanguageSelection(uint16 language) {
 	_language = language;
 	ConfMan.setInt("comfy_language", language);
 	ConfMan.flushToDisk();
 }
 
+uint16 ComfyEngine::languageSetDataSubdirectory(Common::String text) {
+	uint start = 0;
+	uint end = text.size();
+	while (start < end && Common::isSpace((byte)text[start]))
+		start++;
+
+	while (end > start && Common::isSpace((byte)text[end - 1]))
+		end--;
+
+	_v3LanguageDataSubdirectory = text.substr(start, end - start);
+	_languageSessionRestartRequested = true;
+	if (_v3LanguageDataSubdirectory.empty())
+		return 0x20;
+
+	byte character = _v3LanguageDataSubdirectory.lastChar();
+	if (character == ' ')
+		return 0x81;
+
+	if (Common::isSpace(character))
+		return 0x21;
+
+	if (Common::isDigit(character))
+		return 0x12;
+
+	if (Common::isUpper(character))
+		return character <= 'F' ? 0x14 : 0x04;
+
+	if (Common::isLower(character))
+		return character <= 'f' ? 0x18 : 0x08;
+
+	if (character < 0x20 || character == 0x7F)
+		return 0x20;
+
+	if (character < 0x80)
+		return 0x40;
+
+	return 0;
+}
+
 Common::Path ComfyEngine::getLanguageDirectory(uint16 language) {
 	if (language >= ARRAYSIZE(_languageDirectories))
 		return Common::Path();
@@ -257,7 +300,7 @@ uint32 ComfyEngine::assetsAlignEven32(uint32 value) {
 	return value + (value & 1);
 }
 
-void ComfyEngine::midiFileGetTileParams(uint16 *entryCount, uint16 *entrySize) {
+void ComfyEngine::midiFileGetEntryTableParams(uint16 *entryCount, uint16 *entrySize) {
 	if (entryCount)
 		*entryCount = _midiEntryCount;
 
@@ -273,11 +316,11 @@ void ComfyEngine::midiFileReadEntries(byte *destination) {
 	_midiFileStream->read(destination, size);
 }
 
-byte *ComfyEngine::soundReadTiledData() {
+byte *ComfyEngine::soundReadHeaderTable() {
 	return _vocFile ? objFileReadTiled(4, (uint32)_soundEntryCount * 8, _vocFile) : nullptr;
 }
 
-void ComfyEngine::soundGetTileParams(uint16 *entryCount, uint16 *entrySize) {
+void ComfyEngine::soundGetHeaderTableParams(uint16 *entryCount, uint16 *entrySize) {
 	if (entryCount)
 		*entryCount = _soundEntryCount;
 
@@ -315,19 +358,21 @@ void ComfyEngine::selPoolFree() {
 }
 
 bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount,
-		uint16 handleCount, uint32 &numSprites) {
-	return sceneFrameInitTables(sceneCount, actorCount, keyBitCount, handleCount, numSprites);
+		uint16 scriptVariableCount, uint32 &numSprites) {
+	return sceneFrameInitTables(sceneCount, actorCount, keyBitCount, scriptVariableCount, numSprites);
 }
 
 bool ComfyEngine::sceneFrameInitTables(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount,
-		uint16 handleCount, uint32 &numSprites) {
+		uint16 scriptVariableCount, uint32 &numSprites) {
+
 	_stringTable.resize(_stringCount);
 	memset(&_stringTable[0], 0, _stringTable.size() * sizeof(uint16));
 	_sceneHandles.resize(sceneCount + 1);
 	memset(&_sceneHandles[0], 0, _sceneHandles.size() * sizeof(uint16));
-	_midiHandles.resize(handleCount + 1);
-	memset(&_midiHandles[0], 0, _midiHandles.size() * sizeof(uint16));
+	_scriptVariables.resize(scriptVariableCount + 1);
+	memset(&_scriptVariables[0], 0, _scriptVariables.size() * sizeof(uint16));
 	_actors.resize(actorCount + 1);
+
 	for (uint i = 0; i < _actors.size(); i++)
 		_actors[i] = Actor();
 
@@ -335,11 +380,11 @@ bool ComfyEngine::sceneFrameInitTables(uint16 sceneCount, uint16 actorCount, uin
 		return false;
 
 	memset(_actorPcTable, 0, sizeof(_actorPcTable));
-	for (uint i = 0; i < 0xC7 && i < ARRAYSIZE(_actorPcTable); i++)
+	for (uint i = 0; i < 199 && i < ARRAYSIZE(_actorPcTable); i++)
 		_actorPcTable[i] = (uint32)(i + 1) << 24;
 
-	if (0xC7 < ARRAYSIZE(_actorPcTable))
-		_actorPcTable[0xC7] = 0;
+	if (ARRAYSIZE(_actorPcTable) > 199)
+		_actorPcTable[199] = 0;
 
 	uint32 stringBytes = stringTableGetSize();
 	uint32 handleBytes = _sceneHandles.size() * sizeof(uint16);
@@ -365,34 +410,38 @@ bool ComfyEngine::sceneFrameInitTables(uint16 sceneCount, uint16 actorCount, uin
 		_sceneStringTableOffset = _sceneActorPcOffset + COMFY_SCENE_ACTOR_PC_BYTES;
 	} else {
 		_sceneEntryListOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES;
-		_sceneActorPcOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES + midiGetVersion();
+		_sceneActorPcOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES + midiGetInstanceStateSize();
 		_sceneStringTableOffset = _sceneActorPcOffset + COMFY_SCENE_ACTOR_PC_BYTES;
 	}
 
 	_sceneHandlesOffset = _sceneStringTableOffset + stringBytes;
 	_sceneActorsOffset = _sceneHandlesOffset + handleBytes;
 	_sceneKeyBitsOffset = _sceneActorsOffset + actorBytes;
-	if (_engineVersion == 3)
+
+	if (_engineVersion == 3) {
 		_sceneAnimStateOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES + COMFY_SCENE_VOC_STATE_BYTES_V3;
-	else if (!_isPanther)
+	} else if (!_isPanther) {
 		_sceneAnimStateOffset = _sceneKeyBitsOffset + keyBytes;
+	}
+
 	uint32 sceneBytes = assetsAlignEven32(_sceneKeyBitsOffset + keyBytes);
 	_sceneMemoryBlock.resize(sceneBytes);
 	memset(&_sceneMemoryBlock[0], 0, sceneBytes);
 	numSprites = sceneBytes;
 	_numSprites = numSprites;
 	_envNumSprites = numSprites;
-	_activeSceneCount = handleCount;
+	_activeSceneCount = scriptVariableCount;
 
-	if (_isPanther || _engineVersion == 3)
+	if (_isPanther || _engineVersion == 3) {
 		midiInitInstanceAt();
-	else
+	} else {
 		midiInitInstance();
+	}
 
-	if (_isPanther || _engineVersion == 3) {
-		if (!soundInit())
-			return false;
+	if (!soundInit())
+		return false;
 
+	if (_isPanther || _engineVersion == 3) {
 		if (_usesAnimFile && !animFileOpen())
 			return false;
 	}
@@ -408,6 +457,7 @@ bool ComfyEngine::sceneFrameInitTables(uint16 sceneCount, uint16 actorCount, uin
 	_actors[_actors.size() - 1].nextLink = 0;
 	_actors[_actors.size() - 1].sceneHandle = 0;
 	actorSetFrame(0);
+
 	return true;
 }
 
@@ -418,8 +468,11 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	if (!memCompactAndCheck(0x200000))
 		return false;
 
+	spriteInvalidateHostCache(_frameSpriteResource);
+	_frameSpriteResource.id = 0;
+
 	uint32 comfyCacheBytes = _engineVersion == 3 ? 0x32000 : 0xA000;
-	_comfyObjFile = objFileLoadSoundData(Common::Path("COMFY.OBJ"), 0x0800, comfyCacheBytes);
+	_comfyObjFile = objFileOpen(Common::Path("COMFY.OBJ"), 0x0800, comfyCacheBytes);
 	if (!_comfyObjFile)
 		return false;
 
@@ -434,31 +487,30 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	_picDataSize = READ_LE_UINT32(value);
 	objFileReadField(value, 0x12, 2, _comfyObjFile);
 	_resourceHandleCount = READ_LE_UINT16(value);
+
 	_usesAnimFile = (_resourceHandleCount & 0x8000) != 0;
 	_resourceHandleCount &= 0x7FFF;
 	_comfyObjOpen = true;
 	_numFrames = (uint16)(_picDataSize / COMFY_TILE_SIZE + (_picDataSize % COMFY_TILE_SIZE ? 2 : 1));
+
 	if (_engineVersion == 3) {
 		uint16 preloadCount = MIN<uint16>(_numFrames, 0x64);
 		for (uint16 i = 0; i < preloadCount; i++)
 			objFileReadTiled((uint32)i << 11, 8, _comfyObjFile);
 	}
 
-	_picFile = objFileLoadSoundData(Common::Path("PICFILE.DAT"), 0x0800, 0x5000);
+	_picFile = objFileOpen(Common::Path("PICFILE.DAT"), 0x0800, 0x5000);
 	if (!_picFile)
 		return false;
 
 	byte objectCount[2];
 	objFileReadField(objectCount, 0, sizeof(objectCount), _picFile);
 	_numObjects = READ_LE_UINT16(objectCount);
-	soundBufFree(_picFile);
-
-	if (!_isPanther && _engineVersion != 3 && !soundInit())
-		return false;
+	objFileClose(_picFile);
 
 	_picFileMapped = true;
 	uint32 numSprites = 0;
-	if (!sceneLoadAndInit(_sceneCount, 0x78, _keyBitCount, _resourceHandleCount, numSprites))
+	if (!sceneLoadAndInit(_sceneCount, 120, _keyBitCount, _resourceHandleCount, numSprites))
 		return false;
 
 	_soundLoaded = true;
@@ -475,11 +527,11 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 
 	uint16 midiEntryCount = 0;
 	uint16 midiEntrySize = 0;
-	midiFileGetTileParams(&midiEntryCount, &midiEntrySize);
+	midiFileGetEntryTableParams(&midiEntryCount, &midiEntrySize);
 	uint32 midiHeaderBytes = assetsAlignEven32((uint32)midiEntryCount * midiEntrySize);
 	uint16 soundEntryCount = 0;
 	uint16 soundEntrySize = 0;
-	soundGetTileParams(&soundEntryCount, &soundEntrySize);
+	soundGetHeaderTableParams(&soundEntryCount, &soundEntrySize);
 	uint32 soundHeaderBytes = assetsAlignEven32((uint32)soundEntryCount * soundEntrySize);
 	uint32 objectTableBytes = assetsAlignEven32((uint32)_numObjects * 0x11);
 	uint32 headerTotalBytes = midiHeaderBytes + soundHeaderBytes + objectTableBytes;
@@ -494,6 +546,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 
 	_spriteHeaders.resize(_numObjects);
 	_spriteResources.resize(_numObjects);
+
 	for (uint i = 0; i < _numObjects; i++) {
 		_spriteHeaders[i] = SpriteObjectHeader();
 		_spriteResources[i].header = SpriteObjectHeader();
@@ -504,6 +557,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 
 	_objectCacheEntries.resize(_numObjects);
 	_frameCacheEntries.resize(_numFrames + 1);
+
 	if (!_objectCacheEntries.empty())
 		memset(&_objectCacheEntries[0], 0xFF, _objectCacheEntries.size() * sizeof(SpriteCacheEntry));
 
@@ -515,8 +569,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	for (uint i = 0; i < _spriteResources.size(); i++)
 		spriteInvalidateHostCache(_spriteResources[i]);
 
-	// Panther hardcodes the original background-buffer flag to one; WCOMFY v3 hardcodes it to zero.
-	if (_isPanther) {
+	if (_backgroundBufferEnabled) {
 		_backgroundFramebuf.resize(framebufferBytes());
 		memset(&_backgroundFramebuf[0], 0, _backgroundFramebuf.size());
 		_backgroundFrame = 0;
@@ -543,17 +596,17 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 		WRITE_LE_UINT16(&_scenePoolData[0], 0x8000);
 
 	uint32 freeKB = memGetFreeKBThunk();
-	if (!_isPanther && _engineVersion != 3 && freeKB < 0x12C)
-		freeKB = memGetFreeKBThunk() * 0x5A / 0x64;
+	if (!_isPanther && _engineVersion != 3 && freeKB < 300)
+		freeKB = memGetFreeKBThunk() * 90 / 100;
 
-	if (freeKB <= 0x12C)
+	if (freeKB <= 300)
 		return false;
 
 	uint32 picCacheBytes = freeKB << 10;
 	if (_isPanther || _engineVersion == 3)
 		picCacheBytes = (freeKB - 1) << 10;
 
-	_picFile = objFileLoadSoundData(Common::Path("PICFILE.DAT"), 0x8000, picCacheBytes);
+	_picFile = objFileOpen(Common::Path("PICFILE.DAT"), 0x8000, picCacheBytes);
 	if (!_picFile)
 		return false;
 
@@ -563,6 +616,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	uint32 remaining = objectTableBytes;
 	_headerXmsObjectTableBase = xmsOffset;
 	_headerXmsObjectTableBytes = objectTableBytes;
+
 	while (remaining) {
 		uint32 chunk = MIN<uint32>(remaining, 0x8000);
 		byte *source = objFileReadTiled(fileOffset, chunk, _picFile);
@@ -605,15 +659,15 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	_headerXmsSoundHeadersBase = xmsOffset;
 	_headerXmsSoundHeadersBytes = soundHeaderBytes;
 	if (soundHeaderBytes) {
-		byte *soundTiledData = soundReadTiledData();
-		if (!soundTiledData)
+		byte *soundHeaderTable = soundReadHeaderTable();
+		if (!soundHeaderTable)
 			return false;
 
 		XmsMove move;
 		move.length = soundHeaderBytes;
 		move.destinationHandle = _xmsHeaderHandle;
 		move.destinationOffset = xmsOffset;
-		move.sourceMemory = soundTiledData;
+		move.sourceMemory = soundHeaderTable;
 		if (xmsTransfer(move) < 0)
 			return false;
 
@@ -623,7 +677,6 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	_activeSceneCount = _resourceHandleCount;
 	_sceneEntryCount = 0;
 	_sceneEntryFrameSize = 0;
-	_usesWcomfy99ScriptOps = _engineVersion == 3;
 	_scriptFault = false;
 
 	return true;
@@ -650,10 +703,10 @@ void ComfyEngine::assetsUnload(byte freeAudio) {
 		soundShutdown();
 
 	if (_picFileDatOpen)
-		soundBufFree(_picFile);
+		objFileClose(_picFile);
 
 	if (_comfyObjOpen)
-		soundBufFree(_comfyObjFile);
+		objFileClose(_comfyObjFile);
 
 	if (_soundLoaded)
 		sceneShutdown();
@@ -666,20 +719,19 @@ void ComfyEngine::assetsUnload(byte freeAudio) {
 	_spriteResources.clear();
 	_stringTable.clear();
 	_sceneHandles.clear();
-	_midiHandles.clear();
+	_scriptVariables.clear();
 	_actors.clear();
 	_sceneMemoryBlock.clear();
 	keyBitFree();
-	soundBufFree(_vocFile);
-	soundBufFree(_picFile);
-	soundBufFree(_comfyObjFile);
+	objFileClose(_vocFile);
+	objFileClose(_picFile);
+	objFileClose(_comfyObjFile);
 	delete _midiFileStream;
 	_midiFileStream = nullptr;
 	xmsReset();
 	_spriteConversionLoads = ResourceLoadList();
 	memset(_sceneEntryOffsets, 0, sizeof(_sceneEntryOffsets));
 	memset(_actorPcTable, 0, sizeof(_actorPcTable));
-	_usesWcomfy99ScriptOps = false;
 	_currentActor = 0;
 	_scriptFault = false;
 	_stringCount = 0;
@@ -723,8 +775,6 @@ void ComfyEngine::assetsUnload(byte freeAudio) {
 	_headerXmsObjectTableBytes = 0;
 	_headerXmsMidiEntriesBytes = 0;
 	_headerXmsSoundHeadersBytes = 0;
-	// The original consumes one UI character here; ScummVM has no teardown prompt to acknowledge.
-	(void)freeAudio;
 }
 
 } // End of namespace Comfy
diff --git a/engines/comfy/memory.cpp b/engines/comfy/memory.cpp
index b15d768c804..26e8856cee0 100644
--- a/engines/comfy/memory.cpp
+++ b/engines/comfy/memory.cpp
@@ -125,7 +125,7 @@ int32 ComfyEngine::memFreeTrackFar(uint16 handle) {
 	return memFreeTrack(handle);
 }
 
-int32 ComfyEngine::xmsCopyToConv(XmsMove &move) {
+int32 ComfyEngine::xmsTransfer(XmsMove &move) {
 	byte *source = (byte *)move.sourceMemory;
 	byte *destination = move.destinationMemory;
 	uint32 sourceSize = UINT32_MAX;
@@ -155,10 +155,6 @@ int32 ComfyEngine::xmsCopyToConv(XmsMove &move) {
 	return 0;
 }
 
-int32 ComfyEngine::xmsTransfer(XmsMove &move) {
-	return xmsCopyToConv(move);
-}
-
 void ComfyEngine::xmsReset() {
 	for (uint16 handle = 1; handle < COMFY_XMS_HANDLE_CAPACITY; handle++) {
 		if (_xmsBlocks[handle].data)
diff --git a/engines/comfy/midi.cpp b/engines/comfy/midi.cpp
index 70238f48717..02ff0da33ef 100644
--- a/engines/comfy/midi.cpp
+++ b/engines/comfy/midi.cpp
@@ -27,26 +27,7 @@
 
 namespace Comfy {
 
-void ComfyEngine::midiHandleAddTo(uint16 handleIndex, int16 delta) {
-	if (handleIndex < _midiHandles.size())
-		_midiHandles[handleIndex] += delta;
-}
-
-void ComfyEngine::midiHandleCopy(uint16 destination, uint16 source) {
-	if (destination < _midiHandles.size() && source < _midiHandles.size())
-		_midiHandles[destination] = _midiHandles[source];
-}
-
-void ComfyEngine::midiHandleSet(uint16 handleIndex, uint16 value) {
-	if (handleIndex < _midiHandles.size())
-		_midiHandles[handleIndex] = value;
-}
-
-uint16 ComfyEngine::midiGetHandle(uint16 handleIndex) {
-	return handleIndex < _midiHandles.size() ? _midiHandles[handleIndex] : 0;
-}
-
-uint16 ComfyEngine::midiGetVersion() {
+uint16 ComfyEngine::midiGetInstanceStateSize() {
 	return COMFY_SCENE_MIDI_VERSION_BYTES_CLASSIC;
 }
 
@@ -303,7 +284,7 @@ void ComfyEngine::midiRemoveTrack(uint16 id) {
 	midiFindNext(_midiEvents);
 }
 
-void ComfyEngine::midiClearChannel(uint16 channel) {
+void ComfyEngine::midiClearLoadedSong(uint16 channel) {
 	if (channel >= COMFY_MIDI_CHANNEL_COUNT)
 		return;
 
@@ -341,14 +322,14 @@ void ComfyEngine::midiResumeAll() {
 	}
 }
 
-void ComfyEngine::midiStopChannel(uint16 channel) {
+void ComfyEngine::midiStartChannel(uint16 channel) {
 	if (!_midiPlyrDriver || channel >= COMFY_MIDI_CHANNEL_COUNT || !_midiChannels[channel].entryCount)
 		return;
 
 	MidiChannelState &state = _midiChannels[channel];
 	byte *song = spriteLoadFromFile(state.entries[0].songId, channel);
 	if (!song) {
-		midiClearChannel(channel);
+		midiClearLoadedSong(channel);
 		return;
 	}
 
@@ -358,9 +339,10 @@ void ComfyEngine::midiStopChannel(uint16 channel) {
 	_midiPlyrDriver->musicPlaySong(song, size, channel);
 }
 
-void ComfyEngine::midiStopAll() {
+
+void ComfyEngine::midiRestartChannels() {
 	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++)
-		midiClearChannel(channel);
+		midiClearLoadedSong(channel);
 
 	if (_midiPlyrDriver)
 		_midiPlyrDriver->musicStopAll(1);
@@ -376,7 +358,7 @@ void ComfyEngine::midiStopAll() {
 
 	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
 		if (_midiChannels[channel].entryCount)
-			midiStopChannel(channel);
+			midiStartChannel(channel);
 	}
 }
 
@@ -384,7 +366,7 @@ void ComfyEngine::midiShutdown() {
 	if (_usesAnimFile && _engineVersion == 2 && !_isPanther)
 		animFileShutdown();
 
-	_midiHandles.clear();
+	_scriptVariables.clear();
 	_sceneMemoryBlock.clear();
 	_sceneMidiInstanceOffset = 0;
 	_sceneEntryListOffset = 0;
@@ -406,7 +388,7 @@ void ComfyEngine::midiFinishChannel(uint16 channel) {
 	if (_midiPlyrDriver)
 		_midiPlyrDriver->musicStopSong(1, channel);
 
-	midiClearChannel(channel);
+	midiClearLoadedSong(channel);
 	if (state.entries[0].completionKey)
 		keyBitSet(state.entries[0].completionKey);
 
@@ -415,7 +397,7 @@ void ComfyEngine::midiFinishChannel(uint16 channel) {
 
 	state.entryCount--;
 	if (state.entryCount)
-		midiStopChannel(channel);
+		midiStartChannel(channel);
 }
 
 void ComfyEngine::midiStopAndFireKeys(uint16 channel) {
@@ -427,7 +409,7 @@ void ComfyEngine::midiStopAndFireKeys(uint16 channel) {
 	if (_midiPlyrDriver)
 		_midiPlyrDriver->musicStopSong(1, channel);
 
-	midiClearChannel(channel);
+	midiClearLoadedSong(channel);
 	for (uint i = 0; i < state.entryCount; i++) {
 		// The original tests every entry but always fires the first entry's key.
 		if (state.entries[i].completionKey)
@@ -437,14 +419,14 @@ void ComfyEngine::midiStopAndFireKeys(uint16 channel) {
 	state.entryCount = 0;
 }
 
-void ComfyEngine::midiStopAndRemove(uint16 channel) {
+void ComfyEngine::midiStopAndAdvanceChannel(uint16 channel) {
 	if (channel >= COMFY_MIDI_CHANNEL_COUNT)
 		return;
 
 	if (_midiPlyrDriver)
 		_midiPlyrDriver->musicStopSong(1, channel);
 
-	midiClearChannel(channel);
+	midiClearLoadedSong(channel);
 	midiFinishChannel(channel);
 }
 
@@ -467,7 +449,7 @@ void ComfyEngine::midiAddTrackEntry(uint16 channel, uint16 songId, uint16 comple
 
 	state.entryCount++;
 	if (state.entryCount == 1)
-		midiStopChannel(channel);
+		midiStartChannel(channel);
 }
 
 void ComfyEngine::midiSetChannelParam(uint16 channel, byte parameter, uint16 value, uint16 ticks) {
diff --git a/engines/comfy/object_file.cpp b/engines/comfy/object_file.cpp
index a9ed5d0314d..a0141cada3f 100644
--- a/engines/comfy/object_file.cpp
+++ b/engines/comfy/object_file.cpp
@@ -74,7 +74,7 @@ ComfyEngine::ObjFileCacheRow *ComfyEngine::tileListAlloc(ObjFile *objectFile) {
 	return row;
 }
 
-void ComfyEngine::tileListRemove(ObjFile *objectFile, uint16 index) {
+void ComfyEngine::tileListTouch(ObjFile *objectFile, uint16 index) {
 	if (!objectFile || !objectFile->cacheRows || index >= objectFile->cacheRowCount)
 		return;
 
@@ -111,7 +111,7 @@ void ComfyEngine::tileListRemove(ObjFile *objectFile, uint16 index) {
 	}
 }
 
-uint16 ComfyEngine::tileListRemoveRange(ObjFile *objectFile, uint16 first, uint16 last) {
+uint16 ComfyEngine::tileListTouchRange(ObjFile *objectFile, uint16 first, uint16 last) {
 	if (!objectFile || !objectFile->tileStatus)
 		return 0;
 
@@ -126,7 +126,7 @@ uint16 ComfyEngine::tileListRemoveRange(ObjFile *objectFile, uint16 first, uint1
 	while (row <= last && row < objectFile->tileStatusCount) {
 		uint16 tile = objectFile->tileStatus[row];
 		if (tile != 0xFFFF) {
-			tileListRemove(objectFile, tile);
+			tileListTouch(objectFile, tile);
 			removed++;
 		}
 
@@ -183,12 +183,12 @@ uint16 ComfyEngine::tileDrawStrip(ObjFile *objectFile, byte *destination, uint16
 
 	uint32 sourceOffset = (uint32)cacheRow * objectFile->blockSize + sourceColumn;
 	tileCopyXmsPair(objectFile, destination, sourceOffset, drawWidth);
-	tileListRemove(objectFile, cacheRow);
+	tileListTouch(objectFile, cacheRow);
 	_stripsDrawn++;
 	return drawWidth;
 }
 
-void ComfyEngine::tileLoadAndDraw(ObjFile *objectFile, const byte *source, uint16 tileId) {
+void ComfyEngine::tileLoadAndCache(ObjFile *objectFile, const byte *source, uint16 tileId) {
 	ObjFileCacheRow *row = tileListAlloc(objectFile);
 	if (!objectFile || !row)
 		return;
@@ -199,11 +199,11 @@ void ComfyEngine::tileLoadAndDraw(ObjFile *objectFile, const byte *source, uint1
 		objectFile->tileStatus[tileId] = frameIndex;
 
 	tileUploadToXms(objectFile, source, objectFile->blockSize, (uint32)frameIndex * objectFile->blockSize);
-	tileListRemove(objectFile, frameIndex);
+	tileListTouch(objectFile, frameIndex);
 }
 
 void ComfyEngine::frameLoaderLoadTileCore(ObjFile *objectFile, const byte *source, uint16 tileId) {
-	tileLoadAndDraw(objectFile, source, tileId);
+	tileLoadAndCache(objectFile, source, tileId);
 }
 
 void ComfyEngine::frameLoaderLoadTile(ObjFile *objectFile, uint16 tileId) {
@@ -243,7 +243,7 @@ void ComfyEngine::objFileReadFieldCore(byte *destination, uint32 sourceOffset, u
 	uint16 column = (uint16)(sourceOffset % objectFile->blockSize);
 	byte *output = destination;
 	uint32 remaining = byteCount;
-	tileListRemoveRange(objectFile, firstRow, lastRow);
+	tileListTouchRange(objectFile, firstRow, lastRow);
 
 	while (row <= lastRow && remaining) {
 		uint16 copied = 0;
@@ -286,7 +286,7 @@ void ComfyEngine::objFileReadFieldCore(byte *destination, uint32 sourceOffset, u
 						memcpy(output, tileSource + column, size);
 				}
 
-				tileLoadAndDraw(objectFile, tileSource, (uint16)(row + i));
+				tileLoadAndCache(objectFile, tileSource, (uint16)(row + i));
 				column = 0;
 				remaining -= size;
 				output += size;
@@ -355,7 +355,7 @@ byte *ComfyEngine::objFileReadTiledCore(uint32 sourceOffset, uint32 byteCount, O
 		return objectFile->readBuffer + (firstCached ? 0 : firstColumn);
 	}
 
-	tileListRemoveRange(objectFile, firstRow, lastRow);
+	tileListTouchRange(objectFile, firstRow, lastRow);
 	uint16 missing = 0;
 	uint16 row = firstRow;
 	while (row <= lastRow && row < objectFile->tileStatusCount && objectFile->tileStatus[row] == 0xFFFF) {
@@ -369,7 +369,7 @@ byte *ComfyEngine::objFileReadTiledCore(uint32 sourceOffset, uint32 byteCount, O
 	if (missing) {
 		objFileReadRow(objectFile->readBuffer, firstRow, missing, blockSize, objectFile);
 		for (uint16 i = 0; i < missing; i++)
-			tileLoadAndDraw(objectFile, objectFile->readBuffer + (uint32)i * blockSize, (uint16)(firstRow + i));
+			tileLoadAndCache(objectFile, objectFile->readBuffer + (uint32)i * blockSize, (uint16)(firstRow + i));
 	}
 
 	missing = 0;
@@ -391,7 +391,7 @@ byte *ComfyEngine::objFileReadTiledCore(uint32 sourceOffset, uint32 byteCount, O
 		for (uint16 i = missing; i != 0; i--) {
 			uint16 tileId = (uint16)(lastRow - i + 1);
 			uint16 bufferRow = (uint16)(missing - i);
-			tileLoadAndDraw(objectFile, objectFile->readBuffer + (uint32)bufferRow * blockSize, tileId);
+			tileLoadAndCache(objectFile, objectFile->readBuffer + (uint32)bufferRow * blockSize, tileId);
 		}
 	}
 
@@ -423,7 +423,7 @@ byte *ComfyEngine::frameLoaderReadFrameData(uint32 sourceOffset, uint32 byteCoun
 	return data;
 }
 
-ComfyEngine::ObjFile *ComfyEngine::objFileLoadSoundData(const Common::Path &path, uint16 blockSize,
+ComfyEngine::ObjFile *ComfyEngine::objFileOpen(const Common::Path &path, uint16 blockSize,
 		uint32 maximumBytes) {
 	Common::SeekableReadStream *stream = pathFOpen(path, true);
 	if (!stream || stream->size() < 0 || (uint64)stream->size() > UINT32_MAX || !blockSize) {
@@ -462,7 +462,7 @@ ComfyEngine::ObjFile *ComfyEngine::objFileLoadSoundData(const Common::Path &path
 		if (cacheHandle >= 0)
 			memFreeTrack((uint16)cacheHandle);
 
-		soundBufFree(objectFile);
+		objFileClose(objectFile);
 		return nullptr;
 	}
 
@@ -482,7 +482,7 @@ ComfyEngine::ObjFile *ComfyEngine::objFileLoadSoundData(const Common::Path &path
 	return objectFile;
 }
 
-void ComfyEngine::soundBufFree(ObjFile *&objectFile) {
+void ComfyEngine::objFileClose(ObjFile *&objectFile) {
 	if (!objectFile)
 		return;
 
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index 444613a6813..5264ec5775b 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -53,18 +53,18 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 	WRITE_LE_UINT16(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x18A], _midiTracks.count);
 	if (_engineVersion == 3) {
 		byte *vocState = &_sceneMemoryBlock[_sceneMidiInstanceOffset + COMFY_SCENE_MIDI_INSTANCE_BYTES];
-		vocState[0] = _wcomfy99VocState0;
-		vocState[1] = _wcomfy99VocState1;
-		vocState[2] = _wcomfy99VocState2;
-		vocState[3] = _wcomfy99VocState3;
-		vocState[6] = _wcomfy99VocState6;
+		vocState[0] = _v3SceneWaveBalancePercent;
+		vocState[1] = _v3SceneHostMediaModeEnabled;
+		vocState[2] = _v3SceneWaveLeftPercent;
+		vocState[3] = _v3SceneWaveRightPercent;
+		vocState[6] = _v3SceneMixerVolumePercent;
 		for (uint i = 0; i < COMFY_VOC_QUEUE_CAPACITY; i++) {
 			byte *packedEntry = vocState + 7 + i * 0x1F;
-			VocQueueEntry1999 &entry = _vocQueue1999[i];
+			VocQueueEntryV3 &entry = _vocQueueV3[i];
 			WRITE_LE_UINT16(packedEntry, entry.soundId);
 			WRITE_LE_UINT16(packedEntry + 2, entry.argumentCount);
 			WRITE_LE_UINT16(packedEntry + 4, entry.state);
-			for (uint argument = 0; argument < COMFY_VOC_ARG_CAPACITY_1999; argument++)
+			for (uint argument = 0; argument < COMFY_VOC_ARG_CAPACITY_V3; argument++)
 				WRITE_LE_UINT16(packedEntry + 6 + argument * 2, entry.arguments[argument]);
 
 			packedEntry[0x1E] = entry.clearArgumentKeys;
@@ -211,7 +211,7 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 		animFilePackState(&_sceneMemoryBlock[_sceneAnimStateOffset]);
 }
 
-void ComfyEngine::envConvToXms(byte *source, uint16 index) {
+void ComfyEngine::environmentPackToXms(byte *source, uint16 index) {
 	if (!index || _sceneMemoryBlock.empty())
 		error("Invalid environment XMS destination %u", (uint)index);
 
@@ -225,7 +225,7 @@ void ComfyEngine::envConvToXms(byte *source, uint16 index) {
 		error("Environment XMS destination %u is outside the allocated block", (uint)index);
 }
 
-bool ComfyEngine::envXmsToConv(byte *destination, uint16 index) {
+bool ComfyEngine::environmentUnpackFromXms(byte *destination, uint16 index) {
 	if (!index || _sceneMemoryBlock.empty())
 		error("Invalid environment XMS source %u", (uint)index);
 
@@ -264,18 +264,18 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 	midiFindNext(_midiTracks);
 	if (_engineVersion == 3) {
 		byte *vocState = &_sceneMemoryBlock[_sceneMidiInstanceOffset + COMFY_SCENE_MIDI_INSTANCE_BYTES];
-		_wcomfy99VocState0 = vocState[0];
-		_wcomfy99VocState1 = vocState[1];
-		_wcomfy99VocState2 = vocState[2];
-		_wcomfy99VocState3 = vocState[3];
-		_wcomfy99VocState6 = vocState[6];
+		_v3SceneWaveBalancePercent = vocState[0];
+		_v3SceneHostMediaModeEnabled = vocState[1];
+		_v3SceneWaveLeftPercent = vocState[2];
+		_v3SceneWaveRightPercent = vocState[3];
+		_v3SceneMixerVolumePercent = vocState[6];
 		for (uint i = 0; i < COMFY_VOC_QUEUE_CAPACITY; i++) {
 			byte *packedEntry = vocState + 7 + i * 0x1F;
-			VocQueueEntry1999 &entry = _vocQueue1999[i];
+			VocQueueEntryV3 &entry = _vocQueueV3[i];
 			entry.soundId = READ_LE_UINT16(packedEntry);
-			entry.argumentCount = MIN<uint16>(READ_LE_UINT16(packedEntry + 2), COMFY_VOC_ARG_CAPACITY_1999);
+			entry.argumentCount = MIN<uint16>(READ_LE_UINT16(packedEntry + 2), COMFY_VOC_ARG_CAPACITY_V3);
 			entry.state = READ_LE_UINT16(packedEntry + 4);
-			for (uint argument = 0; argument < COMFY_VOC_ARG_CAPACITY_1999; argument++)
+			for (uint argument = 0; argument < COMFY_VOC_ARG_CAPACITY_V3; argument++)
 				entry.arguments[argument] = READ_LE_UINT16(packedEntry + 6 + argument * 2);
 
 			entry.clearArgumentKeys = packedEntry[0x1E] != 0;
@@ -418,7 +418,7 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 
 }
 
-void ComfyEngine::sceneGoto(uint16 count) {
+void ComfyEngine::sceneEntryInit(uint16 count) {
 	if (_midiPlyrDriver)
 		_midiPlyrDriver->musicStopAll(1);
 
@@ -437,7 +437,7 @@ void ComfyEngine::sceneGoto(uint16 count) {
 	}
 }
 
-void ComfyEngine::sceneStop() {
+void ComfyEngine::sceneEntryStop() {
 	if (_midiPlyrDriver)
 		_midiPlyrDriver->musicStopAll(1);
 
@@ -453,14 +453,14 @@ void ComfyEngine::sceneStartWithMusic(uint16 scene) {
 	if (!_musicEnabled && _midiPlyrDriver)
 		_midiPlyrDriver->musicStopAll(1);
 
-	if (!envXmsToConv(&_sceneMemoryBlock[_sceneMidiInstanceOffset], scene))
+	if (!environmentUnpackFromXms(&_sceneMemoryBlock[_sceneMidiInstanceOffset], scene))
 		return;
 
 	_debugSceneGeneration++;
 
 	midiSyncAndScan();
 	if (!_musicEnabled)
-		midiStopAll();
+		midiRestartChannels();
 
 	Actor *root = actorGetPtr(0);
 	if (root) {
@@ -473,7 +473,7 @@ void ComfyEngine::sceneStartWithMusic(uint16 scene) {
 		memcpy(_keyBits, keySnapshot, MIN<uint32>(sizeof(keySnapshot), _keyBitsSize));
 
 	if (_engineVersion == 3)
-		wcomfy99RestoreHostStateAfterSceneStart();
+		restoreWaveStateAfterSceneStart();
 }
 
 bool ComfyEngine::sceneEntryLoad(uint16 descriptor, uint16 index) {
@@ -609,8 +609,8 @@ void ComfyEngine::sceneShutdown() {
 	_midiFileStream = nullptr;
 	_sceneFrameData.clear();
 	if (_engineVersion == 3) {
-		_wcomfy99VocState2 = 0xFF;
-		_wcomfy99VocState3 = 0xFF;
+		_v3SceneWaveLeftPercent = 0xFF;
+		_v3SceneWaveRightPercent = 0xFF;
 	}
 
 	_sceneOpen = false;
diff --git a/engines/comfy/script.cpp b/engines/comfy/script.cpp
index 0a74207ed27..0b3e6e58abc 100644
--- a/engines/comfy/script.cpp
+++ b/engines/comfy/script.cpp
@@ -31,6 +31,7 @@ byte ComfyEngine::scriptReadByte(uint32 pc) {
 	uint16 tileIndex = (uint16)(pc / COMFY_TILE_SIZE);
 	uint16 tileOffset = (uint16)(pc % COMFY_TILE_SIZE);
 	int16 spriteId = (int16)(-(int16)tileIndex - 1);
+
 	SpriteResource *sprite = spriteGetPtr(spriteId);
 	uint16 frameId = (uint16)-spriteId;
 	if (!sprite || frameId >= _frameCacheEntries.size()) {
@@ -52,6 +53,7 @@ uint16 ComfyEngine::scriptReadWord(uint32 pc) {
 	uint16 tileIndex = (uint16)(pc / COMFY_TILE_SIZE);
 	uint16 tileOffset = (uint16)(pc % COMFY_TILE_SIZE);
 	int16 spriteId = (int16)(-(int16)tileIndex - 1);
+
 	SpriteResource *sprite = spriteGetPtr(spriteId);
 	uint16 frameId = (uint16)-spriteId;
 	if (!sprite || frameId >= _frameCacheEntries.size()) {
@@ -73,6 +75,7 @@ uint32 ComfyEngine::scriptReadDword(uint32 pc) {
 	uint16 tileIndex = (uint16)(pc / COMFY_TILE_SIZE);
 	uint16 tileOffset = (uint16)(pc % COMFY_TILE_SIZE);
 	int16 spriteId = (int16)(-(int16)tileIndex - 1);
+
 	SpriteResource *sprite = spriteGetPtr(spriteId);
 	uint16 frameId = (uint16)-spriteId;
 	if (!sprite || frameId >= _frameCacheEntries.size()) {
@@ -92,8 +95,8 @@ uint32 ComfyEngine::scriptReadDword(uint32 pc) {
 
 uint16 ComfyEngine::scriptReadStringIndex(uint32 pc) {
 	uint16 value = scriptReadWord(pc);
-	if (value >= 0x7530) {
-		uint32 index = value - 0x7530;
+	if (value >= 30000) {
+		uint32 index = value - 30000;
 		if (index < _stringTable.size())
 			value = _stringTable[index];
 	}
@@ -136,5 +139,23 @@ uint32 ComfyEngine::scriptReadArgs(uint32 pc, uint16 fallbackActor, const char *
 	return pc;
 }
 
+void ComfyEngine::scriptVariableAddTo(uint16 variableIndex, int16 delta) {
+	if (variableIndex < _scriptVariables.size())
+		_scriptVariables[variableIndex] += delta;
+}
+
+void ComfyEngine::scriptVariableCopy(uint16 destination, uint16 source) {
+	if (destination < _scriptVariables.size() && source < _scriptVariables.size())
+		_scriptVariables[destination] = _scriptVariables[source];
+}
+
+void ComfyEngine::scriptVariableSet(uint16 variableIndex, uint16 value) {
+	if (variableIndex < _scriptVariables.size())
+		_scriptVariables[variableIndex] = value;
+}
+
+uint16 ComfyEngine::scriptVariableGet(uint16 variableIndex) {
+	return variableIndex < _scriptVariables.size() ? _scriptVariables[variableIndex] : 0;
+}
 
 } // End of namespace Comfy
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index ff0bbdc44a0..7089f67cc32 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -27,43 +27,171 @@
 
 namespace Comfy {
 
+#define O_ACTOR_SET_POSITION 0x01
+#define O_ACTOR_ADD_POSITION 0x02
+#define O_ACTOR_SET_FRAME 0x03
+#define O_WAIT_KEY_SET 0x04
+#define O_JUMP_IF_KEY_STATE 0x05
+#define O_SET_KEY_STATE 0x06
+#define O_ACTOR_DESTROY 0x07
+#define O_ACTOR_CREATE 0x08
+#define O_SET_CURRENT_ACTOR_FRAME 0x09
+#define O_ACTOR_SHOW 0x0A
+#define O_ACTOR_HIDE 0x0B
+#define O_ACTOR_ACTIVATE 0x0C
+#define O_ACTOR_DEACTIVATE 0x0D
+#define O_ACTOR_COMPARE_X_SET_KEY 0x0E
+#define O_ACTOR_COMPARE_Y_SET_KEY 0x0F
+#define O_ACTOR_COMPARE_X_CLEAR_KEY 0x10
+#define O_ACTOR_COMPARE_Y_CLEAR_KEY 0x11
+#define O_MIDI_ADD_TRACK 0x12
+#define O_RANDOM_JUMP 0x13
+#define O_ACTOR_REORDER 0x14
+#define O_LOAD_SPRITE_CONV_LIST 0x15
+#define O_LOAD_SOUND_LIST 0x16
+#define O_QUEUE_VOC 0x17
+#define O_ACTOR_RESET 0x18
+#define O_ACTOR_CALL_IF_KEY_STATE 0x19
+#define O_ACTOR_RETURN 0x1A
+#define O_PLAY_VOC_QUEUE 0x1B
+#define O_MIDI_REMOVE_TRACK 0x1C
+#define O_MIDI_CHANNEL_CONTROL 0x1D
+#define O_ACTOR_SET_TRIGGER 0x1E
+#define O_SET_MUSIC_EVENT 0x1F
+#define O_REQUEST_SCENE 0x20
+#define O_PALETTE_CONTROL 0x21
+#define O_SET_MUSIC_ENABLED 0x22
+#define O_SCRIPT_VARIABLE_ADD 0x23
+#define O_MIDI_SET_TIME_SCALE 0x24
+#define O_CLEAR_KEY_RANGE 0x25
+#define O_SCRIPT_VARIABLE_GE_VALUE_SET_KEY 0x26
+#define O_SKIP_WORD_28 0x28
+#define O_SKIP_WORD_29 0x29
+#define O_ACTOR_SET_SPRITE_SELECTOR 0x2A
+#define O_JUMP_RELATIVE 0x2B
+#define O_COPY_KEY 0x2C
+#define O_SCENE_CONTROL 0x2D
+#define O_SCRIPT_VARIABLE_GE_VARIABLE_SET_KEY 0x2E
+#define O_SCRIPT_VARIABLE_COPY 0x2F
+#define O_ANIMATION_CONTROL 0x30
+#define O_SET_LAST_VOC_ARGUMENTS 0x31
+#define O_UNUSED_32 0x32
+#define O_SKIP_TABLE_BLOCK 0x33
+#define O_CONFIG_STRING_COMMAND 0x34
+#define O_MOUSE_SET_ACTOR 0x35
+#define O_HOST_MEDIA_CONTROL 0x36
+#define O_ANIMATION_AUDIO_CONTROL 0x46
+#define O_PRELOAD_SPRITE_CONV_RANGE 0x47
+#define O_JUMP_IF_KEY_CLEAR_V3 0x48
+#define O_JUMP_IF_KEY_SET_V3 0x49
+#define O_STRING_TABLE_COMPARE_SET_KEY 0x50
+#define O_ACTOR_MOVE_BY 0x51
+#define O_ACTOR_MOVE_TO 0x52
+#define O_ACTOR_SET_FRAME_AND_STOP 0x53
+#define O_COPY_INLINE_BLOCK 0x54
+#define O_COPY_PALETTE_ENTRY 0x55
+#define O_WAIT 0x6E
+#define O_MIDI_ADD_EVENT 0x6F
+#define O_ACTOR_MOVE_BY_V2 0x70
+#define O_ACTOR_MOVE_TO_V2 0x71
+#define O_ACTOR_WAIT_TICKS 0x72
+#define O_WAVE_OUTPUT_RESET 0x73
+#define O_WAIT_KEY_CLEAR 0x74
+#define O_CONDITIONAL_SET_KEY 0x75
+#define O_STRING_TABLE_SET 0x76
+#define O_STRING_TABLE_SET_OFFSET 0x77
+#define O_NOP 0x7F
+
+#define SO_MIDI_LOAD_TRACK 1
+#define SO_MIDI_SET_RATE 2
+#define SO_MIDI_SET_PITCH 3
+#define SO_MIDI_SET_VOLUME 4
+#define SO_MIDI_STOP_AND_ADVANCE 5
+#define SO_MIDI_STOP_AND_FIRE_KEYS 6
+#define SO_MIDI_ENABLE_LOOP 7
+#define SO_MIDI_DISABLE_LOOP 8
+#define SO_SCENE_ENTRY_INIT 1
+#define SO_SCENE_ENTRY_STOP 2
+#define SO_SCENE_ENTRY_LOAD 3
+#define SO_SCENE_MIDI_PLAY_AT_FRAME 4
+#define SO_SCENE_MIDI_STOP 5
+#define SO_SCENE_MIDI_SET_VOLUME 6
+#define SO_ANIM_SHUTDOWN 0
+#define SO_ANIM_LOAD_FRAME 1
+#define SO_ANIM_SET_READY 2
+#define SO_ANIM_CLEAR_READY 3
+#define SO_ANIM_NOOP_4 4
+#define SO_ANIM_NOOP_5 5
+#define SO_ANIM_INVALIDATE_ACTOR_RECT 6
+#define SO_CONFIG_READ_INT 0
+#define SO_CONFIG_WRITE_INT 1
+#define SO_CONFIG_SUSPEND_ACTOR 2
+#define SO_CONFIG_RUN_COMMAND 3
+#define SO_CONFIG_TEST_VALUE 4
+#define SO_CONFIG_TEST_FILE 5
+#define SO_CONFIG_SET_LANGUAGE_DATA_SUBDIRECTORY 6
+#define SO_MOUSE_SET_ACTOR 1
+#define SO_MOUSE_CLEAR_ACTOR 2
+#define SO_HOST_MEDIA_START_INPUT 1
+#define SO_HOST_MEDIA_STOP_INPUT 2
+#define SO_HOST_MEDIA_START_RECORDING_2_ARGS 3
+#define SO_HOST_MEDIA_START_RECORDING_3_ARGS 4
+#define SO_HOST_MEDIA_START_RECORDING_4_ARGS 5
+#define SO_ANIMATION_INDEX_OFFSET 1
+#define SO_WAVE_BALANCE 2
+#define SO_ANIMATION_ACTOR_SCENE 3
+#define SO_WAVE_LEFT 4
+#define SO_WAVE_RIGHT 5
+#define SO_ANIMATION_AUDIO_NOOP 6
+#define SO_HOST_MEDIA_RANGE 7
+#define SO_MIXER_VOLUME 8
+#define SO_CONDITION_SCENE_EXISTS 1
+#define SO_CONDITION_INPUT_MODE 2
+#define SO_CONDITION_MOUSE_LEFT_BUTTON 3
+#define SO_CONDITION_MOUSE_LEFT_BUTTON_ALT 4
+#define SO_CONDITION_MOUSE_RIGHT_BUTTON 5
+#define SO_CONDITION_MOUSE_RIGHT_BUTTON_ALT 6
+#define SO_CONDITION_ACTOR_HIT_TEST 7
+#define SO_CONDITION_ACTOR_BLIT_HIT_TEST 8
+#define SO_CONDITION_FALSE 13
+#define SO_CONDITION_SYSTEM_FEATURE 14
+
 ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte opcode, uint32 &pc) {
 	switch (opcode) {
-	case 0x01:
-	case 0x02: {
-		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
-		pc += 2;
-		int16 x = scriptReadStringIndex(pc);
-		pc += 2;
-		int16 y = scriptReadStringIndex(pc);
-		pc += 2;
+	case O_ACTOR_SET_POSITION:
+	case O_ACTOR_ADD_POSITION: {
+		Actor *target = actorResolve(scriptReadWord(pc), _currentActor); pc += 2;
+		int16 x = scriptReadStringIndex(pc); pc += 2;
+		int16 y = scriptReadStringIndex(pc); pc += 2;
 		byte randomize = scriptReadByte(pc++);
+
 		if (!target)
 			error("Script opcode 0x%02X resolved an invalid actor", opcode);
 
-		if ((opcode == 0x01 && x == (int16)0xF830) || (opcode == 0x02 && x == (int16)0x8AD0)) {
+		if ((opcode == O_ACTOR_SET_POSITION && x == (int16)0xF830) || (opcode == O_ACTOR_ADD_POSITION && x == (int16)0x8AD0)) {
 			Actor *other = actorResolve((uint16)y, _currentActor);
 			if (!other)
 				error("Script opcode 0x%02X resolved an invalid reference actor", opcode);
 
 			x = (int16)(other->xFixed >> 12);
 			y = (int16)(other->yFixed >> 12);
-		} else if (opcode == 0x01 && x == (int16)0xF448) {
+		} else if (opcode == O_ACTOR_SET_POSITION && x == (int16)0xF448) {
 			x = (int16)(-target->xFixed >> 12);
 		}
 
-		if (opcode == 0x01 && y == (int16)0xF448)
+		if (opcode == O_ACTOR_SET_POSITION && y == (int16)0xF448)
 			y = (int16)(-target->yFixed >> 12);
 
 		if (randomize) {
-			if (opcode == 0x02 || x != (int16)0xFC18)
+			if (opcode == O_ACTOR_ADD_POSITION || x != (int16)0xFC18)
 				x = (int16)(((int32)getRandomNumber(0x7FFF) * x) / 0x8000);
 
-			if (opcode == 0x02 || y != (int16)0xFC18)
+			if (opcode == O_ACTOR_ADD_POSITION || y != (int16)0xFC18)
 				y = (int16)(((int32)getRandomNumber(0x7FFF) * y) / 0x8000);
 		}
 
-		if (opcode == 0x01) {
+
+		if (opcode == O_ACTOR_SET_POSITION) {
 			if (x != (int16)0xFC18)
 				target->xFixed = (int32)x * 0x1000;
 
@@ -74,22 +202,24 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			target->yFixed = (int32)((uint32)target->yFixed + (uint32)((int32)y * 0x1000));
 		}
 
+
 		return kScriptContinue;
 	}
 
-	case 0x03: {
+	case O_ACTOR_SET_FRAME: {
 		uint16 actorSlot = scriptReadWord(pc);
 		Actor *target = actorResolve(actorSlot, _currentActor);
 		pc += 2;
 		uint16 frame = scriptReadStringIndex(pc);
 		pc += 2;
-		if (target)
+		if (target) {
 			target->spriteSelector = (uint32)(int32)(int16)frame;
+		}
 
 		return kScriptContinue;
 	}
 
-	case 0x04: {
+	case O_WAIT_KEY_SET: {
 		uint16 key = scriptReadWord(pc);
 		if (key && !keyBitTest(key)) {
 			pc--;
@@ -100,14 +230,14 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x05:
-	case 0x19: {
+	case O_JUMP_IF_KEY_STATE:
+	case O_ACTOR_CALL_IF_KEY_STATE: {
 		uint16 key = scriptReadWord(pc);
 		byte state = scriptReadByte(pc + 2);
 		uint32 targetPc = scriptReadDword(pc + 3);
 		pc += 7;
 		if (!key || (byte)keyBitTest(key) == state) {
-			if (opcode == 0x19)
+			if (opcode == O_ACTOR_CALL_IF_KEY_STATE)
 				actorSetPc(actor, pc);
 
 			pc = targetPc;
@@ -116,7 +246,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x06: {
+	case O_SET_KEY_STATE: {
 		uint16 key = scriptReadWord(pc);
 		byte state = scriptReadByte(pc + 2);
 		pc += 3;
@@ -128,7 +258,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x07: {
+	case O_ACTOR_DESTROY: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		pc += 2;
 		if (!target)
@@ -142,7 +272,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return current ? kScriptYield : kScriptContinue;
 	}
 
-	case 0x08: {
+	case O_ACTOR_CREATE: {
 		uint16 sceneSlot = scriptReadWord(pc);
 		uint16 parentSlot = scriptReadWord(pc + 2);
 		byte flags = scriptReadByte(pc + 4);
@@ -162,36 +292,36 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x09: {
+	case O_SET_CURRENT_ACTOR_FRAME: {
 		int16 frame = scriptReadWord(pc);
 		actorSetFrame(frame);
 		pc += 2;
 		if (!_usesAnimFile && _videoMode == 2)
-			videoSetResolution();
+			renderAddFullFrameDirtyRect();
 
 		return kScriptContinue;
 	}
 
-	case 0x0A:
-	case 0x0B:
-	case 0x0C:
-	case 0x0D: {
+	case O_ACTOR_SHOW:
+	case O_ACTOR_HIDE:
+	case O_ACTOR_ACTIVATE:
+	case O_ACTOR_DEACTIVATE: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		pc += 2;
 		if (!target)
 			error("Script opcode 0x%02X resolved an invalid actor", opcode);
 
 		switch (opcode) {
-		case 0x0A:
+		case O_ACTOR_SHOW:
 			target->visible = 1;
 			break;
-		case 0x0B:
+		case O_ACTOR_HIDE:
 			target->visible = 0;
 			break;
-		case 0x0C:
+		case O_ACTOR_ACTIVATE:
 			target->active = 1;
 			break;
-		case 0x0D:
+		case O_ACTOR_DEACTIVATE:
 			target->moveTicks = 0;
 			target->active = 0;
 			if (target == &actor)
@@ -205,10 +335,10 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x0E:
-	case 0x0F:
-	case 0x10:
-	case 0x11: {
+	case O_ACTOR_COMPARE_X_SET_KEY:
+	case O_ACTOR_COMPARE_Y_SET_KEY:
+	case O_ACTOR_COMPARE_X_CLEAR_KEY:
+	case O_ACTOR_COMPARE_Y_CLEAR_KEY: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		int16 expected = scriptReadWord(pc + 2);
 		uint16 key = scriptReadWord(pc + 4);
@@ -217,16 +347,16 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		if (!target)
 			error("Script opcode 0x%02X resolved an invalid actor", opcode);
 
-		int16 actual = (opcode == 0x0E || opcode == 0x10 ? target->xFixed : target->yFixed) >> 12;
+		int16 actual = (opcode == O_ACTOR_COMPARE_X_SET_KEY || opcode == O_ACTOR_COMPARE_X_CLEAR_KEY ? target->xFixed : target->yFixed) >> 12;
 		bool matched = ((mode & 2) && expected == actual) || ((mode & 4) && expected < actual) || ((mode & 1) && expected > actual);
 		if (matched) {
 			switch (opcode) {
-			case 0x0E:
-			case 0x0F:
+			case O_ACTOR_COMPARE_X_SET_KEY:
+			case O_ACTOR_COMPARE_Y_SET_KEY:
 				keyBitSet(key);
 				break;
-			case 0x10:
-			case 0x11:
+			case O_ACTOR_COMPARE_X_CLEAR_KEY:
+			case O_ACTOR_COMPARE_Y_CLEAR_KEY:
 				keyBitClear(key);
 				break;
 			default:
@@ -237,7 +367,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x12: {
+	case O_MIDI_ADD_TRACK: {
 		uint16 id = scriptReadWord(pc);
 		int16 delta = scriptReadStringIndex(pc + 2);
 		pc += 4;
@@ -245,7 +375,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x13: {
+	case O_RANDOM_JUMP: {
 		byte totalWeight = scriptReadByte(pc++);
 		byte installReturnPc = scriptReadByte(pc++);
 		uint32 returnPc = pc + installReturnPc - 3;
@@ -265,7 +395,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x14: {
+	case O_ACTOR_REORDER: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		byte mode = scriptReadByte(pc + 2);
 		pc += 3;
@@ -284,22 +414,22 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		if (_usesAnimFile && (_videoMode == 2 || _videoMode == 4))
 			renderInvalidateFullFrame();
 		else if (!_usesAnimFile && _videoMode == 2)
-			videoSetResolution();
+			renderAddFullFrameDirtyRect();
 
 		return kScriptContinue;
 	}
 
-	case 0x15:
-	case 0x16: {
+	case O_LOAD_SPRITE_CONV_LIST:
+	case O_LOAD_SOUND_LIST: {
 		byte count = scriptReadByte(pc++);
 		for (uint i = 0; i < count; i++) {
 			uint16 id = scriptReadWord(pc);
 			pc += 2;
 			switch (opcode) {
-			case 0x15:
+			case O_LOAD_SPRITE_CONV_LIST:
 				spriteGetConvPtr((int16)id);
 				break;
-			case 0x16:
+			case O_LOAD_SOUND_LIST:
 				soundLoadEntry(id);
 				break;
 			default:
@@ -310,7 +440,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x17: {
+	case O_QUEUE_VOC: {
 		if (_musicEventMask) {
 			pc--;
 			return kScriptYield;
@@ -324,7 +454,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x18: {
+	case O_ACTOR_RESET: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		pc += 2;
 		if (!target)
@@ -350,28 +480,28 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x1A: {
+	case O_ACTOR_RETURN: {
 		pc = actorPopPc(actor);
 		return kScriptContinue;
 	}
 
-	case 0x1B: {
+	case O_PLAY_VOC_QUEUE: {
 		vocQueuePlayAll();
 		return kScriptContinue;
 	}
 
-	case 0x1C: {
+	case O_MIDI_REMOVE_TRACK: {
 		midiRemoveTrack(scriptReadWord(pc));
 		pc += 2;
 		return kScriptContinue;
 	}
 
-	case 0x1D: {
+	case O_MIDI_CHANNEL_CONTROL: {
 		byte packed = scriptReadByte(pc++);
 		byte channel = (packed >> 4) - 1;
 		byte subop = packed & 0x0F;
 		switch (subop) {
-		case 1: {
+		case SO_MIDI_LOAD_TRACK: {
 			uint16 songId = scriptReadWord(pc);
 			uint16 completionKey = scriptReadWord(pc + 2);
 			uint16 count = scriptReadWord(pc + 4);
@@ -389,27 +519,27 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			midiAddTrackEntry(channel, songId, completionKey, 1, count, frames);
 			break;
 		}
-		case 2:
-		case 3:
-		case 4: {
-			uint16 value = scriptReadWord(pc);
-			uint16 ticks = scriptReadWord(pc + 2);
+		case SO_MIDI_SET_RATE:
+		case SO_MIDI_SET_PITCH:
+		case SO_MIDI_SET_VOLUME: {
+			uint16 value = _engineVersion == 1 ? scriptReadWord(pc) : scriptReadStringIndex(pc);
+			uint16 ticks = _engineVersion == 1 ? scriptReadWord(pc + 2) : scriptReadStringIndex(pc + 2);
 			pc += 4;
 			midiSetChannelParam(channel, subop, value, ticks);
 			break;
 		}
-		case 5:
+		case SO_MIDI_STOP_AND_ADVANCE:
 			if (channel < COMFY_MIDI_CHANNEL_COUNT)
-				midiStopAndRemove(channel);
+				midiStopAndAdvanceChannel(channel);
 			break;
-		case 6:
+		case SO_MIDI_STOP_AND_FIRE_KEYS:
 			if (channel < COMFY_MIDI_CHANNEL_COUNT)
 				midiStopAndFireKeys(channel);
 			break;
-		case 7:
-		case 8:
+		case SO_MIDI_ENABLE_LOOP:
+		case SO_MIDI_DISABLE_LOOP:
 			if (_engineVersion == 3 && channel < COMFY_MIDI_CHANNEL_COUNT && _midiPlyrDriver)
-				_midiPlyrDriver->musicSetLoop(subop == 7 ? 1 : 0, channel);
+				_midiPlyrDriver->musicSetLoop(subop == SO_MIDI_ENABLE_LOOP ? 1 : 0, channel);
 
 			break;
 		default:
@@ -419,7 +549,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x1E: {
+	case O_ACTOR_SET_TRIGGER: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		uint16 key = scriptReadWord(pc + 2);
 		byte flags = scriptReadByte(pc + 4);
@@ -441,7 +571,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x1F: {
+	case O_SET_MUSIC_EVENT: {
 		uint16 bit = scriptReadWord(pc);
 		pc += 2;
 		if ((int16)bit >= 0x32) {
@@ -454,19 +584,19 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptYield;
 	}
 
-	case 0x20: {
+	case O_REQUEST_SCENE: {
 		uint16 scene = scriptReadWord(pc);
 		pc += 2;
 		if (!_pendingScene || (int16)scene < (int16)_pendingScene)
 			_pendingScene = scene;
 
 		if (_videoMode == 2 || (_usesAnimFile && _videoMode == 4))
-			renderSetDirty();
+			renderRequestFullFrameInvalidation();
 
 		return kScriptYield;
 	}
 
-	case 0x21: {
+	case O_PALETTE_CONTROL: {
 		uint16 paletteId = scriptReadStringIndex(pc);
 		uint16 fadeTicks = scriptReadStringIndex(pc + 2);
 		byte brightness = scriptReadByte(pc + 4);
@@ -482,28 +612,28 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x22: {
+	case O_SET_MUSIC_ENABLED: {
 		musicSetEnabled(scriptReadByte(pc));
 		pc++;
 		return kScriptContinue;
 	}
 
-	case 0x23: {
+	case O_SCRIPT_VARIABLE_ADD: {
 		uint16 handle = scriptReadWord(pc);
 		int16 delta = scriptReadStringIndex(pc + 2);
 		pc += 4;
-		midiHandleAddTo(handle, delta);
+		scriptVariableAddTo(handle, delta);
 
 		return kScriptContinue;
 	}
 
-	case 0x24: {
+	case O_MIDI_SET_TIME_SCALE: {
 		midiSetTimeScale((int16)scriptReadStringIndex(pc));
 		pc += 2;
 		return kScriptContinue;
 	}
 
-	case 0x25: {
+	case O_CLEAR_KEY_RANGE: {
 		uint16 first = scriptReadWord(pc);
 		uint16 last = scriptReadWord(pc + 2);
 		pc += 4;
@@ -516,27 +646,27 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x26:
-	case 0x2E: {
+	case O_SCRIPT_VARIABLE_GE_VALUE_SET_KEY:
+	case O_SCRIPT_VARIABLE_GE_VARIABLE_SET_KEY: {
 		uint16 first = scriptReadWord(pc);
 		uint16 second = scriptReadWord(pc + 2);
 		uint16 key = scriptReadWord(pc + 4);
 		pc += 6;
-		int16 lhs = (int16)midiGetHandle(first);
-		int16 rhs = opcode == 0x26 ? (int16)second : (int16)midiGetHandle(second);
+		int16 lhs = (int16)scriptVariableGet(first);
+		int16 rhs = opcode == O_SCRIPT_VARIABLE_GE_VALUE_SET_KEY ? (int16)second : (int16)scriptVariableGet(second);
 		if (lhs >= rhs)
 			keyBitSet(key);
 
 		return kScriptContinue;
 	}
 
-	case 0x28:
-	case 0x29: {
+	case O_SKIP_WORD_28:
+	case O_SKIP_WORD_29: {
 		pc += 2;
 		return kScriptContinue;
 	}
 
-	case 0x2A: {
+	case O_ACTOR_SET_SPRITE_SELECTOR: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		uint32 selector = scriptReadDword(pc + 2);
 		pc += 6;
@@ -546,12 +676,12 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x2B: {
+	case O_JUMP_RELATIVE: {
 		pc = (uint32)((int32)pc + (int16)(scriptReadWord(pc) * 2));
 		return kScriptContinue;
 	}
 
-	case 0x2C: {
+	case O_COPY_KEY: {
 		uint16 destination = scriptReadWord(pc);
 		uint16 source = scriptReadWord(pc + 2);
 		pc += 4;
@@ -564,37 +694,37 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x2D: {
+	case O_SCENE_CONTROL: {
 		byte subop = scriptReadByte(pc++);
 		switch (subop) {
-		case 1:
-			sceneGoto(scriptReadWord(pc));
+		case SO_SCENE_ENTRY_INIT:
+			sceneEntryInit(scriptReadWord(pc));
 			pc += 2;
 			break;
-		case 2:
-			sceneStop();
+		case SO_SCENE_ENTRY_STOP:
+			sceneEntryStop();
 			break;
-		case 3: {
+		case SO_SCENE_ENTRY_LOAD: {
 			uint16 descriptor = scriptReadWord(pc);
-			uint16 index = scriptReadWord(pc + 2);
+			uint16 index = _engineVersion == 1 ? scriptReadWord(pc + 2) : scriptReadStringIndex(pc + 2);
 			pc += 4;
 			sceneEntryLoad(descriptor, index);
 			break;
 		}
-		case 4: {
-			uint16 channel = scriptReadWord(pc);
-			uint16 frame = scriptReadWord(pc + 2);
+		case SO_SCENE_MIDI_PLAY_AT_FRAME: {
+			uint16 channel = _engineVersion == 1 ? scriptReadWord(pc) : scriptReadStringIndex(pc);
+			uint16 frame = _engineVersion == 1 ? scriptReadWord(pc + 2) : scriptReadStringIndex(pc + 2);
 			pc += 4;
 			midiPlaySongAtFrame(channel, frame);
 			break;
 		}
-		case 5: {
-			uint16 channel = scriptReadWord(pc);
+		case SO_SCENE_MIDI_STOP: {
+			uint16 channel = _engineVersion == 1 ? scriptReadWord(pc) : scriptReadStringIndex(pc);
 			pc += 2;
 			midiStopSong(channel);
 			break;
 		}
-		case 6:
+		case SO_SCENE_MIDI_SET_VOLUME:
 			if (_engineVersion >= 2) {
 				uint16 channel = scriptReadStringIndex(pc);
 				uint16 volume = scriptReadStringIndex(pc + 2);
@@ -610,47 +740,62 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x2F: {
+	case O_SCRIPT_VARIABLE_COPY: {
 		byte command = scriptReadByte(pc);
 		uint16 destination = scriptReadWord(pc + 1);
 		uint16 first = scriptReadWord(pc + 3);
 		uint16 second = scriptReadWord(pc + 5);
 		pc += 7;
 		if (command == '=')
-			midiHandleCopy(destination, first);
+			scriptVariableCopy(destination, first);
 		else if (command == 'm')
-			midiHandleCopy(destination,
-				(int16)midiGetHandle(second) <= (int16)midiGetHandle(first) ? first : second);
+			scriptVariableCopy(destination,
+				(int16)scriptVariableGet(second) <= (int16)scriptVariableGet(first) ? first : second);
 
 		return kScriptContinue;
 	}
 
-	case 0x30:
+	case O_ANIMATION_CONTROL:
 		if (!_usesAnimFile)
 			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
 	{
 		byte subop = scriptReadByte(pc++);
 		switch (subop) {
-		case 0:
+		case SO_ANIM_SHUTDOWN:
 			animFrameShutdown(true);
 			break;
-		case 1: {
-			uint16 animIndex = scriptReadWord(pc);
+		case SO_ANIM_LOAD_FRAME: {
+			uint16 animIndex = _engineVersion == 3 ? scriptReadStringIndex(pc) : scriptReadWord(pc);
 			uint16 frameKey = scriptReadWord(pc + 2);
 			pc += 4;
-			animFileLoadFrame(animIndex, frameKey, actor.sceneHandle);
+
+			if (_engineVersion == 3) {
+				animIndex += _v3AnimIndexOffset;
+				_v3AnimIndexOffset = 0;
+
+				if (!animFrameIsActive()) {
+					if (!_v3AnimActorSceneHandle)
+						_v3AnimActorSceneHandle = actor.sceneHandle;
+
+					animFileLoadFrame(animIndex, frameKey, _v3AnimActorSceneHandle);
+					_v3AnimActorSceneHandle = 0;
+				}
+			} else {
+				animFileLoadFrame(animIndex, frameKey, actor.sceneHandle);
+			}
+
 			break;
 		}
-		case 2:
+		case SO_ANIM_SET_READY:
 			animFrameSetReady(true);
 			break;
-		case 3:
+		case SO_ANIM_CLEAR_READY:
 			animFrameSetReady(false);
 			break;
-		case 4:
-		case 5:
+		case SO_ANIM_NOOP_4:
+		case SO_ANIM_NOOP_5:
 			break;
-		case 6:
+		case SO_ANIM_INVALIDATE_ACTOR_RECT:
 			if (_engineVersion == 3)
 				animFrameInvalidateActorRect();
 
@@ -662,27 +807,27 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x31:
-	case 0x32:
-	case 0x33:
-	case 0x34:
-	case 0x35:
-	case 0x36:
-		if (!(_usesWcomfy99ScriptOps ||
-			(opcode == 0x31 && (_game->scriptFeatures & COMFY_SCRIPT_OPCODE_31)) ||
-			(opcode == 0x32 && (_game->scriptFeatures & COMFY_SCRIPT_OPCODE_32)) ||
-			(opcode == 0x33 && (_game->scriptFeatures & COMFY_SCRIPT_OPCODE_33))))
+	case O_SET_LAST_VOC_ARGUMENTS:
+	case O_UNUSED_32:
+	case O_SKIP_TABLE_BLOCK:
+	case O_CONFIG_STRING_COMMAND:
+	case O_MOUSE_SET_ACTOR:
+	case O_HOST_MEDIA_CONTROL:
+		if (!((_engineVersion == 3) ||
+			(opcode == O_SET_LAST_VOC_ARGUMENTS && (_game->scriptFeatures & COMFY_SCRIPT_OPCODE_31)) ||
+			(opcode == O_UNUSED_32 && (_game->scriptFeatures & COMFY_SCRIPT_OPCODE_32)) ||
+			(opcode == O_SKIP_TABLE_BLOCK && (_game->scriptFeatures & COMFY_SCRIPT_OPCODE_33))))
 			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
 	{
 		switch (opcode) {
-		case 0x31: {
+		case O_SET_LAST_VOC_ARGUMENTS: {
 			uint16 count = scriptReadStringIndex(pc);
 			pc += 2;
 			if (_animUsesWaveVocCounter) {
 				uint16 slot = _soundEventMaximum ? _soundEventMaximum - 1 : _vocQueueCapacity - 1;
 				if (_engineVersion == 3) {
-					VocQueueEntry1999 &entry = _vocQueue1999[slot];
-					entry.argumentCount = MIN<uint16>(count, COMFY_VOC_ARG_CAPACITY_1999);
+					VocQueueEntryV3 &entry = _vocQueueV3[slot];
+					entry.argumentCount = MIN<uint16>(count, COMFY_VOC_ARG_CAPACITY_V3);
 					for (uint i = 0; i < entry.argumentCount; i++)
 						entry.arguments[i] = scriptReadWord(pc + i * 2);
 				} else {
@@ -697,19 +842,19 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 			break;
 		}
-		case 0x32:
+		case O_UNUSED_32:
 			scriptReadStringIndex(pc);
 			scriptReadStringIndex(pc + 2);
 			pc += 4;
 			break;
-		case 0x33: {
+		case O_SKIP_TABLE_BLOCK: {
 			pc += 4;
 			byte inlineBytes = scriptReadByte(pc++);
 			byte tripleCount = scriptReadByte(pc++);
 			pc += inlineBytes + (uint32)tripleCount * 3;
 			break;
 		}
-		case 0x34: {
+		case O_CONFIG_STRING_COMMAND: {
 			byte subop = scriptReadByte(pc++);
 			uint16 value = scriptReadWord(pc);
 			pc += 2;
@@ -717,29 +862,43 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			for (byte character = scriptReadByte(pc++); character; character = scriptReadByte(pc++))
 				key += (char)character;
 
-			key.trim();
-
 			switch (subop) {
-			case 0:
+			case SO_CONFIG_READ_INT:
 				if (value < _stringTable.size())
 					_stringTable[value] = ConfMan.hasKey(key) ? ConfMan.getInt(key) : 0;
 
 				break;
-			case 1:
+			case SO_CONFIG_WRITE_INT:
 				ConfMan.setInt(key, value);
 				if (key.equalsIgnoreCase("SENSITIVITY"))
-					_wcomfy99Sensitivity = value;
+					_v3Sensitivity = value;
 
 				ConfMan.flushToDisk();
 				break;
-			case 4:
+			case SO_CONFIG_SUSPEND_ACTOR:
+			case SO_CONFIG_RUN_COMMAND:
+				_v3ConfigCommandPending = true;
+				_v3ConfigCommandSubop = subop;
+				_v3ConfigCommandValue = value;
+				_v3ConfigCommandText = key;
+
+				if (subop == SO_CONFIG_SUSPEND_ACTOR) {
+					Actor *configActor = actorGetPtr(sceneGetHandle(1));
+					if (configActor)
+						configActor->active = 0;
+				} else {
+					configRunPendingCommand();
+				}
+
+				break;
+			case SO_CONFIG_TEST_VALUE:
 				if (ConfMan.hasKey(key) && !ConfMan.get(key).equalsIgnoreCase("?????"))
 					keyBitSet(value);
 				else
 					keyBitClear(value);
 
 				break;
-			case 5: {
+			case SO_CONFIG_TEST_FILE: {
 				Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(Common::Path(key), true));
 				if (stream)
 					keyBitSet(value);
@@ -748,57 +907,62 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 				break;
 			}
-			case 6: {
-				key.trim();
-				byte last = key.empty() ? 0 : key.lastChar();
+			case SO_CONFIG_SET_LANGUAGE_DATA_SUBDIRECTORY:
 				if (value < _stringTable.size())
-					_stringTable[value] = Common::isSpace(last) ? 0x81 : Common::isDigit(last) ? 0x12 :
-						(Common::isAlpha(last) ? (Common::isUpper(last) ? 0x04 : 0x08) : 0x40);
+					_stringTable[value] = languageSetDataSubdirectory(key);
 
 				break;
-			}
 			default:
 				error("Unknown script opcode 0x34 subopcode 0x%02X near script PC 0x%08X", subop, pc);
 			}
 
 			break;
 		}
-		case 0x35: {
-			byte subop = scriptReadByte(pc++);
+		case O_MOUSE_SET_ACTOR: {
+			uint32 opcodePc = pc - 1;
+			byte subop = 0;
+			Actor *mouseActor = nullptr;
+			pc = scriptReadArgs(pc, _currentActor, "CO", &subop, &mouseActor);
 			switch (subop) {
-			case 2:
-				_wcomfy99SubsystemWord = 0;
+			case SO_MOUSE_SET_ACTOR:
+				mouseSetActor(mouseActor);
+				break;
+			case SO_MOUSE_CLEAR_ACTOR:
+				mouseSetActor(nullptr);
 				break;
 			default:
-				error("Unknown script opcode 0x35 subopcode 0x%02X at script PC 0x%08X", subop, pc - 2);
+				error("Unknown script opcode 0x35 subopcode 0x%02X at script PC 0x%08X", subop, opcodePc);
 			}
 
 			break;
 		}
-		case 0x36: {
+		case O_HOST_MEDIA_CONTROL: {
 			byte subop = scriptReadByte(pc++);
 			switch (subop) {
-			case 1:
-				_wcomfy99RecordHostEnabled = true;
+			case SO_HOST_MEDIA_START_INPUT:
+				setMediaMode(subop);
 				break;
-			case 2:
-				_wcomfy99RecordHostEnabled = false;
+			case SO_HOST_MEDIA_STOP_INPUT:
+				setMediaMode(subop);
+				_v3HostMediaRecording = false;
 				break;
-			case 3:
-			case 4:
-			case 5:
-				_wcomfy99MixedHostFirstWord = scriptReadWord(pc);
-				_wcomfy99MixedHostSecondWord = scriptReadWord(pc + 2);
+			case SO_HOST_MEDIA_START_RECORDING_2_ARGS:
+			case SO_HOST_MEDIA_START_RECORDING_3_ARGS:
+			case SO_HOST_MEDIA_START_RECORDING_4_ARGS:
+				_v3HostMediaRecordingArg0 = scriptReadStringIndex(pc);
+				_v3HostMediaRecordingArg1 = scriptReadWord(pc + 2);
 				pc += 4;
-				_wcomfy99RecordHostEnabled = true;
+				_v3HostMediaRecording = true;
+				if (!_v3SceneHostMediaModeEnabled)
+					setMediaMode(SO_HOST_MEDIA_START_INPUT);
 
-				if (subop != 3) {
-					_wcomfy99MixedHostThirdWord = scriptReadWord(pc);
+				if (subop != SO_HOST_MEDIA_START_RECORDING_2_ARGS) {
+					_v3HostMediaRecordingArg2 = scriptReadStringIndex(pc);
 					pc += 2;
 				}
 
-				if (subop == 5) {
-					_wcomfy99MixedHostFourthWord = scriptReadWord(pc);
+				if (subop == SO_HOST_MEDIA_START_RECORDING_4_ARGS) {
+					_v3HostMediaRecordingArg3 = scriptReadStringIndex(pc);
 					pc += 2;
 				}
 
@@ -816,42 +980,47 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x46:
-	case 0x47:
-		if (!_usesWcomfy99ScriptOps)
+	case O_ANIMATION_AUDIO_CONTROL:
+	case O_PRELOAD_SPRITE_CONV_RANGE:
+		if (_engineVersion != 3)
 			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
 	{
 		switch (opcode) {
-		case 0x46: {
+		case O_ANIMATION_AUDIO_CONTROL: {
 			byte subop = scriptReadByte(pc++);
-			if (subop < 1 || subop > 8)
+			if (subop < SO_ANIMATION_INDEX_OFFSET || subop > SO_MIXER_VOLUME)
 				error("Unknown script opcode 0x46 subopcode 0x%02X at script PC 0x%08X", subop, pc - 2);
 
-			uint16 argument = scriptReadWord(pc);
-			pc += 2;
-
 			switch (subop) {
-			case 1:
-				_wcomfy99HostWordA = argument;
+			case SO_ANIMATION_INDEX_OFFSET:
+				_v3AnimIndexOffset = scriptReadStringIndex(pc);
+				pc += 2;
+				break;
+			case SO_WAVE_BALANCE:
+				setWaveBalancePercent(scriptReadStringIndex(pc));
+				pc += 2;
 				break;
-			case 2:
-				wcomfy99SetWaveBalancePercent(argument);
+			case SO_ANIMATION_ACTOR_SCENE:
+				_v3AnimActorSceneHandle = scriptReadWord(pc);
+				pc += 2;
 				break;
-			case 3:
-				_wcomfy99HostWordB = argument;
+			case SO_WAVE_LEFT:
+				setWaveLeftPercent(scriptReadStringIndex(pc));
+				pc += 2;
 				break;
-			case 4:
-				wcomfy99SetWaveLeftPercent(argument);
+			case SO_WAVE_RIGHT:
+				setWaveRightPercent(scriptReadStringIndex(pc));
+				pc += 2;
 				break;
-			case 5:
-				wcomfy99SetWaveRightPercent(argument);
+			case SO_ANIMATION_AUDIO_NOOP:
 				break;
-			case 6:
-			case 7:
-				wcomfy99SetHostMediaRangePercent(argument);
+			case SO_HOST_MEDIA_RANGE:
+				setMediaRangePercent(scriptReadStringIndex(pc));
+				pc += 2;
 				break;
-			case 8:
-				wcomfy99SetMixerVolumePercent(argument);
+			case SO_MIXER_VOLUME:
+				setMixerVolumePercent(scriptReadStringIndex(pc));
+				pc += 2;
 				break;
 			default:
 				break;
@@ -859,13 +1028,15 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 			break;
 		}
-		case 0x47:
-			_wcomfy99RangeHostStart = scriptReadWord(pc);
-			_wcomfy99RangeHostEnd = scriptReadWord(pc + 2);
-			_wcomfy99RangeHostCount = _wcomfy99RangeHostEnd >= _wcomfy99RangeHostStart ?
-				_wcomfy99RangeHostEnd - _wcomfy99RangeHostStart + 1 : 0;
+		case O_PRELOAD_SPRITE_CONV_RANGE: {
+			uint16 first = scriptReadStringIndex(pc);
+			uint16 last = scriptReadStringIndex(pc + 2);
 			pc += 4;
+			for (uint16 spriteId = first; (int16)spriteId <= (int16)last; spriteId++)
+				spriteGetConvPtr((int16)spriteId);
+
 			break;
+		}
 		default:
 			break;
 		}
@@ -873,7 +1044,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x50: {
+	case O_STRING_TABLE_COMPARE_SET_KEY: {
 		uint16 lhsIndex = scriptReadWord(pc);
 		uint16 rhsIndex = scriptReadWord(pc + 2);
 		uint16 key = scriptReadWord(pc + 4);
@@ -890,10 +1061,10 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x51:
-	case 0x52:
-	case 0x70:
-	case 0x71: {
+	case O_ACTOR_MOVE_BY:
+	case O_ACTOR_MOVE_TO:
+	case O_ACTOR_MOVE_BY_V2:
+	case O_ACTOR_MOVE_TO_V2: {
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		pc += 2;
 		int16 x = scriptReadStringIndex(pc);
@@ -909,10 +1080,10 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		if (!target)
 			error("Script opcode 0x%02X resolved an invalid actor", opcode);
 
-		if (!duration && (opcode == 0x51 || opcode == 0x52))
+		if (!duration && (opcode == O_ACTOR_MOVE_BY || opcode == O_ACTOR_MOVE_TO))
 			error("Script opcode 0x%02X has a zero movement duration", opcode);
 
-		bool moveTo = opcode == 0x52 || opcode == 0x71;
+		bool moveTo = opcode == O_ACTOR_MOVE_TO || opcode == O_ACTOR_MOVE_TO_V2;
 		if ((moveTo && x == (int16)0xF830) || (!moveTo && x == (int16)0x8AD0)) {
 			Actor *other = actorResolve((uint16)y, _currentActor);
 			if (!other)
@@ -942,7 +1113,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			dy = y == (int16)0xFC18 ? 0 : dy - target->yFixed;
 		}
 
-		if (opcode == 0x51 || opcode == 0x52 || (moveTo && duration < 0)) {
+		if (opcode == O_ACTOR_MOVE_BY || opcode == O_ACTOR_MOVE_TO || (moveTo && duration < 0)) {
 			if (duration < 0)
 				duration = -duration;
 
@@ -962,23 +1133,25 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return blocking && target == &actor ? kScriptYield : kScriptContinue;
 	}
 
-	case 0x48:
-	case 0x49:
-		if (!_usesWcomfy99ScriptOps)
+	case O_JUMP_IF_KEY_CLEAR_V3:
+	case O_JUMP_IF_KEY_SET_V3:
+		if (_engineVersion != 3)
 			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
 	{
 		uint16 key = scriptReadWord(pc);
 		uint32 targetPc = scriptReadDword(pc + 2);
-		bool jumpWhenSet = opcode == 0x49;
+		bool jumpWhenSet = opcode == O_JUMP_IF_KEY_SET_V3;
 		pc = keyBitTest(key) == jumpWhenSet ? targetPc : pc + 6;
 		return kScriptContinue;
 	}
 
-	case 0x53: {
+	case O_ACTOR_SET_FRAME_AND_STOP: {
 		uint16 actorSlot = scriptReadWord(pc);
 		Actor *target = actorResolve(actorSlot, _currentActor);
 		uint16 frame = scriptReadStringIndex(pc + 2);
+
 		pc += 4;
+
 		if (!target)
 			error("Script opcode 0x53 resolved an invalid actor");
 
@@ -988,7 +1161,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x54: {
+	case O_COPY_INLINE_BLOCK: {
 		if (_engineVersion < 2)
 			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
 
@@ -1007,7 +1180,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x55: {
+	case O_COPY_PALETTE_ENTRY: {
 		if (_engineVersion < 2)
 			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
 
@@ -1022,10 +1195,10 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x6E:
+	case O_WAIT:
 		return kScriptYield;
 
-	case 0x6F: {
+	case O_MIDI_ADD_EVENT: {
 		uint16 id = scriptReadWord(pc);
 		int16 delta = scriptReadStringIndex(pc + 2);
 		pc += 4;
@@ -1033,7 +1206,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x72: {
+	case O_ACTOR_WAIT_TICKS: {
 		uint16 requested = scriptReadStringIndex(pc);
 		pc += 2;
 		uint16 balance = actor.waitAccum;
@@ -1050,12 +1223,12 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptYield;
 	}
 
-	case 0x73: {
+	case O_WAVE_OUTPUT_RESET: {
 		_waveOutputActive = false;
 		return kScriptContinue;
 	}
 
-	case 0x74: {
+	case O_WAIT_KEY_CLEAR: {
 		uint16 key = scriptReadWord(pc);
 		if (keyBitTest(key)) {
 			pc--;
@@ -1066,26 +1239,42 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x75: {
+	case O_CONDITIONAL_SET_KEY: {
 		byte kind = scriptReadByte(pc++);
 		uint16 key = scriptReadWord(pc);
 		pc += 2;
 		bool condition = false;
-		if (_usesWcomfy99ScriptOps) {
+		if (_engineVersion == 3) {
 			uint16 argument = scriptReadWord(pc);
 			pc += 2;
 			switch (kind) {
-			case 1:
+			case SO_CONDITION_SCENE_EXISTS:
 				condition = sceneGetHandle(argument) != 0;
 				break;
-			case 2:
+			case SO_CONDITION_INPUT_MODE:
 				condition = _inputDeviceMode == 1;
 				break;
-			case 14:
+			case SO_CONDITION_MOUSE_LEFT_BUTTON:
+			case SO_CONDITION_MOUSE_LEFT_BUTTON_ALT:
+				condition = _mouseLeftButton;
+				break;
+			case SO_CONDITION_MOUSE_RIGHT_BUTTON:
+			case SO_CONDITION_MOUSE_RIGHT_BUTTON_ALT:
+				condition = _mouseRightButton;
+				break;
+			case SO_CONDITION_ACTOR_HIT_TEST:
+			case SO_CONDITION_ACTOR_BLIT_HIT_TEST: {
+				Actor *target = actorResolve(argument, _currentActor);
+				condition = target && actorTestMouseHit(*target, kind == SO_CONDITION_ACTOR_BLIT_HIT_TEST);
+				break;
+			}
+			case SO_CONDITION_FALSE:
+				break;
+			case SO_CONDITION_SYSTEM_FEATURE:
 				if (argument <= 4) {
 					condition = _inputDeviceMode == argument;
 				} else if (argument == 20) {
-					condition = _wcomfy99RecordHostEnabled;
+					condition = _v3HostMediaRecording;
 				} else if (argument == 30) {
 					Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(Common::Path("comfy.htm"), true));
 					condition = (bool)stream;
@@ -1096,7 +1285,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			}
 		} else {
 			switch (kind) {
-			case 1: {
+			case SO_CONDITION_SCENE_EXISTS: {
 				uint16 scene = scriptReadWord(pc);
 				condition = sceneGetHandle(scene) != 0;
 				pc += 2;
@@ -1115,11 +1304,11 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x76:
-	case 0x77: {
+	case O_STRING_TABLE_SET:
+	case O_STRING_TABLE_SET_OFFSET: {
 		uint16 index = scriptReadWord(pc);
 		pc += 2;
-		if (opcode == 0x77) {
+		if (opcode == O_STRING_TABLE_SET_OFFSET) {
 			if (_stringTable.size() <= 1)
 				error("Script opcode 0x77 requires string table entry 1");
 
@@ -1134,7 +1323,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case 0x7F:
+	case O_NOP:
 		return kScriptContinue;
 
 	default:
diff --git a/engines/comfy/sound.cpp b/engines/comfy/sound.cpp
index 1620fc54ab3..01c3de9c9f1 100644
--- a/engines/comfy/sound.cpp
+++ b/engines/comfy/sound.cpp
@@ -295,13 +295,13 @@ private:
 	}
 
 	static uint32 calcSampleRate(byte sample) {
-		uint32 denominator = 0x100 - sample;
-		uint32 rate = denominator ? 0x0F4240 / denominator : 0x2B11;
-		if (rate > 0x2710 && rate < 0x2EE0)
-			return 0x2B11;
+		uint32 denominator = 256 - sample;
+		uint32 rate = denominator ? 1000000 / denominator : 11025;
+		if (rate > 0x2710 && rate < 12000)
+			return 11025;
 
-		if (rate > 0x4E20 && rate < 0x5DC0)
-			return 0x5622;
+		if (rate > 20000 && rate < 24000)
+			return 22050;
 
 		return rate;
 	}
@@ -309,9 +309,9 @@ private:
 	void setSample(byte sample) {
 		_sample = sample;
 		_sampleRate = calcSampleRate(sample);
-		if (_sampleRate == 0x2B11)
+		if (_sampleRate == 11025)
 			_sample = 0xA5;
-		else if (_sampleRate == 0x5622)
+		else if (_sampleRate == 22050)
 			_sample = 0xD3;
 	}
 
@@ -613,7 +613,7 @@ private:
 	uint32 _eventRemaining = 0;
 	uint32 _fillRemaining = 0;
 	uint32 _loopPosition = 0;
-	uint32 _sampleRate = 0x2B11;
+	uint32 _sampleRate = 11025;
 	int16 _loopCount = 0;
 	byte _sample = 0xA5;
 	byte _bitOffset = 0;
@@ -629,17 +629,17 @@ private:
 	BufferState _bufferStates[2];
 };
 
-void ComfyEngine::wcomfy99SetWaveBalancePercent(uint16 value) {
+void ComfyEngine::setWaveBalancePercent(uint16 value) {
 	if ((int16)value < 0)
 		value = 0;
 	else if (value > 100)
 		value = 100;
 
-	_wcomfy99VocState0 = (byte)value;
-	_wcomfy99WaveVolumePercent = value;
+	_v3SceneWaveBalancePercent = (byte)value;
+	_v3WaveBalancePercent = value;
 }
 
-void ComfyEngine::wcomfy99SetWaveLeftPercent(uint16 value) {
+void ComfyEngine::setWaveLeftPercent(uint16 value) {
 	if (value == 0x00FF)
 		return;
 
@@ -648,11 +648,11 @@ void ComfyEngine::wcomfy99SetWaveLeftPercent(uint16 value) {
 	else if (value > 100)
 		value = 100;
 
-	_wcomfy99VocState2 = (byte)value;
-	_wcomfy99WaveLeftPercent = value;
+	_v3SceneWaveLeftPercent = (byte)value;
+	_v3WaveLeftPercent = value;
 }
 
-void ComfyEngine::wcomfy99SetWaveRightPercent(uint16 value) {
+void ComfyEngine::setWaveRightPercent(uint16 value) {
 	if (value == 0x00FF)
 		return;
 
@@ -661,11 +661,11 @@ void ComfyEngine::wcomfy99SetWaveRightPercent(uint16 value) {
 	else if (value > 100)
 		value = 100;
 
-	_wcomfy99VocState3 = (byte)value;
-	_wcomfy99WaveRightPercent = value;
+	_v3SceneWaveRightPercent = (byte)value;
+	_v3WaveRightPercent = value;
 }
 
-void ComfyEngine::wcomfy99SetMixerVolumePercent(uint16 value) {
+void ComfyEngine::setMixerVolumePercent(uint16 value) {
 	if (value == 0x00FF)
 		return;
 
@@ -674,53 +674,53 @@ void ComfyEngine::wcomfy99SetMixerVolumePercent(uint16 value) {
 	else if (value > 100)
 		value = 100;
 
-	_wcomfy99VocState6 = (byte)value;
-	_wcomfy99MixerVolumePercent = value;
+	_v3SceneMixerVolumePercent = (byte)value;
+	_v3MixerVolumePercent = value;
 }
 
-void ComfyEngine::wcomfy99SetHostMediaRangePercent(uint16 value) {
+void ComfyEngine::setMediaRangePercent(uint16 value) {
 	if ((int16)value < 0)
 		value = 0;
 	else if (value > 100)
 		value = 100;
 
-	_wcomfy99MixerAltPercent = value;
+	_v3MixerAltPercent = value;
 }
 
-void ComfyEngine::wcomfy99SetHostMediaMode(byte mode) {
+void ComfyEngine::setMediaMode(byte mode) {
 	if (mode == 1 || mode == 3) {
-		_wcomfy99VocState1 = 1;
-		if (!_wcomfy99HostMediaValueAvailable) {
-			_wcomfy99HostMediaValue = 0;
-			_wcomfy99HostMediaValueAvailable = true;
+		_v3SceneHostMediaModeEnabled = 1;
+		if (!_v3HostMediaValueAvailable) {
+			_v3HostMediaValue = 0;
+			_v3HostMediaValueAvailable = true;
 		}
 	} else if (mode == 2) {
-		_wcomfy99VocState1 = 0;
-		_wcomfy99HostMediaValue = 0;
-		_wcomfy99HostMediaValueAvailable = false;
+		_v3SceneHostMediaModeEnabled = 0;
+		_v3HostMediaValue = 0;
+		_v3HostMediaValueAvailable = false;
 	}
 }
 
-void ComfyEngine::wcomfy99RestoreHostStateAfterSceneStart() {
-	wcomfy99SetWaveBalancePercent(_wcomfy99VocState0);
-	wcomfy99SetWaveLeftPercent(_wcomfy99VocState2);
-	wcomfy99SetWaveRightPercent(_wcomfy99VocState3);
-	wcomfy99SetMixerVolumePercent(_wcomfy99VocState6);
-	if (_wcomfy99VocState1) {
-		wcomfy99SetHostMediaMode(2);
-		wcomfy99SetHostMediaMode(1);
+void ComfyEngine::restoreWaveStateAfterSceneStart() {
+	setWaveBalancePercent(_v3SceneWaveBalancePercent);
+	setWaveLeftPercent(_v3SceneWaveLeftPercent);
+	setWaveRightPercent(_v3SceneWaveRightPercent);
+	setMixerVolumePercent(_v3SceneMixerVolumePercent);
+	if (_v3SceneHostMediaModeEnabled) {
+		setMediaMode(2);
+		setMediaMode(1);
 	} else {
-		wcomfy99SetHostMediaMode(2);
+		setMediaMode(2);
 	}
 }
 
 bool ComfyEngine::soundOpenVocFile() {
-	soundBufFree(_vocFile);
+	objFileClose(_vocFile);
 	uint32 maximumBytes = 0x40000;
-	if (sysGetExtMemKB() < 0x0FA0)
+	if (sysGetExtMemKB() < 4000)
 		maximumBytes /= 2;
 
-	_vocFile = objFileLoadSoundData(Common::Path("VOCFILE.DAT"), 0x8000, maximumBytes);
+	_vocFile = objFileOpen(Common::Path("VOCFILE.DAT"), 0x8000, maximumBytes);
 	if (!_vocFile)
 		return false;
 
@@ -728,7 +728,7 @@ bool ComfyEngine::soundOpenVocFile() {
 	memset(header, 0, sizeof(header));
 	objFileReadFieldCore(header, 0, sizeof(header), _vocFile);
 	if (header[0] != 'C' || (header[1] != 'V' && header[1] != 'W')) {
-		soundBufFree(_vocFile);
+		objFileClose(_vocFile);
 		return false;
 	}
 
@@ -750,16 +750,17 @@ bool ComfyEngine::soundInit() {
 	_soundVocBlockCount = 0;
 	_soundVocCounterSnapshot = 0;
 	_soundVocTimingDelta = 0;
+
 	for (uint i = 0; i < COMFY_VOC_QUEUE_CAPACITY; i++) {
 		_vocQueue[i] = VocQueueEntry();
-		_vocQueue1999[i] = VocQueueEntry1999();
+		_vocQueueV3[i] = VocQueueEntryV3();
 	}
 
-	_wcomfy99VocState0 = 0;
-	_wcomfy99VocState1 = 0;
-	_wcomfy99VocState2 = 0;
-	_wcomfy99VocState3 = 0;
-	_wcomfy99VocState6 = 0;
+	_v3SceneWaveBalancePercent = 0;
+	_v3SceneHostMediaModeEnabled = 0;
+	_v3SceneWaveLeftPercent = 0;
+	_v3SceneWaveRightPercent = 0;
+	_v3SceneMixerVolumePercent = 0;
 	return true;
 }
 
@@ -769,7 +770,7 @@ void ComfyEngine::soundShutdown() {
 	delete _soundDecoderState;
 	_soundDecoderState = nullptr;
 	_soundCues.clear();
-	soundBufFree(_vocFile);
+	objFileClose(_vocFile);
 	_soundEntryCount = 0;
 	_soundNextCue = 0;
 	_soundPaused = false;
@@ -782,7 +783,7 @@ void ComfyEngine::soundShutdown() {
 		_midiPlyrDriver->setIncreaseVocCounter(0);
 }
 
-void ComfyEngine::soundHdrReadFromXms(byte *destination, uint16 index, uint16 size) {
+void ComfyEngine::soundHeaderReadFromXms(byte *destination, uint16 index, uint16 size) {
 	objHdrReadFromXms(destination, _headerXmsSoundHeadersBase, size, index);
 }
 
@@ -799,7 +800,7 @@ void ComfyEngine::soundUpdateVocTiming() {
 	_soundVocBlockCount += blockNo;
 	timeFrac -= _soundVocCounterSnapshot;
 	_midiPlyrDriver->vocSrResetBlockNo();
-	uint32 sampleRate = _soundSampleRate ? _soundSampleRate : 0x2B11;
+	uint32 sampleRate = _soundSampleRate ? _soundSampleRate : 11025;
 	uint32 expected = ((uint32)_soundVocBlockCount * 0x186A00) / sampleRate;
 	_soundVocTimingDelta = (int16)((uint16)expected - (uint16)timeFrac);
 }
@@ -825,7 +826,7 @@ void ComfyEngine::soundServiceWaveBuffers() {
 bool ComfyEngine::soundLoadEntry(uint16 index) {
 	byte header[8];
 	memset(header, 0, sizeof(header));
-	soundHdrReadFromXms(header, index, sizeof(header));
+	soundHeaderReadFromXms(header, index, sizeof(header));
 	uint32 size = READ_LE_UINT32(header);
 	uint32 offset = READ_LE_UINT32(header + 4);
 	return _vocFile && offset <= _vocFile->fileSize && size <= _vocFile->fileSize - offset;
@@ -900,7 +901,7 @@ bool ComfyEngine::soundPrepareDecoderState(uint16 index) {
 	} else {
 		byte header[8];
 		memset(header, 0, sizeof(header));
-		soundHdrReadFromXms(header, index, sizeof(header));
+		soundHeaderReadFromXms(header, index, sizeof(header));
 		dataSize = READ_LE_UINT32(header);
 		dataOffset = READ_LE_UINT32(header + 4);
 		if (!_vocFile || dataOffset > _vocFile->fileSize || dataSize > _vocFile->fileSize - dataOffset)
@@ -1043,11 +1044,10 @@ void ComfyEngine::soundUnpackState(byte *state) {
 }
 
 void ComfyEngine::soundPlayEntry(uint16 index) {
-	debug(5, "COMFY VOC: play id=%u", index);
 	_mixer->stopHandle(_soundHandle);
 	_soundQueueStream = nullptr;
+
 	if (!soundPrepareDecoderState(index)) {
-		debug(5, "COMFY VOC: play id=%u decode failed", index);
 		_soundEventSubIndex = 0;
 		return;
 	}
@@ -1065,7 +1065,6 @@ void ComfyEngine::soundPlayEntry(uint16 index) {
 		free(buffers[1]);
 		delete _soundDecoderState;
 		_soundDecoderState = nullptr;
-		debug(5, "COMFY VOC: play id=%u initial buffer fill failed", index);
 		_soundEventSubIndex = 0;
 		return;
 	}
@@ -1077,7 +1076,6 @@ void ComfyEngine::soundPlayEntry(uint16 index) {
 		free(buffers[1]);
 		delete _soundDecoderState;
 		_soundDecoderState = nullptr;
-		debug(5, "COMFY VOC: play id=%u queue creation failed", index);
 		_soundEventSubIndex = 0;
 		return;
 	}
@@ -1087,9 +1085,7 @@ void ComfyEngine::soundPlayEntry(uint16 index) {
 
 	_mixer->playStream(Audio::Mixer::kSpeechSoundType, &_soundHandle, _soundQueueStream, -1,
 		Audio::Mixer::kMaxChannelVolume, 0, DisposeAfterUse::YES);
-	debug(5, "COMFY VOC: play id=%u submitted active=%u rate=%u cues=%u",
-		index, _mixer->isSoundHandleActive(_soundHandle) ? 1 : 0,
-		_soundSampleRate, (uint)_soundCues.size());
+
 	_soundPaused = false;
 	_soundWaveBufferIndex = 0;
 	_soundEventSubIndex = 0xFFFF;
@@ -1109,7 +1105,6 @@ void ComfyEngine::soundAdvanceTick() {
 	if (!_mixer->isSoundHandleActive(_soundHandle)) {
 		_soundQueueStream = nullptr;
 		if (_soundDecoderState && _soundEventSubIndex != 0) {
-			debug(5, "COMFY VOC: mixer became inactive; marking entry complete");
 			_soundEventSubIndex = 0;
 		}
 
@@ -1126,9 +1121,6 @@ void ComfyEngine::soundAdvanceTick() {
 			(_soundCues[_soundNextCue].value == 1 || _soundCues[_soundNextCue].value == 2)) {
 		phaseCueSeen = true;
 		_soundEventSubIndex = _soundCues[_soundNextCue].value;
-		debug(5, "COMFY VOC: cue=%u threshold=%u counter=%u index=%u/%u",
-			_soundEventSubIndex, _soundCues[_soundNextCue].counterThreshold, counter,
-			_soundNextCue, (uint)_soundCues.size());
 		_soundNextCue++;
 	}
 
@@ -1137,10 +1129,8 @@ void ComfyEngine::soundAdvanceTick() {
 		return;
 
 	_soundEventSubIndex = _soundCues[_soundNextCue].value;
-	debug(5, "COMFY VOC: cue=%u threshold=%u counter=%u index=%u/%u",
-		_soundEventSubIndex, _soundCues[_soundNextCue].counterThreshold, counter,
-		_soundNextCue, (uint)_soundCues.size());
 	_soundNextCue++;
+
 	if (!_soundEventSubIndex) {
 		_mixer->stopHandle(_soundHandle);
 		_soundQueueStream = nullptr;
diff --git a/engines/comfy/timer.cpp b/engines/comfy/timer.cpp
index 14a6bba6581..1683d75bedc 100644
--- a/engines/comfy/timer.cpp
+++ b/engines/comfy/timer.cpp
@@ -23,7 +23,40 @@
 
 namespace Comfy {
 
+void ComfyEngine::timerInit() {
+	if (_timerInitialized)
+		return;
+
+	_timerPitPhase = 0;
+	_timerLastMillis = g_system->getMillis();
+	_timerInitialized = true;
+}
+
+void ComfyEngine::timerShutdown() {
+	if (!_timerInitialized)
+		return;
+
+	_timerInitialized = false;
+}
+
 uint16 ComfyEngine::timerTick() {
+	uint32 now = g_system->getMillis();
+	uint32 elapsedMillis = now - _timerLastMillis;
+
+	_timerLastMillis = now;
+	_timerPitPhase += (uint64)elapsedMillis * 1000 * COMFY_PIT_INPUT_FREQUENCY;
+
+	uint64 pitPeriod = (uint64)COMFY_PIT_TIMER_DIVISOR * 1000000;
+	uint32 callbacks = (uint32)(_timerPitPhase / pitPeriod);
+	_timerPitPhase %= pitPeriod;
+
+	while (callbacks--) {
+		if (shouldQuit())
+			return 0;
+
+		soundAdvanceTick();
+	}
+
 	_timer2 = _timer1;
 	_timer1 = _timer0;
 	_timer0 = _timerCurrent;
diff --git a/engines/comfy/video.cpp b/engines/comfy/video.cpp
index 6f03642bc52..84bb9c6eec7 100644
--- a/engines/comfy/video.cpp
+++ b/engines/comfy/video.cpp
@@ -48,7 +48,7 @@ void ComfyEngine::videoInit() {
 	_backgroundFrame = 0;
 	_dirtyRectCount = 0;
 	_renderDirtyCount = 0;
-	videoSetResolution();
+	renderAddFullFrameDirtyRect();
 	videoPresentFrame();
 	_videoInitialized = true;
 }
@@ -71,17 +71,17 @@ void ComfyEngine::videoShutdown(byte restorePalette) {
 	_videoInitialized = false;
 }
 
-void ComfyEngine::videoSetResolution() {
+void ComfyEngine::renderAddFullFrameDirtyRect() {
 	ComfyRect record;
 	record.left = 0;
 	record.top = 0;
 	record.right = _logicalScreenWidth;
 	record.bottom = _logicalScreenHeight;
 	record.area = _engineVersion == 1 ? (uint16)framebufferBytes() : framebufferBytes();
-	videoFindBestMode(record);
+	renderAddDirtyRect(record);
 }
 
-void ComfyEngine::renderSetDirty() {
+void ComfyEngine::renderRequestFullFrameInvalidation() {
 	_renderDirtyCount = 1;
 }
 
@@ -89,13 +89,13 @@ void ComfyEngine::renderFlushDirty() {
 	_dirtyRectCount = 0;
 	if (_renderDirtyCount) {
 		_renderDirtyCount--;
-		videoSetResolution();
+		renderAddFullFrameDirtyRect();
 	}
 }
 
 void ComfyEngine::renderInvalidateFullFrame() {
 	renderFlushDirty();
-	videoSetResolution();
+	renderAddFullFrameDirtyRect();
 }
 
 void ComfyEngine::renderAddDirtyRectMerged(ComfyRect record) {
@@ -114,7 +114,7 @@ void ComfyEngine::renderAddDirtyRectMerged(ComfyRect record) {
 
 	if (_dirtyRectCount >= COMFY_DIRTY_RECT_CAPACITY) {
 		renderFlushDirty();
-		videoSetResolution();
+		renderAddFullFrameDirtyRect();
 		return;
 	}
 
@@ -203,7 +203,7 @@ void ComfyEngine::renderAddDirtyRectMerged(ComfyRect record) {
 	_dirtyRectCount++;
 }
 
-void ComfyEngine::videoFindBestMode(ComfyRect record) {
+void ComfyEngine::renderAddDirtyRect(ComfyRect record) {
 	if (_engineVersion >= 2) {
 		renderAddDirtyRectMerged(record);
 		return;
@@ -219,7 +219,7 @@ void ComfyEngine::videoFindBestMode(ComfyRect record) {
 
 	if (_dirtyRectCount >= COMFY_DIRTY_RECT_CAPACITY_V1) {
 		renderFlushDirty();
-		videoSetResolution();
+		renderAddFullFrameDirtyRect();
 		return;
 	}
 


Commit: d0f86d329830e6399a24f2c01c462975d0c0d355
    https://github.com/scummvm/scummvm/commit/d0f86d329830e6399a24f2c01c462975d0c0d355
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Another clean-up pass

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/anim_file.cpp
    engines/comfy/comfy.h
    engines/comfy/debug.cpp
    engines/comfy/expr.cpp
    engines/comfy/game.cpp
    engines/comfy/input.cpp
    engines/comfy/memory.cpp
    engines/comfy/midi.cpp
    engines/comfy/midiplyr/midiplyr.cpp
    engines/comfy/object_file.cpp
    engines/comfy/palette.cpp
    engines/comfy/scene.cpp
    engines/comfy/script.cpp
    engines/comfy/script_vm.cpp
    engines/comfy/sound.cpp
    engines/comfy/timer.cpp
    engines/comfy/video.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index bd102dfd43c..55caa6d2d0e 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -33,14 +33,15 @@ bool ComfyEngine::spriteDecompressTile(SpriteResource &sprite, const byte *sourc
 		return false;
 
 	// The original temporarily writes a zero sentinel at source[dataSize].
-	Common::Array<byte> sourceWithSentinel;
-	sourceWithSentinel.resize(sourceSize + 1);
-	memcpy(&sourceWithSentinel[0], source, sourceSize);
-	sourceWithSentinel[sourceSize] = 0;
-	source = &sourceWithSentinel[0];
+	Common::Array<byte> sourceBuf;
+	sourceBuf.resize(sourceSize + 1);
+	memcpy(&sourceBuf[0], source, sourceSize);
+	sourceBuf[sourceSize] = 0;
+	source = &sourceBuf[0];
 	uint32 sourceEnd = sourceSize + 1;
 
 	sprite.pixels.resize(outputSize);
+
 	uint32 sourcePos = 0;
 	uint32 outputPos = 0;
 	uint16 totalOutput = 0;
@@ -65,11 +66,13 @@ bool ComfyEngine::spriteDecompressTile(SpriteResource &sprite, const byte *sourc
 				byte op = sourcePos < sourceEnd ? source[sourcePos++] : 0;
 				if (op & 0x40) {
 					skipCount = op - 0x40;
+
 					while (sourcePos < sourceEnd && (source[sourcePos] & 0x40))
 						skipCount += source[sourcePos++] - 0x40;
 				} else if (op & 0x80) {
 					fillCount = op - 0x80;
 					fillValue = sourcePos < sourceEnd ? source[sourcePos++] : 0;
+
 					while (sourcePos < sourceEnd && (source[sourcePos] & 0xC0) == 0xC0)
 						fillCount += source[sourcePos++] - 0xC0;
 				} else {
@@ -170,6 +173,7 @@ void ComfyEngine::objHdrReadFromXms(byte *destination, uint32 base, uint16 size,
 	move.sourceHandle = _xmsHeaderHandle;
 	move.sourceOffset = base + (uint32)size * row;
 	move.destinationMemory = source;
+
 	if (xmsTransfer(move) < 0) {
 		free(source);
 		error("Headers move (XMS->memory)");
@@ -191,6 +195,7 @@ void ComfyEngine::frameLoaderLoadFrameHeader(SpriteObjectHeader &destination, ui
 	byte raw[0x11];
 	memset(raw, 0, sizeof(raw));
 	objHdrReadFromXms(raw, _headerXmsObjectTableBase, sizeof(raw), index);
+
 	destination.fileOffset = READ_LE_UINT32(raw);
 	destination.dataSize = READ_LE_UINT16(raw + 0x04);
 	destination.width = READ_LE_UINT16(raw + 0x06);
@@ -199,6 +204,7 @@ void ComfyEngine::frameLoaderLoadFrameHeader(SpriteObjectHeader &destination, ui
 	destination.hotspotY = (int16)READ_LE_UINT16(raw + 0x0C);
 	destination.reserved = raw[0x0E];
 	destination.tiledSize = READ_LE_UINT16(raw + 0x0F);
+
 	if (_engineVersion == 3)
 		destination.dataSize = frameLoaderGetFrameDataSize(destination);
 
@@ -243,10 +249,11 @@ void ComfyEngine::scenePoolReserveSlot(uint32 size) {
 			if (tailFree > size)
 				return;
 
-			if (!_scenePoolEvictCursor)
+			if (!_scenePoolEvictCursor) {
 				scenePoolEvict();
-			else
+			} else {
 				_scenePoolCursor = 0;
+			}
 		} else {
 			uint32 gapFree = _scenePoolEvictCursor - _scenePoolCursor;
 			if (gapFree > size)
@@ -282,14 +289,19 @@ void ComfyEngine::spriteCache(int16 spriteId) {
 		byte *entryData = &_scenePoolData[_scenePoolCursor];
 		WRITE_LE_UINT16(entryData, (uint16)spriteId);
 		WRITE_LE_UINT16(entryData + 2, slotSize);
+
 		memcpy(entryData + 0x0C, source, size);
+
 		_frameSpriteResource.id = frameId;
 		_frameSpriteResource.header = SpriteObjectHeader();
 		_frameSpriteResource.header.dataSize = size;
 		_frameSpriteResource.header.tiledSize = size;
 		_frameSpriteResource.pixels.resize(size);
+
 		memcpy(&_frameSpriteResource.pixels[0], entryData + 0x0C, size);
+
 		_frameSpriteResource.loaded = true;
+
 		if (frameId < _frameCacheEntries.size()) {
 			SpriteCacheEntry &entry = _frameCacheEntries[frameId];
 			entry.poolOffset = _scenePoolCursor;
@@ -321,6 +333,7 @@ void ComfyEngine::spriteCache(int16 spriteId) {
 	byte *source = _engineVersion == 3 ?
 		frameLoaderReadFrameData(header.fileOffset, header.dataSize, _picFile) :
 		objFileReadTiled(header.fileOffset, header.dataSize, _picFile);
+
 	if (!source)
 		return;
 
@@ -338,17 +351,21 @@ void ComfyEngine::spriteCache(int16 spriteId) {
 		return;
 
 	byte *entryData = &_scenePoolData[_scenePoolCursor];
+
 	WRITE_LE_UINT16(entryData, (uint16)spriteId);
 	WRITE_LE_UINT16(entryData + 2, slotSize);
 	WRITE_LE_UINT16(entryData + 4, header.width);
 	WRITE_LE_UINT16(entryData + 6, header.height);
 	WRITE_LE_UINT16(entryData + 8, (uint16)header.hotspotX);
 	WRITE_LE_UINT16(entryData + 0x0A, (uint16)header.hotspotY);
+
 	memcpy(entryData + 0x0C, &sprite.pixels[0], sprite.pixels.size());
+
 	SpriteCacheEntry &entry = _objectCacheEntries[spriteId];
 	entry.poolOffset = _scenePoolCursor;
 	entry.slotSize = slotSize;
 	_scenePoolCursor += slotSize;
+
 	if (_scenePoolCursor < _scenePoolData.size())
 		WRITE_LE_UINT16(&_scenePoolData[_scenePoolCursor], 0x8000);
 
@@ -361,6 +378,7 @@ ComfyEngine::SpriteResource *ComfyEngine::spriteLookup(uint16 spriteId, int16 x,
 
 	SpriteResource &sprite = _spriteResources[spriteId];
 	SpriteCacheEntry *entry = spriteId < _objectCacheEntries.size() ? &_objectCacheEntries[spriteId] : nullptr;
+
 	if (entry && entry->slotSize == 0xFFFF) {
 		SpriteObjectHeader header;
 		frameLoaderLoadFrameHeader(header, spriteId);
@@ -378,10 +396,12 @@ ComfyEngine::SpriteResource *ComfyEngine::spriteLookup(uint16 spriteId, int16 x,
 	if (entry && entry->slotSize == 0xFFFF && !fullscreen && offscreen) {
 		_objFileOffset = _spriteLastHeader.fileOffset;
 		_objFileStride = _spriteLastHeader.tiledSize;
-		if (_engineVersion == 3)
+
+		if (_engineVersion == 3) {
 			frameLoaderReadFrameData(sprite.header.fileOffset, sprite.header.dataSize, _picFile);
-		else
+		} else {
 			objFileReadTiled(sprite.header.fileOffset, sprite.header.dataSize, _picFile);
+		}
 
 		return nullptr;
 	}
@@ -427,8 +447,7 @@ void ComfyEngine::spriteGetConvPtr(int16 spriteId) {
 	byte *payload = nullptr;
 	uint16 width = 0;
 	if (entry.slotSize != 0xFFFF) {
-		if (entry.poolOffset <= _scenePoolData.size() && entry.slotSize >= 0x0C &&
-				0x0C <= _scenePoolData.size() - entry.poolOffset) {
+		if (entry.poolOffset <= _scenePoolData.size() && entry.slotSize >= 0x0C && 0x0C <= _scenePoolData.size() - entry.poolOffset) {
 			byte *entryData = &_scenePoolData[entry.poolOffset];
 			width = READ_LE_UINT16(entryData + 4);
 			payload = entryData + 0x0C;
@@ -445,8 +464,9 @@ void ComfyEngine::spriteGetConvPtr(int16 spriteId) {
 	if (!payload || width != 0xFFFF)
 		return;
 
-	// The original uploads the sound-cache tile named by the first payload
-	// word to XMS. ScummVM already keeps the complete source resident.
+	// A width of 0xFFFF marks a conversion-cache payload. The original uses
+	// its first word as a tile index and copies the remaining payload to XMS;
+	// we keep this protocol but clearly we won't do an entire XMS reimplementation for this...
 }
 
 void ComfyEngine::spriteBlitRle(byte *destination, const byte *source, uint32 sourceSize) {
@@ -457,9 +477,11 @@ void ComfyEngine::spriteBlitRle(byte *destination, const byte *source, uint32 so
 	uint32 outputPos = 0;
 	uint32 outputSize = framebufferBytes();
 	byte previousFill = 0;
+
 	while (outputPos < outputSize && sourcePos < sourceSize) {
 		byte op = source[sourcePos++];
 		uint32 count = MIN<uint32>(op & 0x3F, outputSize - outputPos);
+
 		if ((op & 0xC0) == 0) {
 			if (sourcePos + count > sourceSize)
 				return;
@@ -489,8 +511,7 @@ void ComfyEngine::backgroundTransitionFrames(uint16 frame, uint16 previousFrame)
 		if (!background)
 			return;
 
-		if (background->header.width == _logicalScreenWidth &&
-				background->header.height == _logicalScreenHeight && !background->pixels.empty()) {
+		if (background->header.width == _logicalScreenWidth && background->header.height == _logicalScreenHeight && !background->pixels.empty()) {
 			spriteBlitRle(&_backgroundFramebuf[0], &background->pixels[0], background->pixels.size());
 		} else {
 			uint16 color = background->pixels.size() > 3 ? background->pixels[3] : 0;
@@ -505,8 +526,7 @@ void ComfyEngine::backgroundTransitionFrames(uint16 frame, uint16 previousFrame)
 	if (!background)
 		return;
 
-	if (background->header.width == _logicalScreenWidth &&
-			background->header.height == _logicalScreenHeight && !background->pixels.empty()) {
+	if (background->header.width == _logicalScreenWidth && background->header.height == _logicalScreenHeight && !background->pixels.empty()) {
 		spriteBlitRle(_framebufPtr, &background->pixels[0], background->pixels.size());
 	} else {
 		uint16 color = background->pixels.size() > 3 ? background->pixels[3] : 0;
@@ -524,6 +544,7 @@ void ComfyEngine::backgroundRestoreDirtyRects() {
 		ComfyRect &rect = _dirtyRects[i];
 		int16 width = rect.right - rect.left;
 		int16 height = rect.bottom - rect.top;
+
 		if (width <= 0 || height <= 0)
 			continue;
 
@@ -555,6 +576,7 @@ void ComfyEngine::spriteBlitClipped(int16 spriteId, int16 x, int16 y) {
 		int16 drawY = y + row;
 		uint32 packetPos = rowPos + 2;
 		int16 drawX = x;
+
 		while (packetPos < rowPos + rowSize) {
 			byte op = sprite.pixels[packetPos++];
 			uint16 count = op & 0x3F;
@@ -593,8 +615,7 @@ bool ComfyEngine::spriteCoversPoint(int16 spriteId, int16 x, int16 y, int16 poin
 		return false;
 
 	SpriteResource &sprite = *loadedSprite;
-	if (pointX < x || pointY < y || pointX >= x + (int16)sprite.header.width ||
-			pointY >= y + (int16)sprite.header.height)
+	if (pointX < x || pointY < y || pointX >= x + (int16)sprite.header.width || pointY >= y + (int16)sprite.header.height)
 		return false;
 
 	if (sprite.header.width == _logicalScreenWidth && sprite.header.height == _logicalScreenHeight)
@@ -609,9 +630,11 @@ bool ComfyEngine::spriteCoversPoint(int16 spriteId, int16 x, int16 y, int16 poin
 		int16 drawY = y + row;
 		uint32 packetPos = rowPos + 2;
 		int16 drawX = x;
+
 		while (packetPos < rowPos + rowSize) {
 			byte op = sprite.pixels[packetPos++];
 			uint16 count = op & 0x3F;
+
 			if (op & 0x80) {
 				if (packetPos >= rowPos + rowSize)
 					return false;
@@ -666,6 +689,7 @@ bool ComfyEngine::actorTestMouseHit(Actor &actor, bool useBlitHit) {
 	int16 y = (int16)(yFixed >> 12);
 	int16 right;
 	int16 bottom;
+
 	if (selector == 0x00FFFFFF) {
 		uint16 width = 0;
 		uint16 height = 0;
@@ -759,8 +783,10 @@ void ComfyEngine::actorFreeSlot(uint16 sceneSlot) {
 	Actor *root = actorGetPtr(0);
 	actor->nextLink = root ? root->nextLink : 0;
 	actor->sceneHandle = 0;
+
 	if (root)
 		root->nextLink = actorIndex;
+
 	_sceneHandles[sceneSlot] = 0;
 }
 
@@ -809,17 +835,19 @@ void ComfyEngine::actorUnlink(uint16 actorIndex) {
 
 	uint16 next = actor->nextLink;
 	uint16 previous = actor->prevLink;
-	if (next)
+	if (next) {
 		actorGetPtr(next)->prevLink = previous;
-	else if (parent->childTail == actorIndex)
+	} else if (parent->childTail == actorIndex) {
 		parent->childTail = previous;
+	}
 
-	if (previous)
+	if (previous) {
 		actorGetPtr(previous)->nextLink = next;
-	else if (parent->siblingHead == actorIndex)
+	} else if (parent->siblingHead == actorIndex) {
 		parent->siblingHead = next;
-	else
+	} else {
 		parent->childHead = next;
+	}
 }
 
 uint16 ComfyEngine::actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible, byte active,
@@ -846,6 +874,7 @@ uint16 ComfyEngine::actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible,
 	actor->waitTarget = 0;
 	actor->waitAccum = 0;
 	actor->dirty = 1;
+
 	if (_videoMode == 2 || _videoMode == 4) {
 		ComfyRect empty;
 		actor->cachedRect = empty;
@@ -856,10 +885,12 @@ uint16 ComfyEngine::actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible,
 	if (parentSlot) {
 		uint16 parentIndex = sceneGetHandle(parentSlot);
 		actor->parent = parentIndex;
-		if (insertAsChild)
+
+		if (insertAsChild) {
 			actorInsertChild(actorIndex, parentIndex);
-		else
+		} else {
 			actorInsertSibling(actorIndex, parentIndex);
+		}
 	} else {
 		actor->parent = 0;
 		actor->nextLink = 0;
@@ -872,10 +903,12 @@ uint16 ComfyEngine::actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible,
 void ComfyEngine::actorSetPc(Actor &actor, uint32 pc) {
 	uint32 previous = actor.callPc;
 	uint32 packed = pc;
+
 	if (previous) {
 		byte entry = _actorPcTable[0] >> 24;
 		_actorPcTable[0] = _actorPcTable[entry];
 		_actorPcTable[entry] = previous;
+
 		if (_sceneActorPcOffset + sizeof(_actorPcTable) <= _sceneMemoryBlock.size()) {
 			WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneActorPcOffset], _actorPcTable[0]);
 			WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneActorPcOffset + entry * 4], _actorPcTable[entry]);
@@ -890,10 +923,12 @@ void ComfyEngine::actorSetPc(Actor &actor, uint32 pc) {
 uint32 ComfyEngine::actorPopPc(Actor &actor) {
 	uint32 packed = actor.callPc;
 	byte entry = packed >> 24;
+
 	if (entry) {
 		actor.callPc = _actorPcTable[entry];
 		_actorPcTable[entry] = _actorPcTable[0];
 		_actorPcTable[0] = (uint32)entry << 24;
+
 		if (_sceneActorPcOffset + sizeof(_actorPcTable) <= _sceneMemoryBlock.size()) {
 			WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneActorPcOffset], _actorPcTable[0]);
 			WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneActorPcOffset + entry * 4], _actorPcTable[entry]);
@@ -908,11 +943,13 @@ uint32 ComfyEngine::actorPopPc(Actor &actor) {
 void ComfyEngine::actorFreePcChain(Actor &actor) {
 	byte first = actor.callPc >> 24;
 	byte entry = first;
+
 	while (entry) {
 		byte next = _actorPcTable[entry] >> 24;
 		if (!next) {
 			_actorPcTable[entry] = _actorPcTable[0];
 			_actorPcTable[0] = (uint32)first << 24;
+
 			if (_sceneActorPcOffset + sizeof(_actorPcTable) <= _sceneMemoryBlock.size())
 				memcpy(&_sceneMemoryBlock[_sceneActorPcOffset], _actorPcTable, sizeof(_actorPcTable));
 
@@ -958,7 +995,7 @@ void ComfyEngine::actorFreeTreePc(uint16 actorIndex) {
 			if (selector & 0xFF000000) {
 				renderInvalidateFullFrame();
 			} else if (selector != 0x00FFFFFF) {
-			renderAddDirtyRect(actor->cachedRect);
+				renderAddDirtyRect(actor->cachedRect);
 			}
 		}
 
@@ -1095,6 +1132,7 @@ bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
 	}
 
 	uint32 pc = actor->currentPc;
+
 	for (;;) {
 		ScriptDispatchStatus status = scriptStep(*actor, pc);
 		if (status == kScriptContinue)
@@ -1130,6 +1168,7 @@ bool ComfyEngine::actorTickTree(uint16 actorIndex) {
 	bool descendChildren = true;
 	bool stopBranch = actorRunScript(actorIndex, descendChildren);
 	actor = actorGetPtr(actorIndex);
+
 	if (stopBranch || !descendChildren || !actor)
 		return stopBranch;
 
@@ -1137,9 +1176,9 @@ bool ComfyEngine::actorTickTree(uint16 actorIndex) {
 	while (child) {
 		Actor *childActor = actorGetPtr(child);
 		uint16 savedNext = childActor ? childActor->nextLink : 0;
-		if (actorTickTree(child))
+		if (actorTickTree(child)) {
 			child = savedNext;
-		else {
+		} else {
 			childActor = actorGetPtr(child);
 			child = childActor ? childActor->nextLink : 0;
 		}
@@ -1149,9 +1188,9 @@ bool ComfyEngine::actorTickTree(uint16 actorIndex) {
 	while (child) {
 		Actor *childActor = actorGetPtr(child);
 		uint16 savedNext = childActor ? childActor->nextLink : 0;
-		if (actorTickTree(child))
+		if (actorTickTree(child)) {
 			child = savedNext;
-		else {
+		} else {
 			childActor = actorGetPtr(child);
 			child = childActor ? childActor->nextLink : 0;
 		}
@@ -1162,10 +1201,11 @@ bool ComfyEngine::actorTickTree(uint16 actorIndex) {
 
 void ComfyEngine::actorDrawList(uint16 actorIndex, int16 x, int16 y, bool visible) {
 	while (actorIndex) {
-		if (_engineVersion == 3 || _usesAnimFile)
+		if (_engineVersion == 3 || _usesAnimFile) {
 			actorDrawInternal(actorIndex, x, y, visible);
-		else
+		} else {
 			actorDraw(actorIndex, x, y);
+		}
 
 		Actor *actor = actorGetPtr(actorIndex);
 		actorIndex = actor ? actor->nextLink : 0;
@@ -1273,6 +1313,7 @@ uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, ComfyRect &maskRec
 	pc += 2;
 	uint16 bitIndex = 0xFFFF;
 	_keymaskCount = wordsLeft;
+
 	while (wordsLeft > 0 && !_scriptFault) {
 		bitIndex++;
 		uint16 spriteId = scriptReadWord(pc);
@@ -1289,9 +1330,11 @@ uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, ComfyRect &maskRec
 			wordsLeft -= 2;
 			_keymaskCount = wordsLeft;
 			uint32 mask = (uint32)1 << (bitIndex & 31);
+
 			if (mode == 1) {
 				uint16 key = scriptReadWord(pc);
 				_keymaskResult = keyBitTest(key) ? 1 : 0;
+
 				if (_keymaskResult) {
 					_keymaskBits |= mask;
 					maskRecord.right = (uint16)_keymaskBits;
@@ -1299,17 +1342,21 @@ uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, ComfyRect &maskRec
 				}
 
 				pc += 2;
-				if (_keymaskResult)
+
+				if (_keymaskResult) {
 					spriteId &= 0x7FFF;
-				else
+				} else {
 					spriteId = scriptReadWord(pc);
+				}
 			} else {
 				_keymaskResult = (_keymaskBits & mask) ? 1 : 0;
 				pc += 2;
-				if (_keymaskResult)
+
+				if (_keymaskResult) {
 					spriteId &= 0x7FFF;
-				else
+				} else {
 					spriteId = scriptReadWord(pc);
+				}
 			}
 
 			pc += 2;
@@ -1330,6 +1377,7 @@ uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, ComfyRect &maskRec
 
 		_keymaskX = baseX + (int16)dx;
 		_keymaskY = baseY + (int16)dy;
+
 		if (_engineVersion <= 2 && (_keymaskX >= 0x0280 || _keymaskX <= (int16)0xFEC0 ||
 				_keymaskY >= 0x0190 || _keymaskY <= (int16)0xFF38))
 			continue;
@@ -1337,6 +1385,7 @@ uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, ComfyRect &maskRec
 		SpriteResource *sprite = _engineVersion <= 2 ?
 			spriteGetPtr((int16)spriteId) :
 			spriteLookup(spriteId, _keymaskX, _keymaskY);
+
 		if (!sprite)
 			continue;
 
@@ -1350,6 +1399,7 @@ uint16 ComfyEngine::scriptEvalKeyMask(uint32 pc, uint16 mode, ComfyRect &maskRec
 			rect->top = top;
 			rect->right = left + sprite->header.width;
 			rect->bottom = top + sprite->header.height;
+
 			if (_isPanther || _engineVersion == 3) {
 				rect->area = spriteId;
 			} else {
@@ -1371,19 +1421,21 @@ void ComfyEngine::actorEvalFrameSelection(uint16 actorIndex, int16 x, int16 y) {
 
 	uint32 selector = actor->cachedSprite;
 	ComfyRect rect = actor->cachedRect;
+
 	if (selector == 0x00FFFFFF) {
 		animFrameInvalidateRects(rect.left, rect.top, 0);
 	} else if (selector & 0xFF000000) {
 		uint16 last = scriptEvalKeyMask(selector & 0x00FFFFFF, 0, rect, _keymaskInvalidationRects,
 			rect.left, rect.top);
+
 		if (last != 0xFFFF && last >= COMFY_KEYMASK_RECT_CAPACITY)
 			last = COMFY_KEYMASK_RECT_CAPACITY - 1;
 
 		if (last != 0xFFFF) {
 			for (uint i = 0; i <= last; i++) {
 				ComfyRect dirtyRect = _keymaskInvalidationRects[i];
-				dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) *
-					(dirtyRect.bottom - dirtyRect.top);
+				dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) * (dirtyRect.bottom - dirtyRect.top);
+
 				if (_engineVersion == 1)
 					dirtyRect.area = (uint16)dirtyRect.area;
 
@@ -1423,8 +1475,7 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 	}
 
 	if (!_usesAnimFile && !actor->visible) {
-		if ((_videoMode == 2 || _videoMode == 4) &&
-				actor->visible != actor->cachedVisible) {
+		if ((_videoMode == 2 || _videoMode == 4) && actor->visible != actor->cachedVisible) {
 			int16 drawX = (int16)(actor->xFixed >> 12) + x;
 			int16 drawY = (int16)(actor->yFixed >> 12) + y;
 			actorEvalFrameSelection(actorIndex, drawX, drawY);
@@ -1436,10 +1487,12 @@ bool ComfyEngine::actorDraw(uint16 actorIndex, int16 x, int16 y) {
 
 	animFrameRecordVocCounter(1);
 	bool queuedActorDraw = (_isPanther || _engineVersion == 3) && (_videoMode == 2 || _videoMode == 4);
-	if ((_isPanther || _engineVersion == 3) && !queuedActorDraw)
+
+	if ((_isPanther || _engineVersion == 3) && !queuedActorDraw) {
 		actorDrawLegacyInternal(actorIndex, x, y);
-	else
+	} else {
 		actorDrawInternal(actorIndex, x, y, true);
+	}
 
 	if (queuedActorDraw)
 		renderFlushDrawCommands();
@@ -1459,6 +1512,7 @@ bool ComfyEngine::actorDrawLegacyInternal(uint16 actorIndex, int16 x, int16 y) {
 	int16 drawY = (int16)(actor->yFixed >> 12) + y;
 	bool drawResult = true;
 	uint16 linkedActor = actor->siblingHead;
+
 	while (linkedActor && drawResult) {
 		drawResult = actorDrawLegacyInternal(linkedActor, drawX, drawY);
 		Actor *linked = actorGetPtr(linkedActor);
@@ -1476,20 +1530,23 @@ bool ComfyEngine::actorDrawLegacyInternal(uint16 actorIndex, int16 x, int16 y) {
 		uint32 pc = selector & 0x00FFFFFF;
 		int16 wordsLeft = (int16)(scriptReadWord(pc) - 1);
 		pc += 2;
+
 		while (wordsLeft > 0 && !_scriptFault) {
 			uint16 spriteId = scriptReadWord(pc);
 			int16 dx = scriptReadWord(pc + 2);
 			int16 dy = scriptReadWord(pc + 4);
 			pc += 6;
 			wordsLeft -= 3;
+
 			if (spriteId & 0x8000) {
 				wordsLeft -= 2;
 				uint16 key = scriptReadWord(pc);
 				pc += 2;
-				if (keyBitTest(key))
+				if (keyBitTest(key)) {
 					spriteId &= 0x7FFF;
-				else
+				} else {
 					spriteId = scriptReadWord(pc);
+				}
 
 				pc += 2;
 			}
@@ -1530,13 +1587,17 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 
 	int16 drawX = (int16)(actor->xFixed >> 12) + x;
 	int16 drawY = (int16)(actor->yFixed >> 12) + y;
+
 	visible = visible && actor->visible;
 	byte oldVisible = actor->cachedVisible;
 	uint32 oldSelector = actor->cachedSprite;
 	ComfyRect oldRect = actor->cachedRect;
+
 	actorDrawList(actor->siblingHead, drawX, drawY, visible);
+
 	uint32 selector = actor->spriteSelector;
 	bool useDrawQueue = _usesAnimFile && (_isPanther || _engineVersion == 3) && (_videoMode == 2 || _videoMode == 4);
+
 	if (_isPanther || _engineVersion == 3) {
 		ComfyRect newRect;
 		if (selector == 0x00FFFFFF) {
@@ -1573,8 +1634,9 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			_keymaskCurrentRecord.right = 0;
 			_keymaskCurrentRecord.bottom = 0;
 			_keymaskCurrentRecord.area = 0;
-			currentLastRect = scriptEvalKeyMask(selector & 0x00FFFFFF, 1,
-				_keymaskCurrentRecord, _keymaskRects, drawX, drawY);
+
+			currentLastRect = scriptEvalKeyMask(selector & 0x00FFFFFF, 1, _keymaskCurrentRecord, _keymaskRects, drawX, drawY);
+
 			if (currentLastRect != 0xFFFF && currentLastRect >= COMFY_KEYMASK_RECT_CAPACITY)
 				currentLastRect = COMFY_KEYMASK_RECT_CAPACITY - 1;
 
@@ -1590,11 +1652,10 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			}
 		}
 
-		if (scripted && oldSelector == selector && oldRect.left == newRect.left &&
-				oldRect.top == newRect.top && oldVisible == 1 && visible) {
+		if (scripted && oldSelector == selector && oldRect.left == newRect.left && oldRect.top == newRect.top && oldVisible == 1 && visible) {
 			ComfyRect oldMaskRecord = oldRect;
-			uint16 oldLastRect = scriptEvalKeyMask(oldSelector & 0x00FFFFFF, 0,
-				oldMaskRecord, _keymaskOldRects, oldRect.left, oldRect.top);
+			uint16 oldLastRect = scriptEvalKeyMask(oldSelector & 0x00FFFFFF, 0, oldMaskRecord, _keymaskOldRects, oldRect.left, oldRect.top);
+
 			if (oldLastRect != 0xFFFF && oldLastRect >= COMFY_KEYMASK_RECT_CAPACITY)
 				oldLastRect = COMFY_KEYMASK_RECT_CAPACITY - 1;
 
@@ -1602,16 +1663,17 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 				for (uint i = 0; i <= oldLastRect; i++) {
 					ComfyRect &currentRect = _keymaskRects[i];
 					ComfyRect &previousRect = _keymaskOldRects[i];
+
 					bool equal = currentRect.left == previousRect.left &&
 						currentRect.top == previousRect.top &&
 						currentRect.right == previousRect.right &&
 						currentRect.bottom == previousRect.bottom &&
 						currentRect.area == previousRect.area;
+
 					if (!equal)
 						renderAddDirtyRect(previousRect);
 
-					renderQueueDrawCommand(currentRect.left, currentRect.top,
-						currentRect.area, equal ? 1 : 0, actorIndex);
+					renderQueueDrawCommand(currentRect.left, currentRect.top, currentRect.area, equal ? 1 : 0, actorIndex);
 				}
 			}
 
@@ -1625,6 +1687,7 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			oldRect.top != newRect.top || oldRect.right != newRect.right ||
 			oldRect.bottom != newRect.bottom || oldRect.area != newRect.area ||
 			oldVisible != (visible ? 1 : 0);
+
 		if (changed) {
 			if (visible && selector) {
 				if (scripted && currentLastRect != 0xFFFF) {
@@ -1642,23 +1705,22 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 					renderFlushCachedDirtyRects();
 				} else if (oldSelector & 0xFF000000) {
 					ComfyRect oldMaskRecord = oldRect;
-					uint16 oldLastRect = scriptEvalKeyMask(oldSelector & 0x00FFFFFF, 0,
-						oldMaskRecord, _keymaskOldRects, oldRect.left, oldRect.top);
+					uint16 oldLastRect = scriptEvalKeyMask(oldSelector & 0x00FFFFFF, 0, oldMaskRecord, _keymaskOldRects, oldRect.left, oldRect.top);
+
 					if (oldLastRect != 0xFFFF && oldLastRect >= COMFY_KEYMASK_RECT_CAPACITY)
 						oldLastRect = COMFY_KEYMASK_RECT_CAPACITY - 1;
 
 					if (oldLastRect != 0xFFFF) {
 						for (uint i = 0; i <= oldLastRect; i++)
-								renderAddDirtyRect(_keymaskOldRects[i]);
+							renderAddDirtyRect(_keymaskOldRects[i]);
 					}
 				} else {
-						renderAddDirtyRect(oldRect);
+					renderAddDirtyRect(oldRect);
 				}
 			}
 
 			actor->cachedVisible = visible ? 1 : 0;
 			actor->cachedRect = newRect;
-
 			actor->cachedSprite = selector;
 		} else if (visible) {
 			if (scripted && currentLastRect != 0xFFFF) {
@@ -1677,8 +1739,10 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 
 	bool oldScripted = (oldSelector & 0xFF000000) != 0;
 	bool newScripted = (selector & 0xFF000000) != 0;
+
 	ComfyRect newRect;
 	uint16 scriptedLastRect = 0xFFFF;
+
 	if (newScripted) {
 		uint32 pc = selector & 0x00FFFFFF;
 		if (_videoMode == 2 || _videoMode == 4) {
@@ -1687,6 +1751,7 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			_keymaskCurrentRecord.right = 0;
 			_keymaskCurrentRecord.bottom = 0;
 			_keymaskCurrentRecord.area = 0;
+
 			scriptedLastRect = scriptEvalKeyMask(pc, 1, _keymaskCurrentRecord, _keymaskRects, drawX, drawY);
 			if (scriptedLastRect != 0xFFFF && scriptedLastRect >= COMFY_KEYMASK_RECT_CAPACITY)
 				scriptedLastRect = COMFY_KEYMASK_RECT_CAPACITY - 1;
@@ -1695,30 +1760,36 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 				for (uint i = 0; i <= scriptedLastRect; i++) {
 					ComfyRect &drawRecord = _keymaskRects[i];
 					if (drawRecord.area) {
-						if (useDrawQueue)
+						if (useDrawQueue) {
 							renderQueueDrawCommand(drawRecord.left, drawRecord.top, drawRecord.area, 1, actorIndex);
-						else
+						} else {
 							spriteBlitClipped((int16)drawRecord.area, drawRecord.left, drawRecord.top);
+						}
 					}
 				}
 			}
 		} else {
 			int16 wordsLeft = (int16)(scriptReadWord(pc) - 1);
 			pc += 2;
+
 			while (wordsLeft > 0 && !_scriptFault) {
 				uint16 spriteId = scriptReadWord(pc);
 				int16 dx = scriptReadWord(pc + 2);
 				int16 dy = scriptReadWord(pc + 4);
+
 				pc += 6;
 				wordsLeft -= 3;
+
 				if (spriteId & 0x8000) {
 					wordsLeft -= 2;
 					uint16 key = scriptReadWord(pc);
 					pc += 2;
-					if (keyBitTest(key))
+
+					if (keyBitTest(key)) {
 						spriteId &= 0x7FFF;
-					else
+					} else {
 						spriteId = scriptReadWord(pc);
+					}
 
 					pc += 2;
 				}
@@ -1728,10 +1799,12 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 					if (sprite) {
 						int16 spriteX = drawX + dx - sprite->header.hotspotX;
 						int16 spriteY = drawY + dy - sprite->header.hotspotY;
-						if (useDrawQueue)
+
+						if (useDrawQueue) {
 							renderQueueDrawCommand(spriteX, spriteY, spriteId, 1, actorIndex);
-						else
+						} else {
 							spriteBlitClipped((int16)spriteId, spriteX, spriteY);
+						}
 					}
 				}
 			}
@@ -1743,12 +1816,15 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 	} else if (selector == 0x00FFFFFF) {
 		uint16 frameWidth = 0;
 		uint16 frameHeight = 0;
+
 		animFrameGetDimensions(frameWidth, frameHeight);
+
 		newRect.left = drawX;
 		newRect.top = drawY;
 		newRect.right = drawX + frameWidth;
 		newRect.bottom = drawY + frameHeight;
 		newRect.area = frameWidth * frameHeight;
+
 		if (_engineVersion == 1)
 			newRect.area = (uint16)newRect.area;
 
@@ -1768,31 +1844,37 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			newRect.right = newRect.left + sprite->header.width;
 			newRect.bottom = newRect.top + sprite->header.height;
 			newRect.area = sprite->header.width * sprite->header.height;
+
 			if (_engineVersion == 1)
 				newRect.area = (uint16)newRect.area;
 
 			if (visible) {
 				int16 spriteX = drawX - sprite->header.hotspotX;
 				int16 spriteY = drawY - sprite->header.hotspotY;
-				if (useDrawQueue)
+
+				if (useDrawQueue) {
 					renderQueueDrawCommand(spriteX, spriteY, selector, 1, actorIndex);
-				else
+				} else {
 					spriteBlitClipped((int16)selector, spriteX, spriteY);
+				}
 			}
 		}
 	}
+
 	if (_videoMode == 2 || _videoMode == 4) {
 		byte newVisible = visible ? 1 : 0;
 		bool changed = oldSelector != selector || oldVisible != newVisible;
-		if (oldRect.left != newRect.left || oldRect.top != newRect.top ||
-				oldRect.right != newRect.right || oldRect.bottom != newRect.bottom || oldRect.area != newRect.area)
+
+		if (oldRect.left  != newRect.left  || oldRect.top    != newRect.top    ||
+			oldRect.right != newRect.right || oldRect.bottom != newRect.bottom || oldRect.area != newRect.area)
 			changed = true;
 
 		uint16 oldScriptedLastRect = 0xFFFF;
+
 		if (oldScripted) {
 			ComfyRect maskRecord = oldRect;
-			oldScriptedLastRect = scriptEvalKeyMask(oldSelector & 0x00FFFFFF, 0, maskRecord,
-				_keymaskOldRects, oldRect.left, oldRect.top);
+			oldScriptedLastRect = scriptEvalKeyMask(oldSelector & 0x00FFFFFF, 0, maskRecord, _keymaskOldRects, oldRect.left, oldRect.top);
+
 			if (oldScriptedLastRect != 0xFFFF && oldScriptedLastRect >= COMFY_KEYMASK_RECT_CAPACITY)
 				oldScriptedLastRect = COMFY_KEYMASK_RECT_CAPACITY - 1;
 		}
@@ -1802,17 +1884,20 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			if (newScripted && oldScripted && oldSelector == selector &&
 					oldRect.left == _keymaskCurrentRecord.left && oldRect.top == _keymaskCurrentRecord.top &&
 					scriptedLastRect != 0xFFFF && oldScriptedLastRect != 0xFFFF) {
+
 				uint16 last = MAX(scriptedLastRect, oldScriptedLastRect);
+
 				for (uint i = 0; i <= last; i++) {
 					ComfyRect *oldItem = i <= oldScriptedLastRect ? &_keymaskOldRects[i] : nullptr;
 					ComfyRect *newItem = i <= scriptedLastRect ? &_keymaskRects[i] : nullptr;
 					bool equal = oldItem && newItem && oldItem->left == newItem->left && oldItem->top == newItem->top &&
 						oldItem->right == newItem->right && oldItem->bottom == newItem->bottom && oldItem->area == newItem->area;
+
 					if (!equal) {
 						if (oldItem) {
 							ComfyRect dirtyRect = *oldItem;
-							dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) *
-								(dirtyRect.bottom - dirtyRect.top);
+							dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) * (dirtyRect.bottom - dirtyRect.top);
+
 							if (_engineVersion == 1)
 								dirtyRect.area = (uint16)dirtyRect.area;
 
@@ -1821,8 +1906,8 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 
 						if (newItem) {
 							ComfyRect dirtyRect = *newItem;
-							dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) *
-								(dirtyRect.bottom - dirtyRect.top);
+							dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) * (dirtyRect.bottom - dirtyRect.top);
+
 							if (_engineVersion == 1)
 								dirtyRect.area = (uint16)dirtyRect.area;
 
@@ -1835,8 +1920,8 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			} else if (newScripted && scriptedLastRect != 0xFFFF) {
 				for (uint i = 0; i <= scriptedLastRect; i++) {
 					ComfyRect dirtyRect = _keymaskRects[i];
-					dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) *
-						(dirtyRect.bottom - dirtyRect.top);
+					dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) * (dirtyRect.bottom - dirtyRect.top);
+
 					if (_engineVersion == 1)
 						dirtyRect.area = (uint16)dirtyRect.area;
 
@@ -1850,8 +1935,8 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 				if (oldScripted && oldScriptedLastRect != 0xFFFF) {
 					for (uint i = 0; i <= oldScriptedLastRect; i++) {
 						ComfyRect dirtyRect = _keymaskOldRects[i];
-						dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) *
-							(dirtyRect.bottom - dirtyRect.top);
+						dirtyRect.area = (uint32)(dirtyRect.right - dirtyRect.left) * (dirtyRect.bottom - dirtyRect.top);
+
 						if (_engineVersion == 1)
 							dirtyRect.area = (uint16)dirtyRect.area;
 
@@ -1868,6 +1953,7 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 		actor->cachedVisible = newVisible;
 		actor->cachedSprite = selector;
 		actor->cachedRect = newRect;
+
 		if (_engineVersion == 1)
 			actor->cachedRect.area &= 0xFFFF;
 	}
diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
index 540098b0d19..693c3133533 100644
--- a/engines/comfy/anim_file.cpp
+++ b/engines/comfy/anim_file.cpp
@@ -66,8 +66,8 @@ void ComfyEngine::animFrameSetVocCounter(uint32 counter) {
 	if (!_midiPlyrDriver)
 		return;
 
-	// The original uses a wave callback counter when the ANM header requests it.
-	// ScummVM uses the MidiPlyr timer as the common host-side VOC clock.
+	// The original uses a wave callback counter when the ANM header requests it;
+	// we use the MidiPlyr timer as the common host-side VOC clock...
 	_midiPlyrDriver->setIncreaseVocCounter(1);
 	_midiPlyrDriver->setVocCounter(counter);
 }
@@ -86,6 +86,7 @@ bool ComfyEngine::animFileOpen() {
 		return false;
 
 	_animIndexTable.resize(count);
+
 	for (uint i = 0; i < count; i++)
 		_animIndexTable[i] = READ_LE_UINT32(&_animFileData[COMFY_ANMFILE_HEADER_BYTES + i * 4]);
 
@@ -150,6 +151,7 @@ void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 ac
 	memcpy(_animFrameHeader, &_animFileData[offset], sizeof(_animFrameHeader));
 	uint16 magic = READ_LE_UINT16(_animFrameHeader);
 	uint16 expectedMagic = _animPantherFormat ? COMFY_ANMFRAME_PANTHER_MAGIC : COMFY_ANMFRAME_MAGIC;
+
 	if (magic != expectedMagic)
 		error("Invalid frame header in ANMFILE.DAT for animation %u", (uint)animIndex);
 
@@ -160,6 +162,7 @@ void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 ac
 	memset(_animStorageChunkOffsets, 0, sizeof(_animStorageChunkOffsets));
 	memset(_animStorageChunkSizes, 0, sizeof(_animStorageChunkSizes));
 	memset(_animFrameCommandData, 0, sizeof(_animFrameCommandData));
+
 	_animFrameCommandDataSize = 0;
 	_animFrameCommandArgument = 0;
 	_animFrameCommandFlag = false;
@@ -170,6 +173,7 @@ void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 ac
 	_animCurrentActorSceneHandle = actorSceneHandle;
 	_animCurrentFrameKey = frameKey;
 	_animUsesWaveVocCounter = READ_LE_UINT32(_animFrameHeader + 4) != 0;
+
 	if (_animUsesWaveVocCounter) {
 		vocQueuePlayAll();
 		vocQueuePush(0xFFFF, 0, 0);
@@ -194,8 +198,10 @@ void ComfyEngine::animFileLoadFrame(uint16 animIndex, uint16 frameKey, uint16 ac
 uint32 ComfyEngine::animDecompressRle(const byte *source, uint32 sourceSize, byte *destination, uint32 destinationSize) {
 	uint32 sourcePosition = 0;
 	uint32 destinationPosition = 0;
+
 	while (sourcePosition < sourceSize) {
 		byte control = source[sourcePosition++];
+
 		if (control == 0) {
 			if (sourcePosition + 1 >= sourceSize)
 				return destinationPosition;
@@ -266,15 +272,18 @@ uint32 ComfyEngine::animDecodePanther(const byte *source, uint32 sourceSize) {
 	uint32 sourcePosition = 6;
 	uint32 destinationPosition = 0;
 	uint32 written = 0;
+
 	if (kind == 7) {
 		if (sourcePosition + 2 > sourceSize)
 			return 0;
 
 		uint16 rows = READ_LE_UINT16(source + sourcePosition);
 		sourcePosition += 2;
+
 		while (rows && sourcePosition + 2 <= sourceSize && destinationPosition < _animFrameBuffer.size()) {
 			uint16 runCount = READ_LE_UINT16(source + sourcePosition);
 			sourcePosition += 2;
+
 			if (runCount & 0x4000) {
 				destinationPosition += (uint32)(uint16)(0 - runCount) * _logicalScreenWidth;
 				continue;
@@ -294,6 +303,7 @@ uint32 ComfyEngine::animDecodePanther(const byte *source, uint32 sourceSize) {
 
 					byte low = source[sourcePosition++];
 					byte high = source[sourcePosition++];
+
 					while (count-- && destinationPosition + 1 < _animFrameBuffer.size()) {
 						_animFrameBuffer[destinationPosition++] = low;
 						_animFrameBuffer[destinationPosition++] = high;
@@ -324,13 +334,15 @@ uint32 ComfyEngine::animDecodePanther(const byte *source, uint32 sourceSize) {
 
 	uint16 width = READ_LE_UINT16(_animFrameHeader + 10);
 	uint16 height = READ_LE_UINT16(_animFrameHeader + 12);
-	for (uint16 row = 0; row < height && sourcePosition < sourceSize &&
-			destinationPosition < _animFrameBuffer.size(); row++) {
+
+	for (uint16 row = 0; row < height && sourcePosition < sourceSize && destinationPosition < _animFrameBuffer.size(); row++) {
 		sourcePosition++;
 		uint16 remaining = width;
+
 		while (remaining && sourcePosition < sourceSize && destinationPosition < _animFrameBuffer.size()) {
 			byte control = source[sourcePosition++];
 			uint16 count = control;
+
 			if (control & 0x80) {
 				count = 0x100 - control;
 				count = MIN(count, remaining);
@@ -382,8 +394,10 @@ void ComfyEngine::animFileTickCommands() {
 
 	bool ended = false;
 	bool frameReady = false;
+
 	while (!ended && !frameReady) {
 		uint32 headerSize = _animPantherFormat ? 8 : 4;
+
 		if (_animPosition > _animFileData.size() || headerSize > _animFileData.size() - _animPosition)
 			error("ANMFILE.DAT is truncated while reading an animation command");
 
@@ -395,7 +409,7 @@ void ComfyEngine::animFileTickCommands() {
 		uint32 commandSize = rawCommandSize;
 
 		// WPANTHER compares the FR command size as signed. Some Panther data uses
-		// negative sizes here; this marks the frame ready without decoding payload.
+		// negative sizes here; this marks the frame ready without decoding payload...
 		if (_animPantherFormat && command == kAnimCommandFrame && signedCommandSize <= (int32)headerSize) {
 			int64 nextPosition = (int64)commandStart + signedCommandSize;
 			if (nextPosition < 0 || nextPosition > (int64)_animFileData.size())
@@ -406,8 +420,8 @@ void ComfyEngine::animFileTickCommands() {
 			uint32 frameStart = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
 			_animSavedStreamPosition = (uint32)nextPosition - frameStart;
 
-			// The original file object has already consumed the 8-byte FR header.
-			// Its separately serialized cursor can be signed and point backward.
+			// The original file object has already consumed the 8-byte FR header;
+			// its separately serialized cursor can be signed so that it points backwards...
 			_animPosition = commandStart + headerSize;
 			frameReady = true;
 			continue;
@@ -426,8 +440,8 @@ void ComfyEngine::animFileTickCommands() {
 		uint32 payloadSize = commandSize - headerSize;
 		byte *payload = header + headerSize;
 		_animPosition += commandSize;
-		_animSavedStreamPosition = _animPosition -
-			(_animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES);
+		_animSavedStreamPosition = _animPosition - (_animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES);
+
 		if (command == kAnimCommandEnd) {
 			ended = true;
 		} else if (command == kAnimCommandStoreFrameBytes) {
@@ -435,6 +449,7 @@ void ComfyEngine::animFileTickCommands() {
 			uint32 frameStart = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
 			animFilePushStorageChunk((uint32)(payload - &_animFileData[frameStart]), oldSize, (uint16)payloadSize);
 			_animFrameStorage.resize(oldSize + payloadSize);
+
 			if (payloadSize)
 				memcpy(&_animFrameStorage[oldSize], payload, payloadSize);
 
@@ -442,6 +457,7 @@ void ComfyEngine::animFileTickCommands() {
 				_animSoundDataPosition += payloadSize;
 		} else if (command == kAnimCommandDirtyRect) {
 			_animFrameCommandDataSize = payloadSize;
+
 			if (_animPantherFormat && _engineVersion == 3) {
 				_animFrameCommandFlag = (READ_LE_UINT16(header + 6) & 0x8000) != 0;
 				_animFrameCommandArgument = READ_LE_UINT16(header + 6) & 0x07FF;
@@ -458,6 +474,7 @@ void ComfyEngine::animFileTickCommands() {
 					animDecodePanther(payload, payloadSize);
 				} else {
 					animDecompressRle(payload, payloadSize, &_animFrameBuffer[0], _animFrameBuffer.size());
+
 					if (_framebufPtr) {
 						memcpy(_framebufPtr, &_animFrameBuffer[0], COMFY_ANMFRAME_BYTES);
 						renderRequestFullFrameInvalidation();
@@ -503,6 +520,7 @@ bool ComfyEngine::animFrameShouldDraw(uint16 phase) {
 	int16 delta = animFrameVocCounterDelta();
 	int16 adjustedDelta = (int16)((phase == 1 ? (int16)(delta + _animVocDeltaA) : delta) + _animVocDeltaB);
 	bool shouldDraw = adjustedDelta <= threshold;
+
 	if (!shouldDraw) {
 		if ((int16)_animVocDeltaA > 0)
 			_animVocDeltaA--;
@@ -519,6 +537,7 @@ void ComfyEngine::animFrameRecordVocCounter(uint16 phase) {
 		return;
 
 	uint32 counter = _midiPlyrDriver->getVocCounter();
+
 	if (phase == 1) {
 		_animVocCounterStartA = counter;
 	} else if (phase == 2) {
@@ -538,6 +557,7 @@ void ComfyEngine::animFrameWaitForVocCounter() {
 
 	while (animFrameVocCounterDelta() < -(int16)(_animVocDeltaB + 3)) {
 		processEvents();
+
 		if (shouldQuit())
 			break;
 	}
@@ -559,6 +579,7 @@ bool ComfyEngine::animFrameBlitAt(int16 x, int16 y) {
 
 	uint16 frameWidth = 0;
 	uint16 frameHeight = 0;
+
 	if (!animFrameGetDimensions(frameWidth, frameHeight))
 		return false;
 
@@ -574,6 +595,7 @@ bool ComfyEngine::animFrameBlitAt(int16 x, int16 y) {
 		int16 clippedTop = MAX<int16>(top, 0);
 		int16 clippedRight = MIN<int16>(right, _logicalScreenWidth);
 		int16 clippedBottom = MIN<int16>(bottom, _logicalScreenHeight);
+
 		if (clippedLeft >= clippedRight || clippedTop >= clippedBottom)
 			continue;
 
@@ -581,11 +603,13 @@ bool ComfyEngine::animFrameBlitAt(int16 x, int16 y) {
 			uint32 sourceOffset = (uint32)(row - y) * _logicalScreenWidth + clippedLeft - x;
 			uint32 destinationOffset = (uint32)row * _logicalScreenWidth + clippedLeft;
 			uint32 width = clippedRight - clippedLeft;
+
 			if (sourceOffset >= _animFrameBuffer.size())
 				break;
 
 			width = MIN<uint32>(width, _animFrameBuffer.size() - sourceOffset);
 			uint32 column = 0;
+
 			while (column < width) {
 				while (column < width && _animFrameBuffer[sourceOffset + column] == 0xFF)
 					column++;
@@ -614,15 +638,14 @@ bool ComfyEngine::animFrameCoversPoint(int16 x, int16 y, int16 pointX, int16 poi
 	if (!animFrameGetDimensions(frameWidth, frameHeight))
 		return false;
 
-	if (pointX < x || pointY < y || pointX >= x + (int16)frameWidth ||
-			pointY >= y + (int16)frameHeight)
+	if (pointX < x || pointY < y || pointX >= x + (int16)frameWidth || pointY >= y + (int16)frameHeight)
 		return false;
 
 	bool dirty = false;
 	for (uint i = 0; i < _dirtyRectCount; i++) {
 		ComfyRect &dirtyRect = _dirtyRects[i];
-		if (pointX >= dirtyRect.left && pointX < dirtyRect.right &&
-				pointY >= dirtyRect.top && pointY < dirtyRect.bottom) {
+
+		if (pointX >= dirtyRect.left && pointX < dirtyRect.right && pointY >= dirtyRect.top && pointY < dirtyRect.bottom) {
 			dirty = true;
 			break;
 		}
@@ -639,10 +662,10 @@ void ComfyEngine::animFrameInvalidateRects(int16 x, int16 y, byte mode) {
 	if (_animFrameBuffer.empty())
 		return;
 
-	uint16 rectCount = MIN<uint16>(_animFrameCommandDataSize / 4,
-		sizeof(_animFrameCommandData) / 4);
+	uint16 rectCount = MIN<uint16>(_animFrameCommandDataSize / 4, sizeof(_animFrameCommandData) / 4);
 	uint16 splitIndex = _animFrameCommandArgument / 4;
-	uint16 columns = _isPanther ? 0x00A0 : 0x0050;
+	uint16 columns = _isPanther ? 160 : 80;
+
 	if (_engineVersion == 3 && _animFrameCommandFlag) {
 		uint16 frameWidth = READ_LE_UINT16(_animFrameHeader + 10);
 		if (frameWidth)
@@ -659,6 +682,7 @@ void ComfyEngine::animFrameInvalidateRects(int16 x, int16 y, byte mode) {
 		rect.right = x + ((end % columns) + 1) * 4;
 		rect.bottom = y + ((end / columns) + 1) * 4;
 		rect.area = (uint32)(rect.right - rect.left) * (rect.bottom - rect.top);
+
 		if (_engineVersion == 1)
 			rect.area = (uint16)rect.area;
 
@@ -679,6 +703,7 @@ void ComfyEngine::animFrameInvalidateRects(int16 x, int16 y, byte mode) {
 			_animFrameDirtyRects[0].right = _logicalScreenWidth;
 			_animFrameDirtyRects[0].bottom = _logicalScreenHeight;
 			_animFrameDirtyRects[0].area = framebufferBytes();
+
 			if (_engineVersion == 1)
 				_animFrameDirtyRects[0].area = (uint16)_animFrameDirtyRects[0].area;
 		}
@@ -711,9 +736,11 @@ void ComfyEngine::animFrameClear() {
 void ComfyEngine::animFilePackState(byte *state) {
 	memset(state, 0, _animPantherFormat ? COMFY_PANTHER_ANM_STATE_BYTES : COMFY_ANM_STATE_BYTES);
 	memcpy(state, _animFrameHeader, sizeof(_animFrameHeader));
+
 	WRITE_LE_UINT16(state + 0x10, _animCurrentIndex);
 	WRITE_LE_UINT16(state + 0x12, _animVocTargetCounter);
 	state[0x14] = _animActive;
+
 	if (_animPantherFormat) {
 		state[0x15] = _animFrameReady;
 		WRITE_LE_UINT16(state + 0x16, _animCurrentFrameKey);
@@ -736,10 +763,10 @@ void ComfyEngine::animFilePackState(byte *state) {
 	}
 
 	uint32 streamPosition = _animSavedStreamPosition;
-
 	uint32 streamPositionOffset = _animPantherFormat ? 0x27 : 0x28;
 	uint32 chunkTableOffset = _animPantherFormat ? 0x2B : 0x2C;
 	WRITE_LE_UINT32(state + streamPositionOffset, streamPosition);
+
 	for (uint i = 0; i < 6; i++) {
 		byte *chunk = state + chunkTableOffset + i * 0x0A;
 		WRITE_LE_UINT32(chunk, _animStorageChunkFileOffsets[i]);
@@ -770,6 +797,7 @@ void ComfyEngine::animFileRebuildStorage(uint32 targetSize) {
 	memset(_animStorageChunkFileOffsets, 0, sizeof(_animStorageChunkFileOffsets));
 	memset(_animStorageChunkOffsets, 0, sizeof(_animStorageChunkOffsets));
 	memset(_animStorageChunkSizes, 0, sizeof(_animStorageChunkSizes));
+
 	if (_animCurrentIndex >= _animIndexTable.size())
 		return;
 
@@ -784,6 +812,7 @@ void ComfyEngine::animFileRebuildStorage(uint32 targetSize) {
 		uint32 rawCommandSize = _animPantherFormat ? READ_LE_UINT32(header + 2) : READ_LE_UINT16(header + 2);
 		int32 signedCommandSize = _animPantherFormat ? (int32)rawCommandSize : (int32)(uint16)rawCommandSize;
 		uint32 commandSize = rawCommandSize;
+
 		if (_animPantherFormat && command == kAnimCommandFrame && signedCommandSize <= (int32)headerSize)
 			break;
 
@@ -796,16 +825,19 @@ void ComfyEngine::animFileRebuildStorage(uint32 targetSize) {
 
 		uint32 payloadSize = commandSize - headerSize;
 		byte *payload = header + headerSize;
+
 		if (command == kAnimCommandStoreFrameBytes && _animFrameStorage.size() < targetSize) {
 			uint32 copySize = MIN<uint32>(payloadSize, targetSize - _animFrameStorage.size());
 			uint32 oldSize = _animFrameStorage.size();
 			uint32 frameStart = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
 			animFilePushStorageChunk((uint32)(payload - &_animFileData[frameStart]), oldSize, (uint16)copySize);
 			_animFrameStorage.resize(oldSize + copySize);
+
 			if (copySize)
 				memcpy(&_animFrameStorage[oldSize], payload, copySize);
 		} else if (command == kAnimCommandDirtyRect) {
 			_animFrameCommandDataSize = payloadSize;
+
 			if (_animPantherFormat && _engineVersion == 3) {
 				_animFrameCommandFlag = (READ_LE_UINT16(header + 6) & 0x8000) != 0;
 				_animFrameCommandArgument = READ_LE_UINT16(header + 6) & 0x07FF;
@@ -830,6 +862,7 @@ void ComfyEngine::animFileUnpackState(const byte *state) {
 	_animActive = state[0x14] != 0;
 	uint32 chunkTableOffset = 0;
 	uint32 vocCounterOffset = 0;
+
 	if (_animPantherFormat) {
 		_animFrameReady = state[0x15] != 0;
 		_animCurrentFrameKey = READ_LE_UINT16(state + 0x16);
@@ -858,8 +891,7 @@ void ComfyEngine::animFileUnpackState(const byte *state) {
 		_animStorageChunkFileOffsets[i] = READ_LE_UINT32(chunk);
 		_animStorageChunkOffsets[i] = READ_LE_UINT32(chunk + 4);
 		_animStorageChunkSizes[i] = READ_LE_UINT16(chunk + 8);
-		storageSize = MAX<uint32>(storageSize,
-			_animStorageChunkOffsets[i] + _animStorageChunkSizes[i]);
+		storageSize = MAX<uint32>(storageSize, _animStorageChunkOffsets[i] + _animStorageChunkSizes[i]);
 	}
 
 	if (_animCurrentActorSceneHandle == 0)
@@ -889,8 +921,8 @@ void ComfyEngine::animFrameInvalidateActorRect() {
 	if (!actor)
 		return;
 
-	actor->cachedRect.left = 0x270F;
-	actor->cachedRect.right = 0x270F;
+	actor->cachedRect.left = 9999;
+	actor->cachedRect.right = 9999;
 }
 
 } // End of namespace Comfy
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index b9e3e6683a2..74dd5f90b1c 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -709,23 +709,23 @@ private:
 	uint16 _mouseFlags = 0;
 	bool _waveOutputActive = false;
 	byte _v3SceneWaveBalancePercent = 0;
-	byte _v3SceneHostMediaModeEnabled = 0;
+	byte _v3SceneMediaModeEnabled = 0;
 	byte _v3SceneWaveLeftPercent = 0;
 	byte _v3SceneWaveRightPercent = 0;
 	byte _v3SceneMixerVolumePercent = 0;
-	bool _v3HostMediaValueAvailable = false;
-	uint16 _v3HostMediaValue = 0;
-	uint16 _v3HostMediaProgress = 0;
+	bool _v3MediaValueAvailable = false;
+	uint16 _v3MediaValue = 0;
+	uint16 _v3MediaProgress = 0;
 	uint16 _v3Sensitivity = 0;
 	bool _v3ConfigCommandPending = false;
 	byte _v3ConfigCommandSubop = 0;
 	uint16 _v3ConfigCommandValue = 0;
 	Common::String _v3ConfigCommandText;
-	bool _v3HostMediaRecording = false;
-	uint16 _v3HostMediaRecordingArg0 = 0;
-	uint16 _v3HostMediaRecordingArg1 = 0;
-	uint16 _v3HostMediaRecordingArg2 = 0;
-	uint16 _v3HostMediaRecordingArg3 = 0;
+	bool _v3MediaRecording = false;
+	uint16 _v3MediaRecordingArg0 = 0;
+	uint16 _v3MediaRecordingArg1 = 0;
+	uint16 _v3MediaRecordingArg2 = 0;
+	uint16 _v3MediaRecordingArg3 = 0;
 	uint16 _v3AnimIndexOffset = 0;
 	uint16 _v3AnimActorSceneHandle = 0;
 	uint16 _v3WaveBalancePercent = 0;
@@ -1108,6 +1108,7 @@ private:
 	void soundUnpackState(byte *state);
 	void soundPlayEntry(uint16 index);
 	void soundAdvanceTick();
+
 #ifdef USE_IMGUI
 	bool debugScriptHasRange(uint32 pc, uint32 width);
 	uint16 debugScriptReadWord(uint32 pc);
diff --git a/engines/comfy/debug.cpp b/engines/comfy/debug.cpp
index a98a52bd5bc..603518861ad 100644
--- a/engines/comfy/debug.cpp
+++ b/engines/comfy/debug.cpp
@@ -38,14 +38,12 @@ static void debugIncludeMapPoint(int16 &mapLeft, int16 &mapTop, int16 &mapRight,
 	mapBottom = MAX(mapBottom, y);
 }
 
-static void debugIncludeMapRect(int16 &mapLeft, int16 &mapTop, int16 &mapRight, int16 &mapBottom,
-		int16 left, int16 top, int16 right, int16 bottom) {
+static void debugIncludeMapRect(int16 &mapLeft, int16 &mapTop, int16 &mapRight, int16 &mapBottom, int16 left, int16 top, int16 right, int16 bottom) {
 	debugIncludeMapPoint(mapLeft, mapTop, mapRight, mapBottom, left, top);
 	debugIncludeMapPoint(mapLeft, mapTop, mapRight, mapBottom, right, bottom);
 }
 
-static ImVec2 debugMapPointToCanvas(const ImVec2 &canvasPos, int16 mapLeft, int16 mapTop,
-		float scale, float margin, int16 x, int16 y) {
+static ImVec2 debugMapPointToCanvas(const ImVec2 &canvasPos, int16 mapLeft, int16 mapTop, float scale, float margin, int16 x, int16 y) {
 	return ImVec2(canvasPos.x + ((float)x - mapLeft) * scale + margin,
 		canvasPos.y + ((float)y - mapTop) * scale + margin);
 }
@@ -75,16 +73,17 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 	}
 
 	ImGui::Text("Game: %s  version: %u  actors: %u", getGameId().c_str(), _engineVersion, (uint)_actors.size());
-	ImGui::TextDisabled("Tip: disable Visible/Active to isolate a problematic actor.");
 	bool centerFramebuffer = ImGui::Button("Center framebuffer");
 	ImGui::SameLine();
 	ImGui::Checkbox("Tree view", &_state->_actorDebugTreeView);
+
 	if (_state->_actorDebugLastScene != _currentScene ||
 			_state->_actorDebugLastSceneGeneration != _debugSceneGeneration) {
 		centerFramebuffer = true;
 		_state->_actorDebugLastScene = _currentScene;
 		_state->_actorDebugLastSceneGeneration = _debugSceneGeneration;
 	}
+
 	ImGui::Separator();
 
 	ImGui::BeginChild("comfy_actor_map", ImVec2(0, 320), true, ImGuiWindowFlags_HorizontalScrollbar);
@@ -104,6 +103,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 		int32 yFixed = actor.yFixed;
 		uint16 parent = actor.parent;
 		uint guard = 0;
+
 		while (parent && parent < _actors.size() && guard++ < COMFY_ACTOR_COUNT) {
 			Actor *parentActor = actorGetPtr(parent);
 			if (!parentActor)
@@ -119,8 +119,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 		debugIncludeMapPoint(mapLeft, mapTop, mapRight, mapBottom, x, y);
 
 		uint32 selector = actor.spriteSelector;
-		if (selector && !(selector & 0xFF000000) && selector != 0x00FFFFFF &&
-				selector < _spriteResources.size() && _spriteResources[selector].loaded) {
+		if (selector && !(selector & 0xFF000000) && selector != 0x00FFFFFF && selector < _spriteResources.size() && _spriteResources[selector].loaded) {
 			SpriteResource &sprite = _spriteResources[selector];
 			debugIncludeMapRect(mapLeft, mapTop, mapRight, mapBottom,
 				x - sprite.header.hotspotX, y - sprite.header.hotspotY,
@@ -130,6 +129,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 			uint32 pc = selector & 0x00FFFFFF;
 			int16 wordsLeft = (int16)(debugScriptReadWord(pc) - 1);
 			pc += 2;
+
 			while (wordsLeft > 0 && debugScriptHasRange(pc, 6)) {
 				uint16 rawSpriteId = debugScriptReadWord(pc);
 				int16 dx = debugScriptReadWord(pc + 2);
@@ -144,10 +144,12 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 					wordsLeft -= 2;
 					uint16 key = debugScriptReadWord(pc);
 					pc += 2;
-					if (keyBitTest(key))
+
+					if (keyBitTest(key)) {
 						spriteId &= 0x7FFF;
-					else
+					} else {
 						spriteId = debugScriptReadWord(pc);
+					}
 
 					pc += 2;
 				}
@@ -155,6 +157,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 				int16 limbX = x + dx;
 				int16 limbY = y + dy;
 				debugIncludeMapPoint(mapLeft, mapTop, mapRight, mapBottom, limbX, limbY);
+
 				if (spriteId && spriteId < _spriteResources.size() && _spriteResources[spriteId].loaded) {
 					SpriteResource &sprite = _spriteResources[spriteId];
 					debugIncludeMapRect(mapLeft, mapTop, mapRight, mapBottom,
@@ -168,18 +171,17 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 
 	float margin = 32.0F;
 	float scale = 1.0F;
-	ImVec2 canvasSize((float)(mapRight - mapLeft) * scale + margin * 2.0F,
-		(float)(mapBottom - mapTop) * scale + margin * 2.0F);
+	ImVec2 canvasSize((float)(mapRight - mapLeft) * scale + margin * 2.0F, (float)(mapBottom - mapTop) * scale + margin * 2.0F);
 
 	ImDrawList *drawList = ImGui::GetWindowDrawList();
 	drawList->PushClipRect(canvasPos, ImVec2(canvasPos.x + canvasSize.x, canvasPos.y + canvasSize.y), true);
 	drawList->AddRectFilled(canvasPos, ImVec2(canvasPos.x + canvasSize.x, canvasPos.y + canvasSize.y), IM_COL32(18, 20, 24, 230));
 	drawList->AddRect(canvasPos, ImVec2(canvasPos.x + canvasSize.x, canvasPos.y + canvasSize.y), IM_COL32(180, 180, 180, 180));
 	ImVec2 screenTopLeft = debugMapPointToCanvas(canvasPos, mapLeft, mapTop, scale, margin, 0, 0);
-	ImVec2 screenBottomRight = debugMapPointToCanvas(canvasPos, mapLeft, mapTop, scale, margin,
-		_logicalScreenWidth, _logicalScreenHeight);
+	ImVec2 screenBottomRight = debugMapPointToCanvas(canvasPos, mapLeft, mapTop, scale, margin, _logicalScreenWidth, _logicalScreenHeight);
 	drawList->AddRectFilled(screenTopLeft, screenBottomRight, IM_COL32(38, 43, 54, 220));
 	drawList->AddRect(screenTopLeft, screenBottomRight, IM_COL32(110, 170, 240, 230));
+
 	for (uint i = 0; i < _actors.size(); i++) {
 		Actor &actor = _actors[i];
 		uint16 sceneHandle = actor.sceneHandle;
@@ -190,6 +192,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 		int32 yFixed = actor.yFixed;
 		uint16 parent = actor.parent;
 		uint guard = 0;
+
 		while (parent && parent < _actors.size() && guard++ < COMFY_ACTOR_COUNT) {
 			Actor *parentActor = actorGetPtr(parent);
 			if (!parentActor)
@@ -204,8 +207,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 		int16 y = (int16)(yFixed >> 12);
 		bool visibleActor = actor.visible != 0;
 		bool activeActor = actor.active != 0;
-		ImU32 color = visibleActor ? (activeActor ? IM_COL32(82, 220, 120, 230) : IM_COL32(238, 185, 74, 230)) :
-			IM_COL32(120, 120, 120, 170);
+		ImU32 color = visibleActor ? (activeActor ? IM_COL32(82, 220, 120, 230) : IM_COL32(238, 185, 74, 230)) : IM_COL32(120, 120, 120, 170);
 
 		ImVec2 point = debugMapPointToCanvas(canvasPos, mapLeft, mapTop, scale, margin, x, y);
 		drawList->AddCircleFilled(point, 3.0F, color);
@@ -215,19 +217,21 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 		drawList->AddText(ImVec2(point.x + 4.0F, point.y - 4.0F), color, actorLabel);
 
 		uint32 selector = actor.spriteSelector;
-		if (visibleActor && selector && !(selector & 0xFF000000) && selector != 0x00FFFFFF &&
-				selector < _spriteResources.size() && _spriteResources[selector].loaded) {
+		if (visibleActor && selector && !(selector & 0xFF000000) && selector != 0x00FFFFFF && selector < _spriteResources.size() && _spriteResources[selector].loaded) {
 			SpriteResource &sprite = _spriteResources[selector];
+
 			ImVec2 topLeft = debugMapPointToCanvas(canvasPos, mapLeft, mapTop, scale, margin,
 				x - sprite.header.hotspotX, y - sprite.header.hotspotY);
 			ImVec2 bottomRight = debugMapPointToCanvas(canvasPos, mapLeft, mapTop, scale, margin,
 				x - sprite.header.hotspotX + sprite.header.width,
 				y - sprite.header.hotspotY + sprite.header.height);
+
 			drawList->AddRect(topLeft, bottomRight, color);
 		} else if (selector & 0xFF000000) {
 			uint32 pc = selector & 0x00FFFFFF;
 			int16 wordsLeft = (int16)(debugScriptReadWord(pc) - 1);
 			pc += 2;
+
 			while (wordsLeft > 0 && debugScriptHasRange(pc, 6)) {
 				uint16 rawSpriteId = debugScriptReadWord(pc);
 				int16 dx = debugScriptReadWord(pc + 2);
@@ -235,6 +239,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 				pc += 6;
 				wordsLeft -= 3;
 				uint16 spriteId = rawSpriteId;
+
 				if (spriteId & 0x8000) {
 					if (!debugScriptHasRange(pc, 4))
 						break;
@@ -242,10 +247,12 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 					wordsLeft -= 2;
 					uint16 key = debugScriptReadWord(pc);
 					pc += 2;
-					if (keyBitTest(key))
+
+					if (keyBitTest(key)) {
 						spriteId &= 0x7FFF;
-					else
+					} else {
 						spriteId = debugScriptReadWord(pc);
+					}
 
 					pc += 2;
 				}
@@ -254,6 +261,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 				int16 limbY = y + dy;
 				ImVec2 limbPoint = debugMapPointToCanvas(canvasPos, mapLeft, mapTop, scale, margin, limbX, limbY);
 				drawList->AddCircleFilled(limbPoint, 2.0F, IM_COL32(120, 205, 255, 220));
+
 				if (spriteId && spriteId < _spriteResources.size() && _spriteResources[spriteId].loaded) {
 					SpriteResource &sprite = _spriteResources[spriteId];
 					ImVec2 topLeft = debugMapPointToCanvas(canvasPos, mapLeft, mapTop, scale, margin,
@@ -261,6 +269,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 					ImVec2 bottomRight = debugMapPointToCanvas(canvasPos, mapLeft, mapTop, scale, margin,
 						limbX - sprite.header.hotspotX + sprite.header.width,
 						limbY - sprite.header.hotspotY + sprite.header.height);
+
 					drawList->AddRect(topLeft, bottomRight, IM_COL32(120, 205, 255, 180));
 				}
 			}
@@ -268,6 +277,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 	}
 
 	ImGui::Dummy(canvasSize);
+
 	if (centerFramebuffer) {
 		ImVec2 childSize = ImGui::GetWindowSize();
 		float targetX = ((float)-mapLeft + (float)_logicalScreenWidth / 2.0F) * scale + margin - childSize.x / 2.0F;
@@ -275,6 +285,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 		ImGui::SetScrollX(MAX(0.0F, targetX));
 		ImGui::SetScrollY(MAX(0.0F, targetY));
 	}
+
 	drawList->PopClipRect();
 	ImGui::EndChild();
 	ImGui::Separator();
@@ -312,8 +323,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 			uint childCount = 0;
 			uint16 child = actor.childHead;
 			uint guard = 0;
-			while (child && child < _actors.size() && child < COMFY_ACTOR_COUNT &&
-					childCount < COMFY_ACTOR_COUNT && guard++ < COMFY_ACTOR_COUNT) {
+			while (child && child < _actors.size() && child < COMFY_ACTOR_COUNT && childCount < COMFY_ACTOR_COUNT && guard++ < COMFY_ACTOR_COUNT) {
 				if (!visited[child]) {
 					children[childCount] = child;
 					childCount++;
@@ -332,6 +342,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 			int32 yFixed = actor.yFixed;
 			uint16 parent = actor.parent;
 			guard = 0;
+
 			while (parent && parent < _actors.size() && guard++ < COMFY_ACTOR_COUNT) {
 				Actor *parentActor = actorGetPtr(parent);
 				if (!parentActor)
@@ -347,6 +358,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 			bool visibleActor = actor.visible != 0;
 			bool activeActor = actor.active != 0;
 			ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanAvailWidth;
+
 			if (!childCount)
 				flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen;
 
@@ -354,17 +366,20 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 			bool open = ImGui::TreeNodeEx("actor", flags, "%u", actorIndex);
 
 			ImGui::SameLine(120.0F);
-			ImGui::Text("scene=%u pos=%d,%d selector=0x%08X move=%d",
-				sceneHandle, x, y, selector, (int16)actor.moveTicks);
+			ImGui::Text("scene=%u pos=%d,%d selector=0x%08X move=%d", sceneHandle, x, y, selector, (int16)actor.moveTicks);
 
 			ImGui::SameLine(520.0F);
+
 			if (ImGui::Checkbox("Visible", &visibleActor)) {
 				actor.visible = visibleActor ? 1 : 0;
 				renderRequestFullFrameInvalidation();
 			}
+
 			ImGui::SameLine();
+
 			if (ImGui::Checkbox("Active", &activeActor))
 				actor.active = activeActor ? 1 : 0;
+
 			ImGui::PopID();
 
 			if (open && childCount) {
@@ -381,8 +396,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 			}
 
 			if (!stackCount) {
-				for (uint i = 0; i < _actors.size() && i < COMFY_ACTOR_COUNT &&
-						stackCount < ARRAYSIZE(actorStack); i++) {
+				for (uint i = 0; i < _actors.size() && i < COMFY_ACTOR_COUNT && stackCount < ARRAYSIZE(actorStack); i++) {
 					Actor &orphanActor = _actors[i];
 					if (visited[i] || (!orphanActor.sceneHandle && i != 0))
 						continue;
@@ -419,6 +433,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 			int32 yFixed = actor.yFixed;
 			uint16 parent = actor.parent;
 			uint guard = 0;
+
 			while (parent && parent < _actors.size() && guard++ < COMFY_ACTOR_COUNT) {
 				Actor *parentActor = actorGetPtr(parent);
 				if (!parentActor)
@@ -451,15 +466,19 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 			ImGui::Text("0x%08X", actor.currentPc);
 			ImGui::TableSetColumnIndex(7);
 			ImGui::PushID((int)i * 2);
+
 			if (ImGui::Checkbox("", &visibleActor)) {
 				actor.visible = visibleActor ? 1 : 0;
 				renderRequestFullFrameInvalidation();
 			}
+
 			ImGui::PopID();
 			ImGui::TableSetColumnIndex(8);
 			ImGui::PushID((int)i * 2 + 1);
+
 			if (ImGui::Checkbox("", &activeActor))
 				actor.active = activeActor ? 1 : 0;
+
 			ImGui::PopID();
 			ImGui::TableSetColumnIndex(9);
 			ImGui::Text("%d", (int16)actor.moveTicks);
@@ -475,11 +494,13 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 				ImGui::Text("local fixed x=0x%08X y=0x%08X moveDx=0x%08X moveDy=0x%08X",
 					(uint32)actor.xFixed, (uint32)actor.yFixed,
 					(uint32)actor.moveDx, (uint32)actor.moveDy);
+
 				if (selector & 0xFF000000) {
 					uint32 pc = selector & 0x00FFFFFF;
 					int16 wordsLeft = (int16)(debugScriptReadWord(pc) - 1);
 					pc += 2;
 					uint limb = 0;
+
 					while (wordsLeft > 0 && limb < 16 && debugScriptHasRange(pc, 6)) {
 						uint16 rawSpriteId = debugScriptReadWord(pc);
 						int16 dx = debugScriptReadWord(pc + 2);
@@ -488,6 +509,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 						wordsLeft -= 3;
 						uint16 spriteId = rawSpriteId;
 						uint16 key = 0;
+
 						if (spriteId & 0x8000) {
 							if (!debugScriptHasRange(pc, 4))
 								break;
@@ -495,10 +517,12 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 							wordsLeft -= 2;
 							key = debugScriptReadWord(pc);
 							pc += 2;
-							if (keyBitTest(key))
+
+							if (keyBitTest(key)) {
 								spriteId &= 0x7FFF;
-							else
+							} else {
 								spriteId = debugScriptReadWord(pc);
+							}
 
 							pc += 2;
 						}
@@ -517,8 +541,8 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 
 		ImGui::EndTable();
 	}
-	ImGui::EndChild();
 
+	ImGui::EndChild();
 	ImGui::End();
 }
 
diff --git a/engines/comfy/expr.cpp b/engines/comfy/expr.cpp
index 515b1be9fd8..28c51e8c408 100644
--- a/engines/comfy/expr.cpp
+++ b/engines/comfy/expr.cpp
@@ -25,6 +25,7 @@ namespace Comfy {
 
 uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 	_exprStackTop = 0;
+
 	for (;;) {
 		byte opcode = scriptReadByte(pc++);
 		if (_scriptFault)
@@ -45,6 +46,7 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 			uint16 index = scriptReadWord(pc);
 			pc += 2;
 			uint16 value = index < _stringTable.size() ? _stringTable[index] : 0;
+
 			if (_exprStackTop < COMFY_EXPR_STACK_CAPACITY)
 				_exprStack[_exprStackTop++] = value;
 
@@ -54,19 +56,21 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 		if (opcode >= 0x10 && opcode <= 0x14) {
 			Actor *actor = actorResolve(scriptReadWord(pc), fallbackActor);
 			pc += 2;
+
 			if (!actor) {
 				_scriptFault = true;
 				return 0;
 			}
 
 			uint16 value = 0;
-			if (opcode == 0x10)
+			if (opcode == 0x10) {
 				value = (uint32)actor->xFixed >> 12;
-			else if (opcode == 0x11)
+			} else if (opcode == 0x11) {
 				value = (uint32)actor->yFixed >> 12;
-			else if (opcode == 0x12 || opcode == 0x13) {
+			} else if (opcode == 0x12 || opcode == 0x13) {
 				bool useX = opcode == 0x12;
 				int32 position = useX ? actor->xFixed : actor->yFixed;
+
 				while (actor->parent) {
 					actor = actorGetPtr(actor->parent);
 					if (!actor)
@@ -97,21 +101,22 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 		if (_engineVersion == 3 && opcode >= 0x17 && opcode <= 0x21) {
 			uint16 value = 0;
 			bool pushValue = true;
-			if (opcode == 0x17)
+
+			if (opcode == 0x17) {
 				value = _mouseX;
-			else if (opcode == 0x18)
+			} else if (opcode == 0x18) {
 				value = _mouseY;
-			else if (opcode == 0x19)
+			} else if (opcode == 0x19) {
 				value = _v3SceneWaveBalancePercent;
-			else if (opcode == 0x1A)
-				value = _v3HostMediaValueAvailable ? _v3HostMediaValue : 0;
-			else if (opcode == 0x1B)
+			} else if (opcode == 0x1A) {
+				value = _v3MediaValueAvailable ? _v3MediaValue : 0;
+			} else if (opcode == 0x1B) {
 				pushValue = false;
-			else if (opcode == 0x1C)
+			} else if (opcode == 0x1C) {
 				value = _v3SceneWaveLeftPercent;
-			else if (opcode == 0x1D)
+			} else if (opcode == 0x1D) {
 				value = _v3SceneWaveRightPercent;
-			else if (opcode == 0x1E) {
+			} else if (opcode == 0x1E) {
 				if (_exprStackTop) {
 					uint16 dimension = _exprStack[_exprStackTop - 1];
 					if (dimension == 0x6E)
@@ -124,7 +129,7 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 
 				pushValue = false;
 			} else if (opcode == 0x1F || opcode == 0x20) {
-				value = _v3HostMediaProgress;
+				value = _v3MediaProgress;
 			} else if (opcode == 0x21) {
 				value = _v3SceneMixerVolumePercent;
 			}
@@ -157,19 +162,21 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 
 		int16 rhs = _exprStack[--_exprStackTop];
 		int16 lhs = _exprStack[_exprStackTop - 1];
-		if (opcode == 0x08)
+
+		if (opcode == 0x08) {
 			_exprStack[_exprStackTop - 1] = (uint16)(lhs + rhs);
-		else if (opcode == 0x09)
+		} else if (opcode == 0x09) {
 			_exprStack[_exprStackTop - 1] = (uint16)(lhs - rhs);
-		else if (opcode == 0x0A)
+		} else if (opcode == 0x0A) {
 			_exprStack[_exprStackTop - 1] = (uint16)(lhs * rhs);
-		else if ((opcode == 0x0B || opcode == 0x0E) && !rhs) {
+		} else if ((opcode == 0x0B || opcode == 0x0E) && !rhs) {
 			_scriptFault = true;
 			return 0;
-		} else if (opcode == 0x0B)
+		} else if (opcode == 0x0B) {
 			_exprStack[_exprStackTop - 1] = (uint16)(lhs / rhs);
-		else if (opcode == 0x0E)
+		} else if (opcode == 0x0E) {
 			_exprStack[_exprStackTop - 1] = (uint16)(lhs % rhs);
+		}
 	}
 }
 
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index 89f42777275..f4f7598fce4 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -216,6 +216,7 @@ void ComfyEngine::iniWriteLanguageSelection(uint16 language) {
 uint16 ComfyEngine::languageSetDataSubdirectory(Common::String text) {
 	uint start = 0;
 	uint end = text.size();
+
 	while (start < end && Common::isSpace((byte)text[start]))
 		start++;
 
@@ -224,6 +225,7 @@ uint16 ComfyEngine::languageSetDataSubdirectory(Common::String text) {
 
 	_v3LanguageDataSubdirectory = text.substr(start, end - start);
 	_languageSessionRestartRequested = true;
+
 	if (_v3LanguageDataSubdirectory.empty())
 		return 0x20;
 
@@ -288,6 +290,7 @@ bool ComfyEngine::readAssetFile(const Common::Path &filename, Common::Array<byte
 
 	uint32 size = stream->size();
 	data.resize(size);
+
 	if (size && stream->read(&data[0], size) != size) {
 		data.clear();
 		return false;
@@ -357,14 +360,11 @@ void ComfyEngine::selPoolFree() {
 	_selectorPoolInitialized = false;
 }
 
-bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount,
-		uint16 scriptVariableCount, uint32 &numSprites) {
+bool ComfyEngine::sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount, uint16 scriptVariableCount, uint32 &numSprites) {
 	return sceneFrameInitTables(sceneCount, actorCount, keyBitCount, scriptVariableCount, numSprites);
 }
 
-bool ComfyEngine::sceneFrameInitTables(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount,
-		uint16 scriptVariableCount, uint32 &numSprites) {
-
+bool ComfyEngine::sceneFrameInitTables(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount, uint16 scriptVariableCount, uint32 &numSprites) {
 	_stringTable.resize(_stringCount);
 	memset(&_stringTable[0], 0, _stringTable.size() * sizeof(uint16));
 	_sceneHandles.resize(sceneCount + 1);
@@ -389,17 +389,19 @@ bool ComfyEngine::sceneFrameInitTables(uint16 sceneCount, uint16 actorCount, uin
 	uint32 stringBytes = stringTableGetSize();
 	uint32 handleBytes = _sceneHandles.size() * sizeof(uint16);
 	uint32 actorRecordSize = COMFY_ACTOR_SIZE_V3;
-	if (_engineVersion == 1)
+
+	if (_engineVersion == 1) {
 		actorRecordSize = COMFY_ACTOR_SIZE_V1;
-	else if (_engineVersion == 2)
+	} else if (_engineVersion == 2) {
 		actorRecordSize = COMFY_ACTOR_SIZE_V2;
+	}
 
 	uint32 actorBytes = _actors.size() * actorRecordSize;
 	uint32 keyBytes = ((uint32)keyBitCount + 1) / 8 + 1;
 	_sceneMidiInstanceOffset = 0;
+
 	if (_engineVersion == 3) {
-		_sceneEntryListOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES + COMFY_SCENE_VOC_STATE_BYTES_V3 +
-				COMFY_ANM_STATE_BYTES;
+		_sceneEntryListOffset = COMFY_SCENE_MIDI_INSTANCE_BYTES + COMFY_SCENE_VOC_STATE_BYTES_V3 + COMFY_ANM_STATE_BYTES;
 		_sceneActorPcOffset = _sceneEntryListOffset + COMFY_SCENE_STATE_BYTES_V3;
 		_sceneStringTableOffset = _sceneActorPcOffset + COMFY_SCENE_ACTOR_PC_BYTES;
 	} else if (_isPanther) {
@@ -628,6 +630,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 		move.destinationHandle = _xmsHeaderHandle;
 		move.destinationOffset = xmsOffset;
 		move.sourceMemory = source;
+
 		if (xmsTransfer(move) < 0)
 			return false;
 
@@ -638,6 +641,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 
 	_headerXmsMidiEntriesBase = xmsOffset;
 	_headerXmsMidiEntriesBytes = midiHeaderBytes;
+
 	if (midiHeaderBytes) {
 		if (!scenePtr)
 			return false;
@@ -658,6 +662,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 
 	_headerXmsSoundHeadersBase = xmsOffset;
 	_headerXmsSoundHeadersBytes = soundHeaderBytes;
+
 	if (soundHeaderBytes) {
 		byte *soundHeaderTable = soundReadHeaderTable();
 		if (!soundHeaderTable)
@@ -688,6 +693,7 @@ void ComfyEngine::assetsUnload(byte freeAudio) {
 	_scenePoolData.clear();
 	spriteInvalidateHostCache(_frameSpriteResource);
 	_frameSpriteResource.id = 0;
+
 	if (!_backgroundFramebuf.empty()) {
 		_backgroundFramebuf.clear();
 		_backgroundFrame = 0;
@@ -715,6 +721,7 @@ void ComfyEngine::assetsUnload(byte freeAudio) {
 		animFileShutdown();
 
 	selPoolFree();
+
 	_spriteHeaders.clear();
 	_spriteResources.clear();
 	_stringTable.clear();
@@ -722,13 +729,17 @@ void ComfyEngine::assetsUnload(byte freeAudio) {
 	_scriptVariables.clear();
 	_actors.clear();
 	_sceneMemoryBlock.clear();
+
 	keyBitFree();
+
 	objFileClose(_vocFile);
 	objFileClose(_picFile);
 	objFileClose(_comfyObjFile);
 	delete _midiFileStream;
 	_midiFileStream = nullptr;
+
 	xmsReset();
+
 	_spriteConversionLoads = ResourceLoadList();
 	memset(_sceneEntryOffsets, 0, sizeof(_sceneEntryOffsets));
 	memset(_actorPcTable, 0, sizeof(_actorPcTable));
diff --git a/engines/comfy/input.cpp b/engines/comfy/input.cpp
index 90e2862168a..8c6b913f62d 100644
--- a/engines/comfy/input.cpp
+++ b/engines/comfy/input.cpp
@@ -88,11 +88,12 @@ void ComfyEngine::lptKeyToFlags(uint16 key) {
 			flags |= 0x10;
 			break;
 		case 27:
-			if (_engineVersion == 3 && (_inputDeviceMode == 2 || _inputDeviceMode == 4) &&
-					!_inputKeyboardBit7Held)
+			if (_engineVersion == 3 && (_inputDeviceMode == 2 || _inputDeviceMode == 4) && !_inputKeyboardBit7Held) {
 				_inputKeyboardResetRequested = true;
-			else
+			} else {
 				flags |= 0x20;
+			}
+
 			break;
 		default:
 			break;
@@ -134,6 +135,7 @@ bool ComfyEngine::hostKeyboardLoadDatMap() {
 	while (stream->pos() < stream->size()) {
 		byte key;
 		byte bit;
+
 		if (stream->read(&key, 1) != 1 || stream->read(&bit, 1) != 1 || bit >= COMFY_KEYBOARD_CONTACT_COUNT) {
 			hostKeyboardResetMap();
 			return false;
@@ -223,8 +225,9 @@ void ComfyEngine::setToyKeyboardState(uint32 activeMask, uint32 latchedMask, uin
 uint32 ComfyEngine::lptKeyboardScan() {
 	// The original wrote eight successive column strobes to the LPT data port, waited 100 busy-loop
 	// iterations after each write, and sampled three bits from the status port. Concatenating those
-	// eight 3-bit samples produced the 24-contact scan word. ScummVM supplies that same word from the
-	// keymapper, KEYBOARD.DAT mappings, and the toy-keyboard UI instead of accessing an I/O port.
+	// eight 3-bit samples produced the 24-contact scan word. We supply that same word from the
+	// keymapper, KEYBOARD.DAT mappings, and the toy-keyboard UI instead of accessing an I/O port...
+
 	if (_engineVersion == 3 && _inputDeviceMode == 2) {
 		_keyboardActiveMask |= _keymapperActiveMask;
 		_keyboardLatchedMask |= _keymapperLatchedMask;
@@ -260,9 +263,11 @@ uint32 ComfyEngine::lptKeyboardScan() {
 
 		_keyboardActiveMask &= ~0x02;
 		_keyboardLatchedMask &= ~0x02;
+
 		if (_inputKeyboardPulseTicks) {
 			_inputComfyboardSuppressBit1 = true;
 			_inputKeyboardPulseTicks--;
+
 			if (_inputKeyboardPulseTicks & 1) {
 				_keyboardActiveMask |= 0x02;
 				_keyboardLatchedMask |= 0x02;
@@ -276,9 +281,9 @@ uint32 ComfyEngine::lptKeyboardScan() {
 	if (_inputKeyboardSyntheticBit7)
 		keyboardState |= 0x80;
 
-	uint32 comfyboardState = (_toyKeyboardActiveMask | _toyKeyboardHoldMask |
-		_toyKeyboardLatchedMask) & 0x00FFFFFF;
+	uint32 comfyboardState = (_toyKeyboardActiveMask | _toyKeyboardHoldMask | _toyKeyboardLatchedMask) & 0x00FFFFFF;
 	uint32 comfyboardHostState = (comfyboardState | _keymapperActiveMask | _keymapperLatchedMask) & 0x00FFFFFF;
+
 	if (_engineVersion == 3 && _midiPlyrDriver) {
 		_midiPlyrDriver->comfyboardSetHostButtons(comfyboardHostState);
 		comfyboardState |= _midiPlyrDriver->comfyboardGetButtons() & 0x00FFFFFF;
@@ -289,6 +294,7 @@ uint32 ComfyEngine::lptKeyboardScan() {
 
 	if (_engineVersion == 3 && !_inputDeviceMode) {
 		_inputDeviceMode = inputDetectDevice(comfyboardState, keyboardState);
+
 		if (_inputDeviceMode == 1 && _midiPlyrDriver) {
 			_midiPlyrDriver->comfyboardStopSleepUse();
 		} else if (_inputDeviceMode == 2 && _midiPlyrDriver) {
@@ -298,16 +304,18 @@ uint32 ComfyEngine::lptKeyboardScan() {
 	}
 
 	uint32 scanState;
-	if (_engineVersion == 3 && _inputDeviceMode == 1)
+
+	if (_engineVersion == 3 && _inputDeviceMode == 1) {
 		scanState = comfyboardState;
-	else if (_engineVersion == 3 && _inputDeviceMode == 2)
+	} else if (_engineVersion == 3 && _inputDeviceMode == 2) {
 		scanState = keyboardState | (_inputKeyboardBit7Held ? 0x80 : 0);
-	else if (_engineVersion == 3 && (_inputDeviceMode == 3 || _inputDeviceMode == 4)) {
-		// Modes 3 and 4 used WinMM MIDI input. ScummVM supplies their logical contacts through the keymapper/UI.
-		scanState = (_toyKeyboardActiveMask | _toyKeyboardHoldMask | _toyKeyboardLatchedMask |
-				_keymapperActiveMask | _keymapperLatchedMask) & 0x00FFFFFF;
+	} else if (_engineVersion == 3 && (_inputDeviceMode == 3 || _inputDeviceMode == 4)) {
+		// Modes 3 and 4 originally used WinMM MIDI input, we route those signalsthrough the keymapper/UI...
+		scanState = (_toyKeyboardActiveMask | _toyKeyboardHoldMask | _toyKeyboardLatchedMask | _keymapperActiveMask | _keymapperLatchedMask) & 0x00FFFFFF;
+
 		if (_inputDeviceMode == 4) {
 			scanState |= 0x2000;
+
 			if (_inputKeyboardSyntheticBit7)
 				scanState |= 0x80;
 		}
@@ -393,35 +401,41 @@ void ComfyEngine::lptKeyboardDispatchEvents(uint32 scanState) {
 	uint32 pressedThisFrame = (~_lptPrevScanState & scanState) & 0x00FFFFFF;
 	keyBitCopyRange(0x20, 0x18, pressedThisFrame);
 
-	if (pressedThisFrame & 0x00FFDFFF)
+	if (pressedThisFrame & 0x00FFDFFF) {
 		keyBitSet(6);
-	else
+	} else {
 		keyBitClear(6);
+	}
 
-	if ((scanState & 0x2000) != (_lptPrevScanState & 0x2000))
+	if ((scanState & 0x2000) != (_lptPrevScanState & 0x2000)) {
 		keyBitSet(0x41);
-	else
+	} else {
 		keyBitClear(0x41);
+	}
 
-	if ((_lptPrevScanState & 0x2000) && ((~scanState & 0x00FFFFFF) & 0x2000))
+	if ((_lptPrevScanState & 0x2000) && ((~scanState & 0x00FFFFFF) & 0x2000)) {
 		keyBitSet(0x44);
-	else
+	} else {
 		keyBitClear(0x44);
+	}
 
-	if (keyBitTest(0x15))
+	if (keyBitTest(0x15)) {
 		keyBitClear(0x45);
-	else
+	} else {
 		keyBitSet(0x45);
+	}
 
-	if ((_lptPrevScanState & 0x80) && ((~scanState & 0x00FFFFFF) & 0x80))
+	if ((_lptPrevScanState & 0x80) && ((~scanState & 0x00FFFFFF) & 0x80)) {
 		keyBitSet(0x43);
-	else
+	} else {
 		keyBitClear(0x43);
+	}
 
-	if (pressedThisFrame & 0x24924)
+	if (pressedThisFrame & 0x24924) {
 		keyBitSet(7);
-	else
+	} else {
 		keyBitClear(7);
+	}
 
 	_lptPrevScanState = scanState;
 }
@@ -429,8 +443,8 @@ void ComfyEngine::lptKeyboardDispatchEvents(uint32 scanState) {
 void ComfyEngine::lptKeyboardInit() {
 	_inputInitialDeviceMode = _inputDeviceMode;
 	_keyboardUiVisible = true;
-	if (_engineVersion == 3 && _midiPlyrDriver &&
-			(_inputDeviceMode == 0 || _inputDeviceMode == 1)) {
+
+	if (_engineVersion == 3 && _midiPlyrDriver && (_inputDeviceMode == 0 || _inputDeviceMode == 1)) {
 		if (!_inputDeviceMode)
 			_midiPlyrDriver->comfyboardStartSleepUse();
 
@@ -444,8 +458,7 @@ void ComfyEngine::lptKeyboardScanAndProcess() {
 }
 
 void ComfyEngine::lptKeyboardShutdown() {
-	if (_engineVersion == 3 && _midiPlyrDriver &&
-			(_inputInitialDeviceMode == 0 || _inputInitialDeviceMode == 1)) {
+	if (_engineVersion == 3 && _midiPlyrDriver && (_inputInitialDeviceMode == 0 || _inputInitialDeviceMode == 1)) {
 		_midiPlyrDriver->comfyboardStopReading();
 		_midiPlyrDriver->comfyboardStopSleepUse();
 	}
diff --git a/engines/comfy/memory.cpp b/engines/comfy/memory.cpp
index 26e8856cee0..66b38de0814 100644
--- a/engines/comfy/memory.cpp
+++ b/engines/comfy/memory.cpp
@@ -23,9 +23,9 @@
 namespace Comfy {
 
 uint16 ComfyEngine::sysGetExtMemKB() {
-	// The original reads CMOS extended-memory registers. The compatibility layer exposes
-	// the 4000 KB configuration that selects the engine's normal high-memory paths.
-	return 0x0FA0;
+	// The original reads CMOS extended-memory registers, so we basically
+	// expose whatever makes the engine select the high-memory paths...
+	return 4000;
 }
 
 uint32 ComfyEngine::memCompactAndCheck(uint32 minimumBytes) {
@@ -59,6 +59,7 @@ uint32 ComfyEngine::memGetFreeKB() {
 
 	uint32 extendedKB = sysGetExtMemKB();
 	uint32 allocatedKB = allocatedBytes >> 10;
+
 	if (extendedKB <= 0x0400 + allocatedKB)
 		return 0x0E;
 
@@ -71,7 +72,8 @@ uint32 ComfyEngine::memGetFreeKBThunk() {
 
 uint32 ComfyEngine::memGetXmsLimit() {
 	uint32 limit = 0x7D000;
-	if (sysGetExtMemKB() < 0x0FA0)
+
+	if (sysGetExtMemKB() < 4000)
 		limit -= 0x25800;
 
 	return limit;
@@ -118,6 +120,7 @@ int32 ComfyEngine::memFreeTrack(uint16 handle) {
 	_xmsBlocks[handle].data = nullptr;
 	_xmsBlocks[handle].size = 0;
 	_xmsBlockCount--;
+
 	return 0;
 }
 
diff --git a/engines/comfy/midi.cpp b/engines/comfy/midi.cpp
index 02ff0da33ef..afa5d9dca54 100644
--- a/engines/comfy/midi.cpp
+++ b/engines/comfy/midi.cpp
@@ -46,9 +46,10 @@ uint16 ComfyEngine::midiTick() {
 
 	do {
 		_midiTimeCounter = _midiPlyrDriver->getTimeCounter();
-		if ((_engineVersion == 3 && _midiTimeCounter <= previousCounter) ||
-				(_engineVersion != 3 && _midiTimeCounter == previousCounter)) {
+
+		if ((_engineVersion == 3 && _midiTimeCounter <= previousCounter) || (_engineVersion != 3 && _midiTimeCounter == previousCounter)) {
 			processEvents();
+
 			if (shouldQuit())
 				return 0;
 
@@ -81,7 +82,7 @@ uint16 ComfyEngine::midiTick() {
 		}
 	}
 
-	while (_midiEvents.nextIndex != 0x03E7 && (int32)_midiInstanceEventTime >= _midiEvents.nextTime) {
+	while (_midiEvents.nextIndex != 999 && (int32)_midiInstanceEventTime >= _midiEvents.nextTime) {
 		keyBitSet(_midiEvents.entries[_midiEvents.nextIndex].id);
 		_midiEvents.count--;
 		_midiEvents.entries[_midiEvents.nextIndex] = _midiEvents.entries[_midiEvents.count];
@@ -101,17 +102,18 @@ bool ComfyEngine::midiPlyrStart() {
 		return false;
 
 	byte flags;
-	if (signature[0] == 'C' && signature[1] == 'M')
+	if (signature[0] == 'C' && signature[1] == 'M') {
 		flags = 0;
-	else if (signature[0] == 'C' && signature[1] == 'm')
+	} else if (signature[0] == 'C' && signature[1] == 'm') {
 		flags = 1;
-	else
+	} else {
 		return false;
+	}
 
 	midiPlyrStop();
-	MidiPlyrDriver::DriverVersion version = _engineVersion == 3 ?
-		MidiPlyrDriver::kDriverVersion2 : MidiPlyrDriver::kDriverVersion1;
+	MidiPlyrDriver::DriverVersion version = _engineVersion == 3 ? MidiPlyrDriver::kDriverVersion2 : MidiPlyrDriver::kDriverVersion1;
 	_midiPlyrDriver = new MidiPlyrDriver(version);
+
 	if (!_midiPlyrDriver->musicStart(flags)) {
 		delete _midiPlyrDriver;
 		_midiPlyrDriver = nullptr;
@@ -162,13 +164,14 @@ void ComfyEngine::midiSetTimeScale(int16 delta) {
 
 void ComfyEngine::midiFindNext(MidiQueue &queue) {
 	if (!queue.count) {
-		queue.nextIndex = 0x03E7;
+		queue.nextIndex = 999;
 		queue.nextTime = 0;
 		return;
 	}
 
 	queue.nextIndex = 0;
 	queue.nextTime = queue.entries[0].time;
+
 	for (uint i = 1; i < queue.count; i++) {
 		if (queue.entries[i].time < queue.nextTime) {
 			queue.nextIndex = i;
@@ -185,6 +188,7 @@ void ComfyEngine::midiInitInstanceAt() {
 	_midiInstanceTrackBase = 1;
 	_midiEvents.baseTime = 0;
 	_midiTracks.baseTime = 1;
+
 	if (_midiPlyrDriver)
 		_midiPlyrDriver->setTimeCounter(_midiTimeCounter);
 
@@ -195,10 +199,11 @@ void ComfyEngine::midiInitInstanceAt() {
 void ComfyEngine::midiInitInstance() {
 	if (_engineVersion == 3) {
 		_midiTracks.nextTime = 0;
-		_midiTracks.nextIndex = 0x03E7;
+		_midiTracks.nextIndex = 999;
 		_midiEvents.nextTime = 0;
-		_midiEvents.nextIndex = 0x03E7;
+		_midiEvents.nextIndex = 999;
 		_midiTimeScale = 0x400;
+
 		if (_midiPlyrDriver) {
 			_midiPlyrDriver->setIncreaseVocCounter(0);
 			_midiPlyrDriver->setVocCounter(0);
@@ -215,6 +220,7 @@ void ComfyEngine::midiInitInstance() {
 	_midiInstanceTrackBase = 1;
 	_midiEvents.baseTime = 0;
 	_midiTracks.baseTime = 1;
+
 	midiFindNext(_midiEvents);
 	midiFindNext(_midiTracks);
 }
@@ -222,10 +228,12 @@ void ComfyEngine::midiInitInstance() {
 void ComfyEngine::midiInitChannels() {
 	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
 		_midiChannels[channel] = MidiChannelState();
+
 		MidiChannelState &state = _midiChannels[channel];
 		state.volumeCurrent = state.volumeDefault = 0x6400;
 		state.rateCurrent = state.rateDefault = 0x07D0;
 		state.pitchCurrent = state.pitchDefault = 0x1388;
+
 		if (_engineVersion != 3) {
 			state.volumeTarget = state.volumeDefault;
 			state.rateTarget = state.rateDefault;
@@ -444,6 +452,7 @@ void ComfyEngine::midiAddTrackEntry(uint16 channel, uint16 songId, uint16 comple
 	entry.completionKey = completionKey;
 	entry.loadFlag = loadFlag;
 	entry.frameCount = frameCount;
+
 	for (uint i = 0; i < frameCount && i < COMFY_ANIM_FRAME_CAPACITY; i++)
 		entry.frames[i] = frames ? frames[i] : 0;
 
@@ -500,6 +509,7 @@ void ComfyEngine::musicSetEnabled(byte value) {
 	if (!_animFrameReady || !_animUsesWaveVocCounter || value) {
 		_soundPaused = value != 0;
 		_mixer->pauseHandle(_soundHandle, _soundPaused);
+
 		if (_midiPlyrDriver)
 			_midiPlyrDriver->setIncreaseVocCounter(_soundPaused ? 0 : 1);
 	}
diff --git a/engines/comfy/midiplyr/midiplyr.cpp b/engines/comfy/midiplyr/midiplyr.cpp
index 9dc0feccba6..a09396bcda8 100644
--- a/engines/comfy/midiplyr/midiplyr.cpp
+++ b/engines/comfy/midiplyr/midiplyr.cpp
@@ -141,8 +141,7 @@ bool MidiPlyrDriver::musicStart(byte flags) {
 	midiFreeAllChannels();
 
 	if ((flags & 2) == 0) {
-		_timerInstalled = g_system->getTimerManager()->installTimerProc(
-			&timerProc, MIDIPLYR_TIMER_PERIOD, this, "Comfy::MidiPlyrDriver");
+		_timerInstalled = g_system->getTimerManager()->installTimerProc(&timerProc, MIDIPLYR_TIMER_PERIOD, this, "Comfy::MidiPlyrDriver");
 
 		if (!_timerInstalled) {
 			midiClose();
@@ -410,10 +409,11 @@ void MidiPlyrDriver::musicPlaySong(const byte *data, uint32 size, uint16 trackIn
 	track.midiLoopFlag = 0;
 	track.eventDataSize = READ_LE_UINT16(data + 4);
 
-	if (_midiFileFormat == 1)
+	if (_midiFileFormat == 1) {
 		_ticksPerQuarter = READ_LE_UINT16(data + 2);
-	else
+	} else {
 		musicSetRateInternal(READ_LE_UINT16(data + 2), trackIndex);
+	}
 
 	musicSetPitchInternal(5000, trackIndex);
 	track.startTick = _seqCurrentTick;
@@ -818,7 +818,7 @@ void MidiPlyrDriver::comfyboardPollTimer() {
 		return;
 
 	if (!_comfyboardSleepUseStopped && !_comfyboardSampleIndex) {
-		// The original saves the LPT control byte, writes 0x0C to port + 2, and writes 1 to the data port.
+		// The original saves the LPT control byte, writes 0x0C to port + 2, and writes 1 to the data port
 		_comfyboardSavedControl = 0;
 	}
 
@@ -843,7 +843,7 @@ void MidiPlyrDriver::comfyboardPollTimer() {
 		return;
 	}
 
-	// The original writes ((_comfyboardSampleIndex << 1) | 1) to the LPT data port here.
+	// The original writes ((_comfyboardSampleIndex << 1) | 1) to the LPT data port here
 	_comfyboardSampleIndex++;
 }
 
diff --git a/engines/comfy/object_file.cpp b/engines/comfy/object_file.cpp
index a0141cada3f..df21a83c9bc 100644
--- a/engines/comfy/object_file.cpp
+++ b/engines/comfy/object_file.cpp
@@ -29,6 +29,7 @@ ComfyEngine::ObjFileCacheRow *ComfyEngine::tileListEvictTail(ObjFile *objectFile
 	ObjFileCacheRow *row = &objectFile->cacheRows[objectFile->tileLruTail];
 	objectFile->tileLruTail = row->previousIndex;
 	objectFile->tileLruTailValid = row->previousValid;
+
 	if (objectFile->tileStatus && row->frameIndex < objectFile->tileStatusCount)
 		objectFile->tileStatus[row->frameIndex] = 0xFFFF;
 
@@ -41,8 +42,10 @@ ComfyEngine::ObjFileCacheRow *ComfyEngine::tileListAlloc(ObjFile *objectFile) {
 
 	ObjFileCacheRow *row = nullptr;
 	uint16 rowIndex = objectFile->currentBlock;
+
 	if (objectFile->currentBlock < objectFile->cacheRowCount) {
 		row = &objectFile->cacheRows[rowIndex];
+
 		if (!objectFile->currentBlock) {
 			objectFile->tileLruTail = rowIndex;
 			objectFile->tileLruTailValid = 1;
@@ -59,6 +62,7 @@ ComfyEngine::ObjFileCacheRow *ComfyEngine::tileListAlloc(ObjFile *objectFile) {
 			row->nextValid = tail->nextValid;
 			row->previousIndex = objectFile->tileLruTail;
 			row->previousValid = 1;
+
 			if (row->nextIndex < objectFile->cacheRowCount) {
 				objectFile->cacheRows[row->nextIndex].previousIndex = rowIndex;
 				objectFile->cacheRows[row->nextIndex].previousValid = 1;
@@ -101,6 +105,7 @@ void ComfyEngine::tileListTouch(ObjFile *objectFile, uint16 index) {
 		row->nextValid = tail->nextValid;
 		row->previousIndex = objectFile->tileLruTail;
 		row->previousValid = 1;
+
 		if (row->nextIndex < objectFile->cacheRowCount) {
 			objectFile->cacheRows[row->nextIndex].previousIndex = index;
 			objectFile->cacheRows[row->nextIndex].previousValid = 1;
@@ -117,12 +122,14 @@ uint16 ComfyEngine::tileListTouchRange(ObjFile *objectFile, uint16 first, uint16
 
 	uint16 removed = 0;
 	uint16 row = first;
+
 	while (row <= last && row < objectFile->tileStatusCount && objectFile->tileStatus[row] != 0xFFFF) {
 		removed++;
 		row++;
 	}
 
 	row++;
+
 	while (row <= last && row < objectFile->tileStatusCount) {
 		uint16 tile = objectFile->tileStatus[row];
 		if (tile != 0xFFFF) {
@@ -167,17 +174,18 @@ void ComfyEngine::tileCopyXmsPair(ObjFile *objectFile, byte *destination, uint32
 	move.sourceHandle = objectFile->cacheXmsHandle;
 	move.sourceOffset = sourceOffset;
 	move.destinationMemory = destination;
+
 	if (xmsTransfer(move) < 0)
 		error("Unable to read object-file tile from XMS");
 }
 
-uint16 ComfyEngine::tileDrawStrip(ObjFile *objectFile, byte *destination, uint16 cacheRow,
-		uint16 sourceColumn, uint32 width) {
+uint16 ComfyEngine::tileDrawStrip(ObjFile *objectFile, byte *destination, uint16 cacheRow, uint16 sourceColumn, uint32 width) {
 	if (!objectFile || !destination || !objectFile->blockSize)
 		return 0;
 
 	uint16 drawWidth = (uint16)width;
 	uint16 remainingColumns = (uint16)(objectFile->blockSize - sourceColumn);
+
 	if (remainingColumns < drawWidth)
 		drawWidth = remainingColumns;
 
@@ -185,6 +193,7 @@ uint16 ComfyEngine::tileDrawStrip(ObjFile *objectFile, byte *destination, uint16
 	tileCopyXmsPair(objectFile, destination, sourceOffset, drawWidth);
 	tileListTouch(objectFile, cacheRow);
 	_stripsDrawn++;
+
 	return drawWidth;
 }
 
@@ -223,6 +232,7 @@ void ComfyEngine::objFileReadRow(byte *destination, uint16 row, uint16 count, ui
 		return;
 
 	uint32 total = (uint32)size * count;
+
 	if (total == 0x10000) {
 		objectFile->stream->read(destination, size);
 		objectFile->stream->read(destination + size, (uint32)size * (count - 1));
@@ -243,12 +253,13 @@ void ComfyEngine::objFileReadFieldCore(byte *destination, uint32 sourceOffset, u
 	uint16 column = (uint16)(sourceOffset % objectFile->blockSize);
 	byte *output = destination;
 	uint32 remaining = byteCount;
+
 	tileListTouchRange(objectFile, firstRow, lastRow);
 
 	while (row <= lastRow && remaining) {
 		uint16 copied = 0;
-		if (row < objectFile->tileStatusCount && objectFile->tileStatus[row] == 0xFFFF &&
-				(_isPanther || _engineVersion == 3))
+
+		if (row < objectFile->tileStatusCount && objectFile->tileStatus[row] == 0xFFFF && (_isPanther || _engineVersion == 3))
 			frameLoaderLoadTile(objectFile, row);
 
 		if (row < objectFile->tileStatusCount && objectFile->tileStatus[row] != 0xFFFF) {
@@ -256,8 +267,8 @@ void ComfyEngine::objFileReadFieldCore(byte *destination, uint32 sourceOffset, u
 		} else {
 			uint16 missingRows = 0;
 			uint16 probe = row;
-			while (probe <= lastRow && probe < objectFile->tileStatusCount &&
-					objectFile->tileStatus[probe] == 0xFFFF) {
+
+			while (probe <= lastRow && probe < objectFile->tileStatusCount && objectFile->tileStatus[probe] == 0xFFFF) {
 				if ((uint32)(missingRows + 1) * objectFile->blockSize > 0x10000)
 					break;
 
@@ -274,9 +285,11 @@ void ComfyEngine::objFileReadFieldCore(byte *destination, uint32 sourceOffset, u
 				return;
 
 			objFileReadRow(readDestination, row, missingRows, objectFile->blockSize, objectFile);
+
 			for (uint16 i = 0; i < missingRows; i++) {
 				byte *tileSource = readDestination + (uint32)i * objectFile->blockSize;
 				uint16 size = objectFile->blockSize;
+
 				if (bounce) {
 					size = objectFile->blockSize - column;
 					if (size > remaining)
@@ -358,6 +371,7 @@ byte *ComfyEngine::objFileReadTiledCore(uint32 sourceOffset, uint32 byteCount, O
 	tileListTouchRange(objectFile, firstRow, lastRow);
 	uint16 missing = 0;
 	uint16 row = firstRow;
+
 	while (row <= lastRow && row < objectFile->tileStatusCount && objectFile->tileStatus[row] == 0xFFFF) {
 		missing++;
 		row++;
@@ -368,12 +382,14 @@ byte *ComfyEngine::objFileReadTiledCore(uint32 sourceOffset, uint32 byteCount, O
 
 	if (missing) {
 		objFileReadRow(objectFile->readBuffer, firstRow, missing, blockSize, objectFile);
+
 		for (uint16 i = 0; i < missing; i++)
 			tileLoadAndCache(objectFile, objectFile->readBuffer + (uint32)i * blockSize, (uint16)(firstRow + i));
 	}
 
 	missing = 0;
 	row = lastRow;
+
 	while (row >= firstRow && row < objectFile->tileStatusCount && objectFile->tileStatus[row] == 0xFFFF) {
 		missing++;
 		if (row == firstRow)
@@ -418,13 +434,11 @@ byte *ComfyEngine::frameLoaderReadFrameData(uint32 sourceOffset, uint32 byteCoun
 	if (!data)
 		return nullptr;
 
-	objFileReadFieldCore(objectFile->readBuffer + 0x10000, sourceOffset + 0x10000,
-		byteCount - 0x10000, objectFile);
+	objFileReadFieldCore(objectFile->readBuffer + 0x10000, sourceOffset + 0x10000, byteCount - 0x10000, objectFile);
 	return data;
 }
 
-ComfyEngine::ObjFile *ComfyEngine::objFileOpen(const Common::Path &path, uint16 blockSize,
-		uint32 maximumBytes) {
+ComfyEngine::ObjFile *ComfyEngine::objFileOpen(const Common::Path &path, uint16 blockSize, uint32 maximumBytes) {
 	Common::SeekableReadStream *stream = pathFOpen(path, true);
 	if (!stream || stream->size() < 0 || (uint64)stream->size() > UINT32_MAX || !blockSize) {
 		delete stream;
@@ -456,9 +470,9 @@ ComfyEngine::ObjFile *ComfyEngine::objFileOpen(const Common::Path &path, uint16
 	objectFile->tileReadBuffer = (byte *)malloc(blockSize);
 	objectFile->tileStatus = (uint16 *)malloc((fileBlocks ? fileBlocks : 1) * sizeof(uint16));
 	objectFile->cacheRows = (ObjFileCacheRow *)malloc((cacheRows ? cacheRows : 1) * sizeof(ObjFileCacheRow));
+
 	int32 cacheHandle = memAllocTrack((uint16)(cachePages + 1));
-	if (!objectFile->readBuffer || !objectFile->tileReadBuffer || !objectFile->tileStatus ||
-			!objectFile->cacheRows || cacheHandle < 0) {
+	if (!objectFile->readBuffer || !objectFile->tileReadBuffer || !objectFile->tileStatus || !objectFile->cacheRows || cacheHandle < 0) {
 		if (cacheHandle >= 0)
 			memFreeTrack((uint16)cacheHandle);
 
diff --git a/engines/comfy/palette.cpp b/engines/comfy/palette.cpp
index b7c68e976c5..daba62fead9 100644
--- a/engines/comfy/palette.cpp
+++ b/engines/comfy/palette.cpp
@@ -43,6 +43,7 @@ void ComfyEngine::colorDatClose() {
 void ComfyEngine::colorDatReadEntry(uint16 paletteId) {
 	colorDatOpen();
 	uint16 offset = (uint16)(paletteId * COMFY_PALETTE_BYTES);
+
 	if (!_colorDatStream->seek(offset))
 		error("Could not seek to palette %u in COLORS.DAT", (uint)paletteId);
 
@@ -79,6 +80,7 @@ void ComfyEngine::paletteFadeStep(uint16 delta) {
 		return;
 
 	_fadeStep = (uint16)(_fadeStep + delta);
+
 	if ((int16)_fadeStep >= (int16)_fadeMax) {
 		_fadeStep = _fadeMax;
 		memcpy(_paletteFadeSource, _paletteTarget, COMFY_PALETTE_BYTES);
@@ -94,7 +96,7 @@ void ComfyEngine::paletteFadeStep(uint16 delta) {
 void ComfyEngine::paletteLoadWithFade(uint16 paletteId, uint16 fadeTicks) {
 	colorDatReadEntry(paletteId);
 	if (_engineVersion != 3)
-		_palettePage = 'S';
+		_palettePage = 83;
 
 	if (_paletteFading)
 		memcpy(_paletteFadeSource, _paletteDisplay, COMFY_PALETTE_BYTES);
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index 5264ec5775b..b2d570925d0 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -51,19 +51,22 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 	WRITE_LE_UINT32(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x184], _midiInstanceTrackBase);
 	WRITE_LE_UINT16(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x188], _midiEvents.count);
 	WRITE_LE_UINT16(&_sceneMemoryBlock[_sceneMidiInstanceOffset + 0x18A], _midiTracks.count);
+
 	if (_engineVersion == 3) {
 		byte *vocState = &_sceneMemoryBlock[_sceneMidiInstanceOffset + COMFY_SCENE_MIDI_INSTANCE_BYTES];
 		vocState[0] = _v3SceneWaveBalancePercent;
-		vocState[1] = _v3SceneHostMediaModeEnabled;
+		vocState[1] = _v3SceneMediaModeEnabled;
 		vocState[2] = _v3SceneWaveLeftPercent;
 		vocState[3] = _v3SceneWaveRightPercent;
 		vocState[6] = _v3SceneMixerVolumePercent;
+
 		for (uint i = 0; i < COMFY_VOC_QUEUE_CAPACITY; i++) {
 			byte *packedEntry = vocState + 7 + i * 0x1F;
 			VocQueueEntryV3 &entry = _vocQueueV3[i];
 			WRITE_LE_UINT16(packedEntry, entry.soundId);
 			WRITE_LE_UINT16(packedEntry + 2, entry.argumentCount);
 			WRITE_LE_UINT16(packedEntry + 4, entry.state);
+
 			for (uint argument = 0; argument < COMFY_VOC_ARG_CAPACITY_V3; argument++)
 				WRITE_LE_UINT16(packedEntry + 6 + argument * 2, entry.arguments[argument]);
 
@@ -74,12 +77,14 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 		WRITE_LE_UINT16(vocState + 0x1F9, _soundEventMaximum);
 	} else if (_isPanther) {
 		byte *soundState = &_sceneMemoryBlock[_sceneSoundStateOffset];
+
 		for (uint i = 0; i < COMFY_PANTHER_VOC_QUEUE_CAPACITY; i++) {
 			byte *packedEntry = soundState + i * 0x1A;
 			VocQueueEntry &entry = _vocQueue[i];
 			WRITE_LE_UINT16(packedEntry, entry.soundId);
 			WRITE_LE_UINT16(packedEntry + 2, entry.argumentCount);
 			WRITE_LE_UINT16(packedEntry + 4, entry.state);
+
 			for (uint argument = 0; argument < COMFY_VOC_ARG_CAPACITY; argument++)
 				WRITE_LE_UINT16(packedEntry + 6 + argument * 2, entry.arguments[argument]);
 		}
@@ -93,6 +98,7 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 	sceneEntries[0] = _sceneEntryListActive;
 	WRITE_LE_UINT16(sceneEntries + 1, _sceneEntryCount);
 	WRITE_LE_UINT16(sceneEntries + 3, _sceneEntryFrameSize);
+
 	for (uint i = 0; i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
 		WRITE_LE_UINT16(sceneEntries + 5 + i * 2, (uint16)_sceneEntryOffsets[i]);
 
@@ -107,6 +113,7 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
 		MidiChannelState &state = _midiChannels[channel];
 		byte *packed = sceneEntries + channelTableOffset + channel * 0xA1;
+
 		WRITE_LE_UINT16(packed + 0x87, state.entryCount);
 		WRITE_LE_UINT16(packed + 0x89, state.volumeCurrent);
 		WRITE_LE_UINT16(packed + 0x8B, state.volumeTarget);
@@ -120,12 +127,14 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 		WRITE_LE_UINT16(packed + 0x9B, state.pitchTarget);
 		WRITE_LE_UINT16(packed + 0x9D, state.pitchTicksLeft);
 		WRITE_LE_UINT16(packed + 0x9F, state.pitchDefault);
+
 		for (uint entry = 0; entry < state.entryCount && entry < COMFY_MIDI_TRACK_ENTRY_CAPACITY; entry++) {
 			byte *packedEntry = packed + entry * 0x1B;
 			WRITE_LE_UINT16(packedEntry, state.entries[entry].songId);
 			WRITE_LE_UINT16(packedEntry + 2, state.entries[entry].completionKey);
 			packedEntry[4] = state.entries[entry].loadFlag;
 			WRITE_LE_UINT16(packedEntry + 5, state.entries[entry].frameCount);
+
 			for (uint frame = 0; frame < COMFY_ANIM_FRAME_CAPACITY; frame++)
 				WRITE_LE_UINT16(packedEntry + 7 + frame * 2, state.entries[entry].frames[frame]);
 		}
@@ -139,10 +148,12 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 		memcpy(&_sceneMemoryBlock[_sceneHandlesOffset], &_sceneHandles[0], _sceneHandles.size() * sizeof(uint16));
 
 	uint32 actorStride = COMFY_ACTOR_SIZE_V3;
-	if (_engineVersion == 1)
+
+	if (_engineVersion == 1) {
 		actorStride = COMFY_ACTOR_SIZE_V1;
-	else if (_engineVersion == 2)
+	} else if (_engineVersion == 2) {
 		actorStride = COMFY_ACTOR_SIZE_V2;
+	}
 
 	byte *actorBuffer = (byte *)malloc(actorStride);
 	if (!actorBuffer)
@@ -152,6 +163,7 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 		byte *destination = &_sceneMemoryBlock[_sceneActorsOffset + i * actorStride];
 		Actor &actor = _actors[i];
 		Common::MemoryWriteStream actorStream(actorBuffer, actorStride);
+
 		actorStream.writeUint32LE(actor.currentPc);
 		actorStream.writeUint32LE(actor.callPc);
 		actorStream.writeUint32LE(actor.resetPc);
@@ -184,13 +196,16 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 		actorStream.writeSint16LE(actor.cachedRect.top);
 		actorStream.writeSint16LE(actor.cachedRect.right);
 		actorStream.writeSint16LE(actor.cachedRect.bottom);
-		if (_engineVersion == 1)
+
+		if (_engineVersion == 1) {
 			actorStream.writeUint16LE((uint16)(actor.cachedRect.area & 0xFFFF));
-		else
+		} else {
 			actorStream.writeUint32LE(actor.cachedRect.area);
+		}
 
 		actorStream.writeByte(actor.cachedVisible);
 		actorStream.writeUint32LE(actor.cachedSprite);
+
 		if (_engineVersion == 3)
 			actorStream.writeByte(actor.blitHitMouse);
 
@@ -221,6 +236,7 @@ void ComfyEngine::environmentPackToXms(byte *source, uint16 index) {
 	move.destinationHandle = _xmsEnvHandle;
 	move.destinationOffset = (uint32)(index - 1) * _sceneMemoryBlock.size();
 	move.sourceMemory = source;
+
 	if (xmsTransfer(move) < 0)
 		error("Environment XMS destination %u is outside the allocated block", (uint)index);
 }
@@ -234,6 +250,7 @@ bool ComfyEngine::environmentUnpackFromXms(byte *destination, uint16 index) {
 	move.sourceHandle = _xmsEnvHandle;
 	move.sourceOffset = (uint32)(index - 1) * _sceneMemoryBlock.size();
 	move.destinationMemory = destination;
+
 	if (xmsTransfer(move) < 0)
 		error("Environment XMS source %u is outside the allocated block", (uint)index);
 
@@ -262,19 +279,22 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 	_midiTracks.baseTime = _midiInstanceTrackBase;
 	midiFindNext(_midiEvents);
 	midiFindNext(_midiTracks);
+
 	if (_engineVersion == 3) {
 		byte *vocState = &_sceneMemoryBlock[_sceneMidiInstanceOffset + COMFY_SCENE_MIDI_INSTANCE_BYTES];
 		_v3SceneWaveBalancePercent = vocState[0];
-		_v3SceneHostMediaModeEnabled = vocState[1];
+		_v3SceneMediaModeEnabled = vocState[1];
 		_v3SceneWaveLeftPercent = vocState[2];
 		_v3SceneWaveRightPercent = vocState[3];
 		_v3SceneMixerVolumePercent = vocState[6];
+
 		for (uint i = 0; i < COMFY_VOC_QUEUE_CAPACITY; i++) {
 			byte *packedEntry = vocState + 7 + i * 0x1F;
 			VocQueueEntryV3 &entry = _vocQueueV3[i];
 			entry.soundId = READ_LE_UINT16(packedEntry);
 			entry.argumentCount = MIN<uint16>(READ_LE_UINT16(packedEntry + 2), COMFY_VOC_ARG_CAPACITY_V3);
 			entry.state = READ_LE_UINT16(packedEntry + 4);
+
 			for (uint argument = 0; argument < COMFY_VOC_ARG_CAPACITY_V3; argument++)
 				entry.arguments[argument] = READ_LE_UINT16(packedEntry + 6 + argument * 2);
 
@@ -285,12 +305,14 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 		_soundEventMaximum = READ_LE_UINT16(vocState + 0x1F9) % COMFY_VOC_QUEUE_CAPACITY;
 	} else if (_isPanther) {
 		byte *soundState = &_sceneMemoryBlock[_sceneSoundStateOffset];
+
 		for (uint i = 0; i < COMFY_PANTHER_VOC_QUEUE_CAPACITY; i++) {
 			byte *packedEntry = soundState + i * 0x1A;
 			VocQueueEntry &entry = _vocQueue[i];
 			entry.soundId = READ_LE_UINT16(packedEntry);
 			entry.argumentCount = MIN<uint16>(READ_LE_UINT16(packedEntry + 2), COMFY_VOC_ARG_CAPACITY);
 			entry.state = READ_LE_UINT16(packedEntry + 4);
+
 			for (uint argument = 0; argument < COMFY_VOC_ARG_CAPACITY; argument++)
 				entry.arguments[argument] = READ_LE_UINT16(packedEntry + 6 + argument * 2);
 		}
@@ -304,6 +326,7 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 	_sceneEntryListActive = sceneEntries[0] != 0;
 	_sceneEntryCount = READ_LE_UINT16(sceneEntries + 1);
 	_sceneEntryFrameSize = READ_LE_UINT16(sceneEntries + 3);
+
 	for (uint i = 0; i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
 		_sceneEntryOffsets[i] = READ_LE_UINT16(sceneEntries + 5 + i * 2);
 
@@ -315,6 +338,7 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 	}
 
 	uint32 channelTableOffset = _engineVersion == 3 || _isPanther ? 0x3D : 0x25;
+
 	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++) {
 		MidiChannelState &state = _midiChannels[channel];
 		byte *packed = sceneEntries + channelTableOffset + channel * 0xA1;
@@ -331,24 +355,30 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 		state.pitchTarget = READ_LE_UINT16(packed + 0x9B);
 		state.pitchTicksLeft = READ_LE_UINT16(packed + 0x9D);
 		state.pitchDefault = READ_LE_UINT16(packed + 0x9F);
+
 		for (uint entry = 0; entry < state.entryCount; entry++) {
 			byte *packedEntry = packed + entry * 0x1B;
 			state.entries[entry].songId = READ_LE_UINT16(packedEntry);
 			state.entries[entry].completionKey = READ_LE_UINT16(packedEntry + 2);
 			state.entries[entry].loadFlag = packedEntry[4];
 			state.entries[entry].frameCount = READ_LE_UINT16(packedEntry + 5);
+
 			for (uint frame = 0; frame < COMFY_ANIM_FRAME_CAPACITY; frame++)
 				state.entries[entry].frames[frame] = READ_LE_UINT16(packedEntry + 7 + frame * 2);
 		}
 	}
+
 	memcpy(_actorPcTable, &_sceneMemoryBlock[_sceneActorPcOffset], sizeof(_actorPcTable));
 	memcpy(&_stringTable[0], &_sceneMemoryBlock[_sceneStringTableOffset], _stringTable.size() * sizeof(uint16));
 	memcpy(&_sceneHandles[0], &_sceneMemoryBlock[_sceneHandlesOffset], _sceneHandles.size() * sizeof(uint16));
+
 	uint32 actorStride = COMFY_ACTOR_SIZE_V3;
-	if (_engineVersion == 1)
+
+	if (_engineVersion == 1) {
 		actorStride = COMFY_ACTOR_SIZE_V1;
-	else if (_engineVersion == 2)
+	} else if (_engineVersion == 2) {
 		actorStride = COMFY_ACTOR_SIZE_V2;
+	}
 
 	byte *actorBuffer = (byte *)malloc(actorStride);
 	if (!actorBuffer)
@@ -360,6 +390,7 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 		actor = Actor();
 		memcpy(actorBuffer, source, actorStride);
 		Common::MemoryReadStream actorStream(actorBuffer, actorStride);
+
 		actor.currentPc = actorStream.readUint32LE();
 		actor.callPc = actorStream.readUint32LE();
 		actor.resetPc = actorStream.readUint32LE();
@@ -392,13 +423,16 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 		actor.cachedRect.top = actorStream.readSint16LE();
 		actor.cachedRect.right = actorStream.readSint16LE();
 		actor.cachedRect.bottom = actorStream.readSint16LE();
-		if (_engineVersion == 1)
+
+		if (_engineVersion == 1) {
 			actor.cachedRect.area = actorStream.readUint16LE();
-		else
+		} else {
 			actor.cachedRect.area = actorStream.readUint32LE();
+		}
 
 		actor.cachedVisible = actorStream.readByte();
 		actor.cachedSprite = actorStream.readUint32LE();
+
 		if (_engineVersion == 3)
 			actor.blitHitMouse = actorStream.readByte();
 
@@ -426,6 +460,7 @@ void ComfyEngine::sceneEntryInit(uint16 count) {
 	_sceneEntryCount = count;
 	uint32 frameSize = _engineVersion == 3 ? COMFY_SCENE_FRAME_BYTES_V3 : COMFY_SCENE_FRAME_BYTES;
 	_sceneEntryFrameSize = count ? frameSize / (int16)count : 0;
+
 	for (uint i = 0; i < count && i < COMFY_SCENE_ENTRY_OFFSET_CAPACITY; i++)
 		_sceneEntryOffsets[i] = 0xFFFF;
 
@@ -447,6 +482,7 @@ void ComfyEngine::sceneEntryStop() {
 void ComfyEngine::sceneStartWithMusic(uint16 scene) {
 	byte keySnapshot[15];
 	memset(keySnapshot, 0, sizeof(keySnapshot));
+
 	if (_keyBits)
 		memcpy(keySnapshot, _keyBits, MIN<uint32>(sizeof(keySnapshot), _keyBitsSize));
 
@@ -465,6 +501,7 @@ void ComfyEngine::sceneStartWithMusic(uint16 scene) {
 	Actor *root = actorGetPtr(0);
 	if (root) {
 		paletteLoadWithFade((uint16)root->xFixed, 0);
+
 		if (root->yFixed)
 			paletteApplyBrightness((byte)root->yFixed);
 	}
@@ -480,15 +517,17 @@ bool ComfyEngine::sceneEntryLoad(uint16 descriptor, uint16 index) {
 	byte header[6];
 	memset(header, 0, sizeof(header));
 	sceneEntryReadFromXms(header, descriptor, sizeof(header));
+
 	uint16 size = READ_LE_UINT16(header);
 	uint32 fileOffset = READ_LE_UINT32(header + 2);
 	uint32 destinationOffset = (uint32)_sceneEntryFrameSize * index;
-	if (!_midiFileStream || destinationOffset > _sceneFrameData.size() ||
-			size > _sceneFrameData.size() - destinationOffset || !_midiFileStream->seek(fileOffset))
+
+	if (!_midiFileStream || destinationOffset > _sceneFrameData.size() || size > _sceneFrameData.size() - destinationOffset || !_midiFileStream->seek(fileOffset))
 		return false;
 
 	if (_midiFileStream->read(&_sceneFrameData[destinationOffset], size) != size)
 		return false;
+
 	if (index < COMFY_SCENE_ENTRY_OFFSET_CAPACITY)
 		_sceneEntryOffsets[index] = descriptor;
 
@@ -501,10 +540,12 @@ void ComfyEngine::sceneEntryReadFromXms(byte *destination, uint16 row, uint16 si
 
 byte *ComfyEngine::sceneFrameGetPtr(uint16 kind, uint16 size) {
 	byte *result = nullptr;
-	if (kind == 0 && !_sceneFrameData.empty())
+
+	if (kind == 0 && !_sceneFrameData.empty()) {
 		result = &_sceneFrameData[0];
-	else if (kind == 1 && size <= _sceneFrameData.size())
+	} else if (kind == 1 && size <= _sceneFrameData.size()) {
 		result = &_sceneFrameData[_sceneFrameData.size() - size];
+	}
 
 	if (result && kind < COMFY_MIDI_CHANNEL_COUNT)
 		_midiChannels[kind].loadedFrameSize = size;
@@ -518,12 +559,12 @@ byte *ComfyEngine::spriteLoadFromFile(uint16 fileOffset, uint16 index) {
 	sceneEntryReadFromXms(header, fileOffset, sizeof(header));
 	uint16 size = READ_LE_UINT16(header);
 	uint32 position = READ_LE_UINT32(header + 2);
+
 	if (!size)
 		return nullptr;
 
 	byte *destination = sceneFrameGetPtr(index, size);
-	if (!destination || !_midiFileStream || !_midiFileStream->seek(position) ||
-			_midiFileStream->read(destination, size) != size) {
+	if (!destination || !_midiFileStream || !_midiFileStream->seek(position) || _midiFileStream->read(destination, size) != size) {
 		if (index < COMFY_MIDI_CHANNEL_COUNT)
 			_midiChannels[index].loadedFrameSize = 0;
 
@@ -540,17 +581,19 @@ void ComfyEngine::midiStopSong(uint16 channel) {
 
 void ComfyEngine::midiPlaySongAtFrame(uint16 channel, uint16 frame) {
 	midiStopSong(channel);
+
 	uint32 offset = (uint32)_sceneEntryFrameSize * frame;
-	if (!_midiPlyrDriver || channel >= COMFY_SCENE_MUSIC_CHANNEL_COUNT ||
-			offset > _sceneFrameData.size() || 6 > _sceneFrameData.size() - offset)
+	if (!_midiPlyrDriver || channel >= COMFY_SCENE_MUSIC_CHANNEL_COUNT || offset > _sceneFrameData.size() || 6 > _sceneFrameData.size() - offset)
 		return;
 
 	byte *song = &_sceneFrameData[offset];
 	uint16 size = READ_LE_UINT16(song + 4) + 6;
+
 	if (size > _sceneFrameData.size() - offset)
 		return;
 
 	_midiPlyrDriver->musicPlaySong(song, size, channel);
+
 	if (_engineVersion == 3 || _isPanther) {
 		_midiPlyrDriver->musicSetVolume(_sceneEntryVolumes[channel], channel);
 		_sceneEntryCompletionKeys[channel] = 0;
@@ -574,6 +617,7 @@ bool ComfyEngine::sceneOpen(uint32 sceneEntryListOffset) {
 	_sceneEntryCount = 0;
 	uint32 frameSize = _engineVersion == 3 ? COMFY_SCENE_FRAME_BYTES_V3 : COMFY_SCENE_FRAME_BYTES;
 	_sceneEntryFrameSize = frameSize;
+
 	if (_sceneFrameData.empty()) {
 		_sceneFrameData.resize(frameSize);
 		memset(&_sceneFrameData[0], 0, _sceneFrameData.size());
@@ -585,8 +629,7 @@ bool ComfyEngine::sceneOpen(uint32 sceneEntryListOffset) {
 		return false;
 
 	byte header[4];
-	if (_midiFileStream->read(header, sizeof(header)) != sizeof(header) ||
-			header[0] != 'C' || (header[1] != 'M' && header[1] != 'm'))
+	if (_midiFileStream->read(header, sizeof(header)) != sizeof(header) || header[0] != 'C' || (header[1] != 'M' && header[1] != 'm'))
 		return false;
 
 	_midiFileMode = header[1] == 'm' ? 1 : 0;
@@ -608,6 +651,7 @@ void ComfyEngine::sceneShutdown() {
 	delete _midiFileStream;
 	_midiFileStream = nullptr;
 	_sceneFrameData.clear();
+
 	if (_engineVersion == 3) {
 		_v3SceneWaveLeftPercent = 0xFF;
 		_v3SceneWaveRightPercent = 0xFF;
diff --git a/engines/comfy/script.cpp b/engines/comfy/script.cpp
index 0b3e6e58abc..87153732acd 100644
--- a/engines/comfy/script.cpp
+++ b/engines/comfy/script.cpp
@@ -34,6 +34,7 @@ byte ComfyEngine::scriptReadByte(uint32 pc) {
 
 	SpriteResource *sprite = spriteGetPtr(spriteId);
 	uint16 frameId = (uint16)-spriteId;
+
 	if (!sprite || frameId >= _frameCacheEntries.size()) {
 		_scriptFault = true;
 		return 0;
@@ -41,6 +42,7 @@ byte ComfyEngine::scriptReadByte(uint32 pc) {
 
 	SpriteCacheEntry &entry = _frameCacheEntries[frameId];
 	uint32 offset = entry.poolOffset + 0x0C + tileOffset;
+
 	if (entry.slotSize == 0xFFFF || offset >= _scenePoolData.size()) {
 		_scriptFault = true;
 		return 0;
@@ -56,6 +58,7 @@ uint16 ComfyEngine::scriptReadWord(uint32 pc) {
 
 	SpriteResource *sprite = spriteGetPtr(spriteId);
 	uint16 frameId = (uint16)-spriteId;
+
 	if (!sprite || frameId >= _frameCacheEntries.size()) {
 		_scriptFault = true;
 		return 0;
@@ -63,6 +66,7 @@ uint16 ComfyEngine::scriptReadWord(uint32 pc) {
 
 	SpriteCacheEntry &entry = _frameCacheEntries[frameId];
 	uint32 offset = entry.poolOffset + 0x0C + tileOffset;
+
 	if (entry.slotSize == 0xFFFF || offset > _scenePoolData.size() || 2 > _scenePoolData.size() - offset) {
 		_scriptFault = true;
 		return 0;
@@ -78,6 +82,7 @@ uint32 ComfyEngine::scriptReadDword(uint32 pc) {
 
 	SpriteResource *sprite = spriteGetPtr(spriteId);
 	uint16 frameId = (uint16)-spriteId;
+
 	if (!sprite || frameId >= _frameCacheEntries.size()) {
 		_scriptFault = true;
 		return 0;
@@ -85,6 +90,7 @@ uint32 ComfyEngine::scriptReadDword(uint32 pc) {
 
 	SpriteCacheEntry &entry = _frameCacheEntries[frameId];
 	uint32 offset = entry.poolOffset + 0x0C + tileOffset;
+
 	if (entry.slotSize == 0xFFFF || offset > _scenePoolData.size() || 4 > _scenePoolData.size() - offset) {
 		_scriptFault = true;
 		return 0;
@@ -95,6 +101,7 @@ uint32 ComfyEngine::scriptReadDword(uint32 pc) {
 
 uint16 ComfyEngine::scriptReadStringIndex(uint32 pc) {
 	uint16 value = scriptReadWord(pc);
+
 	if (value >= 30000) {
 		uint32 index = value - 30000;
 		if (index < _stringTable.size())
@@ -107,6 +114,7 @@ uint16 ComfyEngine::scriptReadStringIndex(uint32 pc) {
 uint32 ComfyEngine::scriptReadArgs(uint32 pc, uint16 fallbackActor, const char *format, ...) {
 	va_list args;
 	va_start(args, format);
+
 	for (char type = *format; type; type = *++format) {
 		if (type == 'C') {
 			byte *value = va_arg(args, byte *);
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 7089f67cc32..d5a822028ee 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -944,25 +944,25 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 				break;
 			case SO_HOST_MEDIA_STOP_INPUT:
 				setMediaMode(subop);
-				_v3HostMediaRecording = false;
+				_v3MediaRecording = false;
 				break;
 			case SO_HOST_MEDIA_START_RECORDING_2_ARGS:
 			case SO_HOST_MEDIA_START_RECORDING_3_ARGS:
 			case SO_HOST_MEDIA_START_RECORDING_4_ARGS:
-				_v3HostMediaRecordingArg0 = scriptReadStringIndex(pc);
-				_v3HostMediaRecordingArg1 = scriptReadWord(pc + 2);
+				_v3MediaRecordingArg0 = scriptReadStringIndex(pc);
+				_v3MediaRecordingArg1 = scriptReadWord(pc + 2);
 				pc += 4;
-				_v3HostMediaRecording = true;
-				if (!_v3SceneHostMediaModeEnabled)
+				_v3MediaRecording = true;
+				if (!_v3SceneMediaModeEnabled)
 					setMediaMode(SO_HOST_MEDIA_START_INPUT);
 
 				if (subop != SO_HOST_MEDIA_START_RECORDING_2_ARGS) {
-					_v3HostMediaRecordingArg2 = scriptReadStringIndex(pc);
+					_v3MediaRecordingArg2 = scriptReadStringIndex(pc);
 					pc += 2;
 				}
 
 				if (subop == SO_HOST_MEDIA_START_RECORDING_4_ARGS) {
-					_v3HostMediaRecordingArg3 = scriptReadStringIndex(pc);
+					_v3MediaRecordingArg3 = scriptReadStringIndex(pc);
 					pc += 2;
 				}
 
@@ -1274,7 +1274,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 				if (argument <= 4) {
 					condition = _inputDeviceMode == argument;
 				} else if (argument == 20) {
-					condition = _v3HostMediaRecording;
+					condition = _v3MediaRecording;
 				} else if (argument == 30) {
 					Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(Common::Path("comfy.htm"), true));
 					condition = (bool)stream;
diff --git a/engines/comfy/sound.cpp b/engines/comfy/sound.cpp
index 01c3de9c9f1..8db112b26c7 100644
--- a/engines/comfy/sound.cpp
+++ b/engines/comfy/sound.cpp
@@ -36,7 +36,7 @@ namespace Comfy {
 struct SoundDecoderState {
 public:
 	// soundPrepareDecoderState() collects an embedded ANM sound into one temporary buffer.
-	// This constructor copies those bytes, so decoding no longer needs the engine or a file.
+	// This constructor copies those bytes, so decoding no longer needs the engine or a file...
 	SoundDecoderState(const byte *data, uint32 size, bool compressed) {
 		_data.resize(size);
 		if (size)
@@ -45,6 +45,7 @@ public:
 		_compressed = compressed;
 		_end = size;
 		_windowEnd = size;
+
 		if (_compressed) {
 			if (size < 5) {
 				_fault = true;
@@ -62,13 +63,13 @@ public:
 
 	// A regular VOC entry remains in VOCFILE.DAT. This constructor retains the engine and
 	// file object so loadSourceWindow() can read each block through objFileReadTiledCore().
-	SoundDecoderState(ComfyEngine *engine, ComfyEngine::ObjFile *objectFile,
-			uint32 sourceBase, uint32 size, bool compressed) {
+	SoundDecoderState(ComfyEngine *engine, ComfyEngine::ObjFile *objectFile, uint32 sourceBase, uint32 size, bool compressed) {
 		_engine = engine;
 		_objectFile = objectFile;
 		_sourceBase = sourceBase;
 		_compressed = compressed;
 		_end = size;
+
 		if (!loadSourceWindow(6)) {
 			_fault = true;
 			return;
@@ -106,7 +107,9 @@ public:
 		return written;
 	}
 
-	uint32 getRate() { return _sampleRate; }
+	uint32 getRate() {
+		return _sampleRate;
+	}
 
 	void copyCues(Common::Array<ComfyEngine::SoundCue> &cues) {
 		cues = _cues;
@@ -136,6 +139,7 @@ public:
 
 	void packState(byte *packedState, uint16 bufferIndex, uint32 playbackPosition, uint32 vocCounter,
 			bool stopped, bool usesAnimData, Common::Array<ComfyEngine::SoundCue> &cues, uint nextCue) {
+
 		memset(packedState, 0, 0x52);
 		packedState[0x3F] = stopped;
 		if (stopped || bufferIndex >= 2)
@@ -150,8 +154,8 @@ public:
 		WRITE_LE_UINT32(packedState + 0x0D, playbackPosition);
 		WRITE_LE_UINT32(packedState + 0x11, vocCounter);
 		uint16 packedCueCount = 0;
-		while (nextCue < cues.size() && packedCueCount < 4 &&
-				cues[nextCue].streamPosition < playbackPosition) {
+
+		while (nextCue < cues.size() && packedCueCount < 4 && cues[nextCue].streamPosition < playbackPosition) {
 			WRITE_LE_UINT16(packedState + 0x15 + packedCueCount * 2, cues[nextCue].value);
 			WRITE_LE_UINT32(packedState + 0x1D + packedCueCount * 4, cues[nextCue].streamPosition);
 			WRITE_LE_UINT32(packedState + 0x2D + packedCueCount * 4, cues[nextCue].counterThreshold);
@@ -184,6 +188,7 @@ public:
 		_position = READ_LE_UINT32(packedState + 0x41);
 		_loopPosition = READ_LE_UINT32(packedState + 0x45);
 		uint32 packedEnd = READ_LE_UINT32(packedState + 0x49);
+
 		if (_position > _end || _loopPosition > _end || packedEnd > _end)
 			return false;
 
@@ -194,6 +199,7 @@ public:
 		_fault = false;
 		_finished = false;
 		_cues.clear();
+
 		uint16 advanceSize = (uint16)(playbackPosition - _streamPosition);
 		if (advanceSize > COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES)
 			advanceSize = COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES;
@@ -201,6 +207,7 @@ public:
 		if (advanceSize) {
 			Common::Array<byte> discardedPcm;
 			discardedPcm.resize(advanceSize);
+
 			if (decode(&discardedPcm[0], advanceSize) != advanceSize)
 				return false;
 		}
@@ -208,6 +215,7 @@ public:
 		_cues.clear();
 		cues.clear();
 		uint16 cueCount = MIN<uint16>(READ_LE_UINT16(packedState + 0x3D), 4);
+
 		for (uint16 i = 0; i < cueCount; i++) {
 			ComfyEngine::SoundCue cue;
 			cue.value = READ_LE_UINT16(packedState + 0x15 + i * 2);
@@ -240,6 +248,7 @@ private:
 
 		uint32 remaining = _end - _position;
 		uint32 readSize = MIN<uint32>(size, remaining);
+
 		if (!_compressed)
 			readSize += 0xC8;
 
@@ -279,6 +288,7 @@ private:
 			_position = position;
 			bool loaded = loadSourceWindow(_decodeBlockSize ? _decodeBlockSize : 6);
 			_position = savedPosition;
+
 			if (!loaded) {
 				_fault = true;
 				return 0;
@@ -297,7 +307,7 @@ private:
 	static uint32 calcSampleRate(byte sample) {
 		uint32 denominator = 256 - sample;
 		uint32 rate = denominator ? 1000000 / denominator : 11025;
-		if (rate > 0x2710 && rate < 12000)
+		if (rate > 10000 && rate < 12000)
 			return 11025;
 
 		if (rate > 20000 && rate < 24000)
@@ -374,7 +384,7 @@ private:
 			case 7:
 				if (_loopCount > 0) {
 					_loopCount--;
-					// The original reloads the loop position twice.
+					// The original reloads the loop position twice...
 					seekToLoop();
 					seekToLoop();
 				}
@@ -393,6 +403,7 @@ private:
 	void seekToLoop() {
 		_position = _loopPosition;
 		_bitOffset = _loopBitOffset;
+
 		if (_objectFile && !loadSourceWindow(_decodeBlockSize))
 			_fault = true;
 	}
@@ -503,6 +514,7 @@ private:
 
 				if (_bitWidth && readBits(1))
 					_predictorDistance = (byte)readBits(7);
+
 				_blockOffset = 0;
 			}
 
@@ -513,8 +525,7 @@ private:
 				if (!delta) {
 					sample = (byte)readBits(8);
 				} else {
-					byte predictor = _history.size() >= _predictorDistance ?
-						_history[_history.size() - _predictorDistance] : 0x80;
+					byte predictor = _history.size() >= _predictorDistance ? _history[_history.size() - _predictorDistance] : 0x80;
 					sample = predictor + (byte)(delta - (1 << (_bitWidth - 1)));
 				}
 			}
@@ -588,8 +599,8 @@ private:
 
 	void pushCue(uint16 value) {
 		// The original keeps at most 0x13 pending pitch entries, but consumes them
-		// while refilling wave buffers. This host decoder stores the full cue
-		// timeline, so applying that pending-entry limit here would drop later cues.
+		// while refilling wave buffers. Our decoder stores the full cue timeline,
+		// so applying that pending-entry limit here would drop later cues...
 		ComfyEngine::SoundCue cue;
 		cue.value = value;
 		cue.streamPosition = _streamPosition;
@@ -689,15 +700,16 @@ void ComfyEngine::setMediaRangePercent(uint16 value) {
 
 void ComfyEngine::setMediaMode(byte mode) {
 	if (mode == 1 || mode == 3) {
-		_v3SceneHostMediaModeEnabled = 1;
-		if (!_v3HostMediaValueAvailable) {
-			_v3HostMediaValue = 0;
-			_v3HostMediaValueAvailable = true;
+		_v3SceneMediaModeEnabled = 1;
+
+		if (!_v3MediaValueAvailable) {
+			_v3MediaValue = 0;
+			_v3MediaValueAvailable = true;
 		}
 	} else if (mode == 2) {
-		_v3SceneHostMediaModeEnabled = 0;
-		_v3HostMediaValue = 0;
-		_v3HostMediaValueAvailable = false;
+		_v3SceneMediaModeEnabled = 0;
+		_v3MediaValue = 0;
+		_v3MediaValueAvailable = false;
 	}
 }
 
@@ -706,7 +718,8 @@ void ComfyEngine::restoreWaveStateAfterSceneStart() {
 	setWaveLeftPercent(_v3SceneWaveLeftPercent);
 	setWaveRightPercent(_v3SceneWaveRightPercent);
 	setMixerVolumePercent(_v3SceneMixerVolumePercent);
-	if (_v3SceneHostMediaModeEnabled) {
+
+	if (_v3SceneMediaModeEnabled) {
 		setMediaMode(2);
 		setMediaMode(1);
 	} else {
@@ -727,6 +740,7 @@ bool ComfyEngine::soundOpenVocFile() {
 	byte header[4];
 	memset(header, 0, sizeof(header));
 	objFileReadFieldCore(header, 0, sizeof(header), _vocFile);
+
 	if (header[0] != 'C' || (header[1] != 'V' && header[1] != 'W')) {
 		objFileClose(_vocFile);
 		return false;
@@ -757,7 +771,7 @@ bool ComfyEngine::soundInit() {
 	}
 
 	_v3SceneWaveBalancePercent = 0;
-	_v3SceneHostMediaModeEnabled = 0;
+	_v3SceneMediaModeEnabled = 0;
 	_v3SceneWaveLeftPercent = 0;
 	_v3SceneWaveRightPercent = 0;
 	_v3SceneMixerVolumePercent = 0;
@@ -779,6 +793,7 @@ void ComfyEngine::soundShutdown() {
 	_soundVocBlockCount = 0;
 	_soundVocCounterSnapshot = 0;
 	_soundVocTimingDelta = 0;
+
 	if (_midiPlyrDriver)
 		_midiPlyrDriver->setIncreaseVocCounter(0);
 }
@@ -793,7 +808,9 @@ void ComfyEngine::soundUpdateVocTiming() {
 
 	uint32 timeFrac = 0;
 	uint16 blockNo = 0;
+
 	_midiPlyrDriver->vocSrGetCounters(timeFrac, blockNo);
+
 	if (!blockNo)
 		return;
 
@@ -840,6 +857,7 @@ bool ComfyEngine::soundPrepareDecoderState(uint16 index) {
 	uint32 dataSize = 0;
 	uint32 dataOffset = 0;
 	bool compressed = _soundCompressed;
+
 	if (index == 0xFFFF) {
 		uint32 storedSize = READ_LE_UINT32(_animFrameHeader + 4);
 		if (!storedSize)
@@ -850,8 +868,8 @@ bool ComfyEngine::soundPrepareDecoderState(uint16 index) {
 			memcpy(&animationSoundData[0], &_animFrameStorage[0], storedSize);
 		} else {
 			// The original streams embedded ANM sound through the file object while VC
-			// chunks arrive. The host decoder owns its source buffer, so rebuild only
-			// the embedded sound stream without changing the animation command cursor.
+			// chunks arrive; our decoder owns its source buffer, so we rebuild only
+			// the embedded sound stream without changing the animation command cursor...
 			if (_animCurrentIndex >= _animIndexTable.size())
 				return false;
 
@@ -859,6 +877,7 @@ bool ComfyEngine::soundPrepareDecoderState(uint16 index) {
 			uint32 position = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
 			while (copied < storedSize) {
 				uint32 headerSize = _animPantherFormat ? 8 : 4;
+
 				if (position > _animFileData.size() || headerSize > _animFileData.size() - position)
 					return false;
 
@@ -867,6 +886,7 @@ bool ComfyEngine::soundPrepareDecoderState(uint16 index) {
 				uint32 rawCommandSize = _animPantherFormat ? READ_LE_UINT32(header + 2) : READ_LE_UINT16(header + 2);
 				int32 signedCommandSize = _animPantherFormat ? (int32)rawCommandSize : (int32)(uint16)rawCommandSize;
 				uint32 commandSize = rawCommandSize;
+
 				if (_animPantherFormat && command == COMFY_ANM_COMMAND_FRAME && signedCommandSize <= (int32)headerSize) {
 					position += headerSize;
 					continue;
@@ -904,6 +924,7 @@ bool ComfyEngine::soundPrepareDecoderState(uint16 index) {
 		soundHeaderReadFromXms(header, index, sizeof(header));
 		dataSize = READ_LE_UINT32(header);
 		dataOffset = READ_LE_UINT32(header + 4);
+
 		if (!_vocFile || dataOffset > _vocFile->fileSize || dataSize > _vocFile->fileSize - dataOffset)
 			return false;
 
@@ -916,10 +937,12 @@ bool ComfyEngine::soundPrepareDecoderState(uint16 index) {
 		return false;
 
 	delete _soundDecoderState;
-	if (objectFile)
+
+	if (objectFile) {
 		_soundDecoderState = new SoundDecoderState(this, objectFile, dataOffset, dataSize, compressed);
-	else
+	} else {
 		_soundDecoderState = new SoundDecoderState(data + dataOffset, dataSize, compressed);
+	}
 
 	if (_soundDecoderState->fault()) {
 		delete _soundDecoderState;
@@ -936,6 +959,7 @@ bool ComfyEngine::soundPrepareDecoderState(uint16 index) {
 bool ComfyEngine::soundDecodePcmBlock(uint16 bufferIndex, byte *&buffer, uint32 &decodedSize) {
 	buffer = nullptr;
 	decodedSize = 0;
+
 	if (!_soundDecoderState)
 		return false;
 
@@ -947,6 +971,7 @@ bool ComfyEngine::soundDecodePcmBlock(uint16 bufferIndex, byte *&buffer, uint32
 
 	decodedSize = _soundDecoderState->decode(buffer, blockSize);
 	_soundDecoderState->copyCues(_soundCues);
+
 	if (!decodedSize) {
 		free(buffer);
 		buffer = nullptr;
@@ -977,12 +1002,10 @@ void ComfyEngine::soundPackState(byte *state) {
 		return;
 	}
 
-	uint32 vocCounter = _midiPlyrDriver ? _midiPlyrDriver->getVocCounter() :
-		(uint32)((_mixer->getSoundElapsedTime(_soundHandle) + 9) / 10);
+	uint32 vocCounter = _midiPlyrDriver ? _midiPlyrDriver->getVocCounter() : (uint32)((_mixer->getSoundElapsedTime(_soundHandle) + 9) / 10);
 	uint32 playbackPosition = (vocCounter * _soundSampleRate) / 100;
 	uint16 bufferIndex = _soundWaveBufferIndex;
-	if ((int32)(_soundDecoderState->getBufferStreamPosition(bufferIndex) -
-			COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES) < (int32)playbackPosition)
+	if ((int32)(_soundDecoderState->getBufferStreamPosition(bufferIndex) - COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES) < (int32)playbackPosition)
 		bufferIndex = 1 - bufferIndex;
 
 	_soundDecoderState->packState(state, bufferIndex, playbackPosition, vocCounter,
@@ -992,6 +1015,7 @@ void ComfyEngine::soundPackState(byte *state) {
 void ComfyEngine::soundUnpackState(byte *state) {
 	_mixer->stopHandle(_soundHandle);
 	_soundQueueStream = nullptr;
+
 	if (state[0x3F] || !_soundDecoderState) {
 		if (_midiPlyrDriver) {
 			_midiPlyrDriver->setIncreaseVocCounter(0);
@@ -1011,6 +1035,7 @@ void ComfyEngine::soundUnpackState(byte *state) {
 	_soundNextCue = 0;
 	byte *buffers[2] = {nullptr, nullptr};
 	uint32 decodedSizes[2] = {0, 0};
+
 	if (!soundDecodePcmBlock(0, buffers[0], decodedSizes[0]) ||
 			!soundDecodePcmBlock(1, buffers[1], decodedSizes[1])) {
 		free(buffers[0]);
@@ -1021,6 +1046,7 @@ void ComfyEngine::soundUnpackState(byte *state) {
 
 	_soundSampleRate = _soundDecoderState->getRate();
 	_soundQueueStream = Audio::makeQueuingAudioStream(_soundSampleRate, false);
+
 	if (!_soundQueueStream) {
 		free(buffers[0]);
 		free(buffers[1]);
@@ -1033,6 +1059,7 @@ void ComfyEngine::soundUnpackState(byte *state) {
 
 	_soundWaveBufferIndex = 0;
 	_soundEventSubIndex = 0xFFFF;
+
 	if (_midiPlyrDriver) {
 		_midiPlyrDriver->setVocCounter(vocCounter);
 		_midiPlyrDriver->setIncreaseVocCounter(1);
@@ -1059,8 +1086,8 @@ void ComfyEngine::soundPlayEntry(uint16 index) {
 
 	byte *buffers[2] = {nullptr, nullptr};
 	uint32 decodedSizes[2] = {0, 0};
-	if (!soundDecodePcmBlock(0, buffers[0], decodedSizes[0]) ||
-			!soundDecodePcmBlock(1, buffers[1], decodedSizes[1])) {
+
+	if (!soundDecodePcmBlock(0, buffers[0], decodedSizes[0]) || !soundDecodePcmBlock(1, buffers[1], decodedSizes[1])) {
 		free(buffers[0]);
 		free(buffers[1]);
 		delete _soundDecoderState;
@@ -1071,6 +1098,7 @@ void ComfyEngine::soundPlayEntry(uint16 index) {
 
 	_soundSampleRate = _soundDecoderState->getRate();
 	_soundQueueStream = Audio::makeQueuingAudioStream(_soundSampleRate, false);
+
 	if (!_soundQueueStream) {
 		free(buffers[0]);
 		free(buffers[1]);
@@ -1089,6 +1117,7 @@ void ComfyEngine::soundPlayEntry(uint16 index) {
 	_soundPaused = false;
 	_soundWaveBufferIndex = 0;
 	_soundEventSubIndex = 0xFFFF;
+
 	if (_midiPlyrDriver) {
 		_midiPlyrDriver->vocSrResetCounters();
 		_midiPlyrDriver->setVocCounter(0);
@@ -1104,6 +1133,7 @@ void ComfyEngine::soundAdvanceTick() {
 
 	if (!_mixer->isSoundHandleActive(_soundHandle)) {
 		_soundQueueStream = nullptr;
+
 		if (_soundDecoderState && _soundEventSubIndex != 0) {
 			_soundEventSubIndex = 0;
 		}
@@ -1111,12 +1141,12 @@ void ComfyEngine::soundAdvanceTick() {
 		return;
 	}
 
-	uint32 counter = _midiPlyrDriver ? _midiPlyrDriver->getVocCounter() :
-		(uint32)((_mixer->getSoundElapsedTime(_soundHandle) + 9) / 10);
+	uint32 counter = _midiPlyrDriver ? _midiPlyrDriver->getVocCounter() : (uint32)((_mixer->getSoundElapsedTime(_soundHandle) + 9) / 10);
 	soundServiceWaveBuffers();
 
 	int32 compareCounter = (int32)(counter - 2);
 	bool phaseCueSeen = false;
+
 	while (_soundNextCue < _soundCues.size() && compareCounter > (int32)_soundCues[_soundNextCue].counterThreshold &&
 			(_soundCues[_soundNextCue].value == 1 || _soundCues[_soundNextCue].value == 2)) {
 		phaseCueSeen = true;
@@ -1124,8 +1154,7 @@ void ComfyEngine::soundAdvanceTick() {
 		_soundNextCue++;
 	}
 
-	if (phaseCueSeen || _soundNextCue == _soundCues.size() ||
-			compareCounter <= (int32)_soundCues[_soundNextCue].counterThreshold)
+	if (phaseCueSeen || _soundNextCue == _soundCues.size() || compareCounter <= (int32)_soundCues[_soundNextCue].counterThreshold)
 		return;
 
 	_soundEventSubIndex = _soundCues[_soundNextCue].value;
@@ -1143,5 +1172,4 @@ void ComfyEngine::soundAdvanceTick() {
 	}
 }
 
-
 } // End of namespace Comfy
diff --git a/engines/comfy/timer.cpp b/engines/comfy/timer.cpp
index 1683d75bedc..f90d9db5107 100644
--- a/engines/comfy/timer.cpp
+++ b/engines/comfy/timer.cpp
@@ -61,6 +61,7 @@ uint16 ComfyEngine::timerTick() {
 	_timer1 = _timer0;
 	_timer0 = _timerCurrent;
 	_timerCurrent = (int16)midiTick();
+
 	return (uint16)_timerCurrent;
 }
 
diff --git a/engines/comfy/video.cpp b/engines/comfy/video.cpp
index 84bb9c6eec7..df255d076e4 100644
--- a/engines/comfy/video.cpp
+++ b/engines/comfy/video.cpp
@@ -41,15 +41,19 @@ void ComfyEngine::videoInit() {
 	_renderHeight = _screenHeight;
 	_viewOffsetX = 0;
 	_viewOffsetY = 0;
+
 	initGraphics(_logicalScreenWidth, _logicalScreenHeight);
+
 	_screen = new Graphics::Screen(_logicalScreenWidth, _logicalScreenHeight);
 	_framebufPtr = new byte[framebufferBytes()]();
 	_presentBuffer = new byte[framebufferBytes()]();
 	_backgroundFrame = 0;
 	_dirtyRectCount = 0;
 	_renderDirtyCount = 0;
+
 	renderAddFullFrameDirtyRect();
 	videoPresentFrame();
+
 	_videoInitialized = true;
 }
 
@@ -58,6 +62,7 @@ void ComfyEngine::videoShutdown(byte restorePalette) {
 		paletteRealize(nullptr);
 
 	colorDatClose();
+
 	delete[] _presentBuffer;
 	_presentBuffer = nullptr;
 	delete[] _framebufPtr;
@@ -78,6 +83,7 @@ void ComfyEngine::renderAddFullFrameDirtyRect() {
 	record.right = _logicalScreenWidth;
 	record.bottom = _logicalScreenHeight;
 	record.area = _engineVersion == 1 ? (uint16)framebufferBytes() : framebufferBytes();
+
 	renderAddDirtyRect(record);
 }
 
@@ -87,6 +93,7 @@ void ComfyEngine::renderRequestFullFrameInvalidation() {
 
 void ComfyEngine::renderFlushDirty() {
 	_dirtyRectCount = 0;
+
 	if (_renderDirtyCount) {
 		_renderDirtyCount--;
 		renderAddFullFrameDirtyRect();
@@ -101,6 +108,7 @@ void ComfyEngine::renderInvalidateFullFrame() {
 void ComfyEngine::renderAddDirtyRectMerged(ComfyRect record) {
 	int16 alignment = _isPanther ? 4 : 2;
 	uint32 mergeThreshold = _game->dirtyRectMergeThreshold;
+
 	record.left = CLIP<int16>(record.left, 0, _logicalScreenWidth);
 	record.left = record.left / alignment * alignment;
 	record.top = CLIP<int16>(record.top, 0, _logicalScreenHeight);
@@ -109,6 +117,7 @@ void ComfyEngine::renderAddDirtyRectMerged(ComfyRect record) {
 	record.right = MIN<int16>(record.right, _logicalScreenWidth);
 	record.bottom = CLIP<int16>(record.bottom, 0, _logicalScreenHeight);
 	record.area = (uint32)((int32)(record.right - record.left) * (record.bottom - record.top));
+
 	if (!record.area)
 		return;
 
@@ -120,8 +129,8 @@ void ComfyEngine::renderAddDirtyRectMerged(ComfyRect record) {
 
 	for (int i = _dirtyRectCount - 1; i >= 0; i--) {
 		ComfyRect &existing = _dirtyRects[i];
-		if (existing.right <= record.left || existing.left >= record.right ||
-				existing.bottom <= record.top || existing.top >= record.bottom)
+
+		if (existing.right <= record.left || existing.left >= record.right || existing.bottom <= record.top || existing.top >= record.bottom)
 			continue;
 
 		ComfyRect merged;
@@ -136,8 +145,7 @@ void ComfyEngine::renderAddDirtyRectMerged(ComfyRect record) {
 		intersection.top = MAX(existing.top, record.top);
 		intersection.right = MIN(existing.right, record.right) / alignment * alignment;
 		intersection.bottom = MIN(existing.bottom, record.bottom);
-		intersection.area = (uint32)((int32)(intersection.right - intersection.left) *
-			(intersection.bottom - intersection.top));
+		intersection.area = (uint32)((int32)(intersection.right - intersection.left) * (intersection.bottom - intersection.top));
 
 		uint32 extraArea = merged.area + intersection.area - record.area - existing.area;
 		if (extraArea < mergeThreshold) {
@@ -152,6 +160,7 @@ void ComfyEngine::renderAddDirtyRectMerged(ComfyRect record) {
 
 		ComfyRect *upperRect;
 		ComfyRect *lowerRect;
+
 		if (existing.top > record.top) {
 			upperRect = &record;
 			lowerRect = &existing;
@@ -166,27 +175,25 @@ void ComfyEngine::renderAddDirtyRectMerged(ComfyRect record) {
 		upperStrip.top = upperRect->top;
 		upperStrip.right = upperRect->right;
 		upperStrip.bottom = lowerRect->top;
-		upperStrip.area = (uint32)((int32)(upperStrip.right - upperStrip.left) *
-			(upperStrip.bottom - upperStrip.top));
+		upperStrip.area = (uint32)((int32)(upperStrip.right - upperStrip.left) * (upperStrip.bottom - upperStrip.top));
 
 		ComfyRect middleStrip;
 		middleStrip.left = MIN(lowerRect->left, upperRect->left);
 		middleStrip.top = lowerRect->top;
 		middleStrip.right = MAX(lowerRect->right, upperRect->right);
 		middleStrip.bottom = MIN(lowerRect->bottom, upperRect->bottom);
-		middleStrip.area = (uint32)((int32)(middleStrip.right - middleStrip.left) *
-			(middleStrip.bottom - middleStrip.top));
+		middleStrip.area = (uint32)((int32)(middleStrip.right - middleStrip.left) * (middleStrip.bottom - middleStrip.top));
 
 		ComfyRect bottomStrip;
 		bottomStrip.left = bottomRect->left;
 		bottomStrip.top = middleStrip.bottom;
 		bottomStrip.right = bottomRect->right;
 		bottomStrip.bottom = bottomRect->bottom;
-		bottomStrip.area = (uint32)((int32)(bottomStrip.right - bottomStrip.left) *
-			(bottomStrip.bottom - bottomStrip.top));
+		bottomStrip.area = (uint32)((int32)(bottomStrip.right - bottomStrip.left) * (bottomStrip.bottom - bottomStrip.top));
 
 		_dirtyRectCount--;
 		_dirtyRects[i] = _dirtyRects[_dirtyRectCount];
+
 		if (upperStrip.area)
 			renderAddDirtyRectMerged(upperStrip);
 
@@ -225,8 +232,7 @@ void ComfyEngine::renderAddDirtyRect(ComfyRect record) {
 
 	for (int i = _dirtyRectCount - 1; i >= 0; i--) {
 		ComfyRect &existing = _dirtyRects[i];
-		if (existing.right < record.left && existing.left <= record.right &&
-				existing.bottom >= record.top && existing.top <= record.bottom)
+		if (existing.right < record.left && existing.left <= record.right && existing.bottom >= record.top && existing.top <= record.bottom)
 			continue;
 
 		ComfyRect merged;
@@ -235,6 +241,7 @@ void ComfyEngine::renderAddDirtyRect(ComfyRect record) {
 		merged.top = MIN(existing.top, record.top) / 2 * 2;
 		merged.bottom = (MAX(existing.bottom, record.bottom) + 1) / 2 * 2;
 		merged.area = (uint32)(merged.right - merged.left) * (merged.bottom - merged.top);
+
 		if (_engineVersion == 1)
 			merged.area = (uint16)merged.area;
 
@@ -261,12 +268,14 @@ void ComfyEngine::videoPresentFrame() {
 	if (!_screen || !_framebufPtr || !_presentBuffer)
 		return;
 
-	if (_renderInterleaved && framebufferBytes() == 0xFA00) {
+	if (_renderInterleaved && framebufferBytes() == 64000) {
 		uint32 byteOffset = 0;
-		for (uint16 i = 0; i < 0x3E80;) {
+
+		for (uint16 i = 0; i < 16000;) {
 			memcpy(_presentBuffer + byteOffset, _framebufPtr + byteOffset, 4);
 			byteOffset += 4;
-			if ((i % 0x4E20) > 0x4268)
+
+			if ((i % 20000) > 17000)
 				i++;
 
 			i++;
@@ -276,6 +285,7 @@ void ComfyEngine::videoPresentFrame() {
 			_logicalScreenWidth, _logicalScreenHeight);
 	} else {
 		uint32 dirtyArea = 0;
+
 		if (_engineVersion == 1) {
 			for (uint i = 0; i < _dirtyRectCount; i++)
 				dirtyArea += _dirtyRects[i].area;
@@ -283,13 +293,13 @@ void ComfyEngine::videoPresentFrame() {
 
 		if (_engineVersion == 1 && dirtyArea > framebufferBytes() - 1000) {
 			framebufCopyAll(_presentBuffer, _framebufPtr);
-			_screen->copyRectToSurface(_presentBuffer, _logicalScreenWidth, 0, 0,
-				_logicalScreenWidth, _logicalScreenHeight);
+			_screen->copyRectToSurface(_presentBuffer, _logicalScreenWidth, 0, 0, _logicalScreenWidth, _logicalScreenHeight);
 		} else {
 			for (uint i = 0; i < _dirtyRectCount; i++) {
 				ComfyRect &record = _dirtyRects[i];
 				int16 width = record.right - record.left;
 				int16 height = record.bottom - record.top;
+
 				if (width <= 0 || height <= 0)
 					continue;
 


Commit: cc283bb746394e251893f52c391cbc73f5b8f7dd
    https://github.com/scummvm/scummvm/commit/cc283bb746394e251893f52c391cbc73f5b8f7dd
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Yet another clean-up pass

Changed paths:
    engines/comfy/expr.cpp
    engines/comfy/game.cpp
    engines/comfy/input.cpp
    engines/comfy/midi.cpp
    engines/comfy/script_vm.cpp


diff --git a/engines/comfy/expr.cpp b/engines/comfy/expr.cpp
index 28c51e8c408..e58f3fcf036 100644
--- a/engines/comfy/expr.cpp
+++ b/engines/comfy/expr.cpp
@@ -23,6 +23,35 @@
 
 namespace Comfy {
 
+#define EO_PUSH_LITERAL_01 0x01
+#define EO_PUSH_STRING_TABLE_VALUE 0x02
+#define EO_PUSH_LITERAL_03 0x03
+#define EO_ADD 0x08
+#define EO_SUBTRACT 0x09
+#define EO_MULTIPLY 0x0A
+#define EO_DIVIDE 0x0B
+#define EO_INDEXED_STRING_TABLE_VALUE 0x0C
+#define EO_END 0x0D
+#define EO_MODULO 0x0E
+#define EO_ACTOR_LOCAL_X 0x10
+#define EO_ACTOR_LOCAL_Y 0x11
+#define EO_ACTOR_WORLD_X 0x12
+#define EO_ACTOR_WORLD_Y 0x13
+#define EO_ACTOR_SPRITE_SELECTOR 0x14
+#define EO_PUSH_LITERAL_15 0x15
+#define EO_RANDOMIZE 0x16
+#define EO_MOUSE_X 0x17
+#define EO_MOUSE_Y 0x18
+#define EO_WAVE_BALANCE_PERCENT 0x19
+#define EO_HOST_MEDIA_VALUE 0x1A
+#define EO_NOOP_1B 0x1B
+#define EO_WAVE_LEFT_PERCENT 0x1C
+#define EO_WAVE_RIGHT_PERCENT 0x1D
+#define EO_LOGICAL_DIMENSION 0x1E
+#define EO_NOOP_1F 0x1F
+#define EO_HOST_MEDIA_PROGRESS 0x20
+#define EO_MIXER_VOLUME_PERCENT 0x21
+
 uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 	_exprStackTop = 0;
 
@@ -31,18 +60,20 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 		if (_scriptFault)
 			return 0;
 
-		if (opcode == 0x0D)
+		switch (opcode) {
+		case EO_END:
 			return _exprStackTop ? _exprStack[0] : 0;
 
-		if (opcode == 0x01 || opcode == 0x03 || opcode == 0x15) {
+		case EO_PUSH_LITERAL_01:
+		case EO_PUSH_LITERAL_03:
+		case EO_PUSH_LITERAL_15:
 			if (_exprStackTop < COMFY_EXPR_STACK_CAPACITY)
 				_exprStack[_exprStackTop++] = scriptReadWord(pc);
 
 			pc += 2;
 			continue;
-		}
 
-		if (opcode == 0x02) {
+		case EO_PUSH_STRING_TABLE_VALUE: {
 			uint16 index = scriptReadWord(pc);
 			pc += 2;
 			uint16 value = index < _stringTable.size() ? _stringTable[index] : 0;
@@ -53,7 +84,11 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 			continue;
 		}
 
-		if (opcode >= 0x10 && opcode <= 0x14) {
+		case EO_ACTOR_LOCAL_X:
+		case EO_ACTOR_LOCAL_Y:
+		case EO_ACTOR_WORLD_X:
+		case EO_ACTOR_WORLD_Y:
+		case EO_ACTOR_SPRITE_SELECTOR: {
 			Actor *actor = actorResolve(scriptReadWord(pc), fallbackActor);
 			pc += 2;
 
@@ -63,12 +98,18 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 			}
 
 			uint16 value = 0;
-			if (opcode == 0x10) {
+			switch (opcode) {
+			case EO_ACTOR_LOCAL_X:
 				value = (uint32)actor->xFixed >> 12;
-			} else if (opcode == 0x11) {
+				break;
+
+			case EO_ACTOR_LOCAL_Y:
 				value = (uint32)actor->yFixed >> 12;
-			} else if (opcode == 0x12 || opcode == 0x13) {
-				bool useX = opcode == 0x12;
+				break;
+
+			case EO_ACTOR_WORLD_X:
+			case EO_ACTOR_WORLD_Y: {
+				bool useX = opcode == EO_ACTOR_WORLD_X;
 				int32 position = useX ? actor->xFixed : actor->yFixed;
 
 				while (actor->parent) {
@@ -80,8 +121,16 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 				}
 
 				value = (uint16)(position >> 12);
-			} else if (opcode == 0x14)
+				break;
+			}
+
+			case EO_ACTOR_SPRITE_SELECTOR:
 				value = (uint16)actor->spriteSelector;
+				break;
+
+			default:
+				break;
+			}
 
 			if (_exprStackTop < COMFY_EXPR_STACK_CAPACITY)
 				_exprStack[_exprStackTop++] = value;
@@ -89,71 +138,121 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 			continue;
 		}
 
-		if (opcode == 0x16) {
+		case EO_INDEXED_STRING_TABLE_VALUE: {
+			if (_exprStackTop < 2) {
+				_exprStackTop = 0;
+				continue;
+			}
+
+			uint16 index = _exprStack[_exprStackTop - 2] + _exprStack[_exprStackTop - 1];
+			_exprStackTop--;
+			_exprStack[_exprStackTop - 1] = index < _stringTable.size() ? _stringTable[index] : 0;
+			continue;
+		}
+
+		case EO_RANDOMIZE:
 			if (_exprStackTop) {
 				int16 maximum = _exprStack[_exprStackTop - 1];
 				_exprStack[_exprStackTop - 1] = (uint16)(((int32)getRandomNumber(0x7FFF) * maximum) / 0x8000);
 			}
 
 			continue;
+
+		default:
+			break;
 		}
 
-		if (_engineVersion == 3 && opcode >= 0x17 && opcode <= 0x21) {
+		if (_engineVersion == 3) {
 			uint16 value = 0;
 			bool pushValue = true;
+			bool handled = true;
 
-			if (opcode == 0x17) {
+			switch (opcode) {
+			case EO_MOUSE_X:
 				value = _mouseX;
-			} else if (opcode == 0x18) {
+				break;
+
+			case EO_MOUSE_Y:
 				value = _mouseY;
-			} else if (opcode == 0x19) {
+				break;
+
+			case EO_WAVE_BALANCE_PERCENT:
 				value = _v3SceneWaveBalancePercent;
-			} else if (opcode == 0x1A) {
+				break;
+
+			case EO_HOST_MEDIA_VALUE:
 				value = _v3MediaValueAvailable ? _v3MediaValue : 0;
-			} else if (opcode == 0x1B) {
+				break;
+
+			case EO_NOOP_1B:
 				pushValue = false;
-			} else if (opcode == 0x1C) {
+				break;
+
+			case EO_WAVE_LEFT_PERCENT:
 				value = _v3SceneWaveLeftPercent;
-			} else if (opcode == 0x1D) {
+				break;
+
+			case EO_WAVE_RIGHT_PERCENT:
 				value = _v3SceneWaveRightPercent;
-			} else if (opcode == 0x1E) {
+				break;
+
+			case EO_LOGICAL_DIMENSION:
 				if (_exprStackTop) {
 					uint16 dimension = _exprStack[_exprStackTop - 1];
-					if (dimension == 0x6E)
+					switch (dimension) {
+					case 0x6E:
 						_exprStack[_exprStackTop - 1] = 320;
-					else if (dimension == 0x6F)
+						break;
+
+					case 0x6F:
 						_exprStack[_exprStackTop - 1] = 200;
-					else
+						break;
+
+					default:
 						_exprStack[_exprStackTop - 1] = 0;
+						break;
+					}
 				}
 
 				pushValue = false;
-			} else if (opcode == 0x1F || opcode == 0x20) {
+				break;
+
+			case EO_NOOP_1F:
+				pushValue = false;
+				break;
+
+			case EO_HOST_MEDIA_PROGRESS:
 				value = _v3MediaProgress;
-			} else if (opcode == 0x21) {
+				break;
+
+			case EO_MIXER_VOLUME_PERCENT:
 				value = _v3SceneMixerVolumePercent;
-			}
+				break;
 
-			if (pushValue && _exprStackTop < COMFY_EXPR_STACK_CAPACITY)
-				_exprStack[_exprStackTop++] = value;
+			default:
+				handled = false;
+				break;
+			}
 
-			continue;
-		}
+			if (handled) {
+				if (pushValue && _exprStackTop < COMFY_EXPR_STACK_CAPACITY)
+					_exprStack[_exprStackTop++] = value;
 
-		if (opcode == 0x0C) {
-			if (_exprStackTop < 2) {
-				_exprStackTop = 0;
 				continue;
 			}
-
-			uint16 index = _exprStack[_exprStackTop - 2] + _exprStack[_exprStackTop - 1];
-			_exprStackTop--;
-			_exprStack[_exprStackTop - 1] = index < _stringTable.size() ? _stringTable[index] : 0;
-			continue;
 		}
 
-		if (opcode != 0x08 && opcode != 0x09 && opcode != 0x0A && opcode != 0x0B && opcode != 0x0E)
+		switch (opcode) {
+		case EO_ADD:
+		case EO_SUBTRACT:
+		case EO_MULTIPLY:
+		case EO_DIVIDE:
+		case EO_MODULO:
+			break;
+
+		default:
 			error("Unknown expression opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
+		}
 
 		if (_exprStackTop < 2) {
 			_exprStackTop = 0;
@@ -163,19 +262,39 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 		int16 rhs = _exprStack[--_exprStackTop];
 		int16 lhs = _exprStack[_exprStackTop - 1];
 
-		if (opcode == 0x08) {
+		switch (opcode) {
+		case EO_ADD:
 			_exprStack[_exprStackTop - 1] = (uint16)(lhs + rhs);
-		} else if (opcode == 0x09) {
+			break;
+
+		case EO_SUBTRACT:
 			_exprStack[_exprStackTop - 1] = (uint16)(lhs - rhs);
-		} else if (opcode == 0x0A) {
+			break;
+
+		case EO_MULTIPLY:
 			_exprStack[_exprStackTop - 1] = (uint16)(lhs * rhs);
-		} else if ((opcode == 0x0B || opcode == 0x0E) && !rhs) {
-			_scriptFault = true;
-			return 0;
-		} else if (opcode == 0x0B) {
+			break;
+
+		case EO_DIVIDE:
+			if (!rhs) {
+				_scriptFault = true;
+				return 0;
+			}
+
 			_exprStack[_exprStackTop - 1] = (uint16)(lhs / rhs);
-		} else if (opcode == 0x0E) {
+			break;
+
+		case EO_MODULO:
+			if (!rhs) {
+				_scriptFault = true;
+				return 0;
+			}
+
 			_exprStack[_exprStackTop - 1] = (uint16)(lhs % rhs);
+			break;
+
+		default:
+			break;
 		}
 	}
 }
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index f4f7598fce4..e40eeea40d5 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -23,7 +23,6 @@
 
 #include "common/config-manager.h"
 #include "common/endian.h"
-#include "common/ptr.h"
 
 namespace Comfy {
 
@@ -284,18 +283,22 @@ Common::SeekableReadStream *ComfyEngine::pathFOpen(const Common::Path &filename,
 }
 
 bool ComfyEngine::readAssetFile(const Common::Path &filename, Common::Array<byte> &data) {
-	Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(filename, true));
-	if (!stream || stream->size() < 0 || (uint64)stream->size() > UINT32_MAX)
+	Common::SeekableReadStream *stream = pathFOpen(filename, true);
+	if (!stream || stream->size() < 0 || (uint64)stream->size() > UINT32_MAX) {
+		delete stream;
 		return false;
+	}
 
 	uint32 size = stream->size();
 	data.resize(size);
 
 	if (size && stream->read(&data[0], size) != size) {
 		data.clear();
+		delete stream;
 		return false;
 	}
 
+	delete stream;
 	return true;
 }
 
diff --git a/engines/comfy/input.cpp b/engines/comfy/input.cpp
index 8c6b913f62d..590c130ef3f 100644
--- a/engines/comfy/input.cpp
+++ b/engines/comfy/input.cpp
@@ -22,7 +22,6 @@
 #include "comfy/comfy.h"
 #include "comfy/midiplyr/midiplyr.h"
 
-#include "common/ptr.h"
 
 namespace Comfy {
 
@@ -118,17 +117,19 @@ bool ComfyEngine::hostKeyboardLoadDatMap() {
 		return true;
 
 	hostKeyboardResetMap();
-	Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(Common::Path("KEYBOARD.DAT"), false));
+	Common::SeekableReadStream *stream = pathFOpen(Common::Path("KEYBOARD.DAT"), false);
 	if (!stream)
-		stream.reset(pathFOpen(Common::Path("KEYBOARD.DAT"), true));
+		stream = pathFOpen(Common::Path("KEYBOARD.DAT"), true);
 
 	if (!stream)
 		return false;
 
 	byte value;
 	do {
-		if (stream->read(&value, 1) != 1)
+		if (stream->read(&value, 1) != 1) {
+			delete stream;
 			return false;
+		}
 	} while (value);
 
 	bool loaded = false;
@@ -138,6 +139,7 @@ bool ComfyEngine::hostKeyboardLoadDatMap() {
 
 		if (stream->read(&key, 1) != 1 || stream->read(&bit, 1) != 1 || bit >= COMFY_KEYBOARD_CONTACT_COUNT) {
 			hostKeyboardResetMap();
+			delete stream;
 			return false;
 		}
 
@@ -146,6 +148,7 @@ bool ComfyEngine::hostKeyboardLoadDatMap() {
 	}
 
 	_keyboardMapLoaded = loaded;
+	delete stream;
 	return loaded;
 }
 
diff --git a/engines/comfy/midi.cpp b/engines/comfy/midi.cpp
index afa5d9dca54..d70221d4d80 100644
--- a/engines/comfy/midi.cpp
+++ b/engines/comfy/midi.cpp
@@ -22,7 +22,6 @@
 #include "comfy/comfy.h"
 #include "comfy/midiplyr/midiplyr.h"
 
-#include "common/ptr.h"
 #include "common/endian.h"
 
 namespace Comfy {
@@ -93,13 +92,15 @@ uint16 ComfyEngine::midiTick() {
 }
 
 bool ComfyEngine::midiPlyrStart() {
-	Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(Common::Path("MIDIFILE.DAT"), true));
+	Common::SeekableReadStream *stream = pathFOpen(Common::Path("MIDIFILE.DAT"), true);
 	if (!stream)
 		return false;
 
 	byte signature[2];
-	if (stream->read(signature, sizeof(signature)) != sizeof(signature))
+	if (stream->read(signature, sizeof(signature)) != sizeof(signature)) {
+		delete stream;
 		return false;
+	}
 
 	byte flags;
 	if (signature[0] == 'C' && signature[1] == 'M') {
@@ -107,9 +108,11 @@ bool ComfyEngine::midiPlyrStart() {
 	} else if (signature[0] == 'C' && signature[1] == 'm') {
 		flags = 1;
 	} else {
+		delete stream;
 		return false;
 	}
 
+	delete stream;
 	midiPlyrStop();
 	MidiPlyrDriver::DriverVersion version = _engineVersion == 3 ? MidiPlyrDriver::kDriverVersion2 : MidiPlyrDriver::kDriverVersion1;
 	_midiPlyrDriver = new MidiPlyrDriver(version);
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index d5a822028ee..854945f711c 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -23,7 +23,6 @@
 
 #include "common/config-manager.h"
 #include "common/endian.h"
-#include "common/ptr.h"
 
 namespace Comfy {
 
@@ -899,12 +898,13 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 				break;
 			case SO_CONFIG_TEST_FILE: {
-				Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(Common::Path(key), true));
+				Common::SeekableReadStream *stream = pathFOpen(Common::Path(key), true);
 				if (stream)
 					keyBitSet(value);
 				else
 					keyBitClear(value);
 
+				delete stream;
 				break;
 			}
 			case SO_CONFIG_SET_LANGUAGE_DATA_SUBDIRECTORY:
@@ -1276,8 +1276,9 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 				} else if (argument == 20) {
 					condition = _v3MediaRecording;
 				} else if (argument == 30) {
-					Common::ScopedPtr<Common::SeekableReadStream> stream(pathFOpen(Common::Path("comfy.htm"), true));
-					condition = (bool)stream;
+					Common::SeekableReadStream *stream = pathFOpen(Common::Path("comfy.htm"), true);
+					condition = stream != nullptr;
+					delete stream;
 				}
 				break;
 			default:


Commit: 1306cf6243c56da393078c4f24b8d4e9818197a9
    https://github.com/scummvm/scummvm/commit/1306cf6243c56da393078c4f24b8d4e9818197a9
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Change how debug window is brought up

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy_keyboard_ui.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index f3c9d359462..9608a658214 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -72,10 +72,12 @@ void onImGuiRender() {
 	io.ConfigFlags &= ~(ImGuiConfigFlags_NoMouseCursorChange | ImGuiConfigFlags_NoMouse);
 
 	bool actorDebugEnabled = debugChannelSet(-1, kDebugImGui);
-	if (actorDebugEnabled)
+	if (actorDebugEnabled) {
+		_state->_actorDebugVisible = true;
 		_state->_engine->drawActorDebugUi(&_state->_actorDebugVisible);
-	else
+	} else {
 		_state->_actorDebugVisible = false;
+	}
 
 	if (ConfMan.getBool("use_imgui_keyboard"))
 		drawComfyKeyboardUi(actorDebugEnabled);
diff --git a/engines/comfy/comfy_keyboard_ui.cpp b/engines/comfy/comfy_keyboard_ui.cpp
index 74eae2b7099..329e24897e3 100644
--- a/engines/comfy/comfy_keyboard_ui.cpp
+++ b/engines/comfy/comfy_keyboard_ui.cpp
@@ -135,9 +135,6 @@ void drawComfyKeyboardUi(bool actorDebugEnabled) {
 	ImGui::SetNextWindowSize(ImVec2(740, 440), ImGuiCond_FirstUseEver);
 
 	if (ImGui::Begin("Comfy Keyboard", &_state->_visible, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoResize)) {
-		if (actorDebugEnabled)
-			ImGui::Checkbox("Actor debug", &_state->_actorDebugVisible);
-
 		ImU32 shell = keyboardColor(232, 228, 208);
 		ImU32 red = keyboardColor(199, 31, 27);
 		ImU32 handset = keyboardColor(211, 48, 38);


Commit: ef6e8ad62da794c28c60b5ebd7c14974af03d395
    https://github.com/scummvm/scummvm/commit/ef6e8ad62da794c28c60b5ebd7c14974af03d395
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Rewrite sound engine to be more accurate

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/anim_file.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/game.cpp
    engines/comfy/midi.cpp
    engines/comfy/scene.cpp
    engines/comfy/sound.cpp
    engines/comfy/timer.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index 55caa6d2d0e..bab9cfcfd68 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -464,9 +464,7 @@ void ComfyEngine::spriteGetConvPtr(int16 spriteId) {
 	if (!payload || width != 0xFFFF)
 		return;
 
-	// A width of 0xFFFF marks a conversion-cache payload. The original uses
-	// its first word as a tile index and copies the remaining payload to XMS;
-	// we keep this protocol but clearly we won't do an entire XMS reimplementation for this...
+	soundPlayFromPtr(payload);
 }
 
 void ComfyEngine::spriteBlitRle(byte *destination, const byte *source, uint32 sourceSize) {
diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
index 693c3133533..ae7f35ffa1f 100644
--- a/engines/comfy/anim_file.cpp
+++ b/engines/comfy/anim_file.cpp
@@ -556,6 +556,8 @@ void ComfyEngine::animFrameWaitForVocCounter() {
 		return;
 
 	while (animFrameVocCounterDelta() < -(int16)(_animVocDeltaB + 3)) {
+		// The original spins on the asynchronous VOC counter; yield so the host backend can advance it...
+		_system->delayMillis(1);
 		processEvents();
 
 		if (shouldQuit())
@@ -788,6 +790,112 @@ void ComfyEngine::animFileRestoreStreamPosition(const byte *state) {
 	_animSavedStreamPosition = streamPosition;
 }
 
+void ComfyEngine::animFileRestoreSoundStorage(uint32 soundPosition) {
+	if (soundPosition > _soundDataEnd) {
+		_soundFault = true;
+		return;
+	}
+
+	if (_soundDataEnd <= _animFrameStorage.size()) {
+		_soundDecoderData.resize(_soundDataEnd);
+		if (_soundDataEnd)
+			memcpy(&_soundDecoderData[0], &_animFrameStorage[0], _soundDataEnd);
+		return;
+	}
+
+	if (_animCurrentIndex >= _animIndexTable.size()) {
+		_soundFault = true;
+		return;
+	}
+
+	uint chunkIndex = 0;
+	while (chunkIndex < 6 && _animStorageChunkOffsets[chunkIndex] > soundPosition)
+		chunkIndex++;
+
+	if (chunkIndex < 6 && _animStorageChunkSizes[chunkIndex]) {
+		uint32 chunkOffset = _animStorageChunkOffsets[chunkIndex];
+		uint16 chunkPosition = (uint16)(soundPosition - chunkOffset);
+		uint32 restoredEnd = 0;
+
+		if (chunkPosition < _animStorageChunkSizes[chunkIndex]) {
+			_soundDecoderData.resize(_soundDataEnd);
+
+			if (_soundDataEnd)
+				memset(&_soundDecoderData[0], 0, _soundDecoderData.size());
+
+			uint32 frameStart = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
+
+			for (int i = (int)chunkIndex; i >= 0; i--) {
+				uint16 sourcePosition = i == (int)chunkIndex ? chunkPosition : 0;
+				uint16 chunkSize = _animStorageChunkSizes[i];
+				uint32 sourceOffset = _animStorageChunkFileOffsets[i] + sourcePosition;
+				uint32 destinationOffset = _animStorageChunkOffsets[i] + sourcePosition;
+
+				if (sourcePosition >= chunkSize || frameStart > _animFileData.size() ||
+						sourceOffset > _animFileData.size() - frameStart ||
+						destinationOffset >= _soundDecoderData.size())
+					continue;
+
+				uint32 copySize = chunkSize - sourcePosition;
+				copySize = MIN<uint32>(copySize, _animFileData.size() - frameStart - sourceOffset);
+				copySize = MIN<uint32>(copySize, _soundDecoderData.size() - destinationOffset);
+				memcpy(&_soundDecoderData[destinationOffset], &_animFileData[frameStart + sourceOffset], copySize);
+				restoredEnd = MAX<uint32>(restoredEnd, destinationOffset + copySize);
+			}
+
+			if (restoredEnd >= _soundDataEnd)
+				return;
+		}
+	}
+
+	// We store the complete source rather than the original 64 KiB circular XMS window...
+	// Rebuild that source when the six serialized XMS chunks do not cover the decoder range...
+	_soundDecoderData.resize(_soundDataEnd);
+	uint32 copied = 0;
+	uint32 position = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
+
+	while (copied < _soundDataEnd) {
+		uint32 headerSize = _animPantherFormat ? 8 : 4;
+
+		if (position > _animFileData.size() || headerSize > _animFileData.size() - position) {
+			_soundFault = true;
+			return;
+		}
+
+		byte *header = &_animFileData[position];
+		uint16 command = READ_LE_UINT16(header);
+		uint32 rawCommandSize = _animPantherFormat ? READ_LE_UINT32(header + 2) : READ_LE_UINT16(header + 2);
+		int32 signedCommandSize = _animPantherFormat ? (int32)rawCommandSize : (int32)(uint16)rawCommandSize;
+		uint32 commandSize = rawCommandSize;
+
+		if (_animPantherFormat && command == kAnimCommandFrame && signedCommandSize <= (int32)headerSize) {
+			position += headerSize;
+			continue;
+		}
+
+		if (commandSize < headerSize || commandSize > _animFileData.size() - position) {
+			_soundFault = true;
+			return;
+		}
+
+		uint32 payloadSize = commandSize - headerSize;
+		if (command == kAnimCommandStoreFrameBytes) {
+			uint32 copySize = MIN<uint32>(payloadSize, _soundDataEnd - copied);
+			if (copySize)
+				memcpy(&_soundDecoderData[copied], header + headerSize, copySize);
+
+			copied += copySize;
+		} else if (command == kAnimCommandEnd) {
+			break;
+		}
+
+		position += commandSize;
+	}
+
+	if (copied < _soundDataEnd)
+		_soundFault = true;
+}
+
 void ComfyEngine::animFileRebuildStorage(uint32 targetSize) {
 	_animFrameStorage.clear();
 	memset(_animFrameCommandData, 0, sizeof(_animFrameCommandData));
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 9608a658214..43fa13998b7 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -597,7 +597,8 @@ void ComfyEngine::midiTrackTickAndRemove() {
 	_midiInstanceTrackBase = _midiTracks.baseTime;
 
 	while (_midiTracks.nextIndex != 999 && _midiTracks.baseTime >= _midiTracks.nextTime) {
-		keyBitSet(_midiTracks.entries[_midiTracks.nextIndex].id);
+		uint16 eventId = _midiTracks.entries[_midiTracks.nextIndex].id;
+		keyBitSet(eventId);
 		_midiTracks.count--;
 		_midiTracks.entries[_midiTracks.nextIndex] = _midiTracks.entries[_midiTracks.count];
 		midiFindNext(_midiTracks);
@@ -605,6 +606,8 @@ void ComfyEngine::midiTrackTickAndRemove() {
 }
 
 void ComfyEngine::sceneTickEvent() {
+	soundAdvanceTick();
+
 	if (_soundEventIndex == _soundEventMaximum)
 		return;
 
@@ -787,14 +790,14 @@ bool ComfyEngine::vocQueuePush(uint16 soundId, uint16 argumentCount, uint32 pc)
 }
 
 void ComfyEngine::vocQueuePlayAll() {
-	_mixer->stopHandle(_soundHandle);
-	_soundQueueStream = nullptr;
-	_soundCues.clear();
-	_soundNextCue = 0;
-	if (_midiPlyrDriver)
-		_midiPlyrDriver->vocSrResetBlockNo();
+	if (_isPanther) {
+		soundStopPlayback();
+	} else {
+		soundStopAllAndReset();
+	}
 
 	if (_engineVersion == 3) {
+		soundPrepareQueuePlayback();
 		uint16 slot = _soundEventIndex;
 		while (slot != _soundEventMaximum) {
 			VocQueueEntryV3 &entry = _vocQueueV3[slot];
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 74dd5f90b1c..f848ddcc8c8 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -81,7 +81,9 @@ class QueuingAudioStream;
 #define COMFY_PANTHER_VOC_QUEUE_CAPACITY 4
 #define COMFY_SOUND_PCM_BLOCK_BYTES 0x4E20
 #define COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES 0x3E80
-#define COMFY_SOUND_PITCH_COUNT_LIMIT 0x13
+#define COMFY_V3_SOUND_PCM_BLOCK_BYTES 0x3E80
+#define COMFY_SOUND_MAX_CUES 0x13
+#define COMFY_V3_SOUND_MAX_CUES 0x27
 #define COMFY_FRAME_LOADER_DATA_BYTES 0x6000
 #define COMFY_VOC_ARG_CAPACITY_V3 12
 #define COMFY_MIDI_QUEUE_CAPACITY 32
@@ -105,7 +107,6 @@ namespace Comfy {
 
 class ComfyEngine;
 class MidiPlyrDriver;
-struct SoundDecoderState;
 
 #ifdef USE_IMGUI
 typedef struct ImGuiState {
@@ -149,8 +150,6 @@ struct ComfyRect {
 
 class ComfyEngine : public Engine {
 private:
-	friend struct SoundDecoderState;
-
 	struct DrawCommand {
 		int16 x;
 		int16 y;
@@ -746,27 +745,35 @@ private:
 	MidiChannelState _midiChannels[COMFY_MIDI_CHANNEL_COUNT];
 	uint32 _midiInstanceTrackBase = 1;
 	Common::Array<SoundCue> _soundCues;
-	SoundDecoderState *_soundDecoderState = nullptr;
 	Audio::SoundHandle _soundHandle;
 	Audio::QueuingAudioStream *_soundQueueStream = nullptr;
 	uint16 _soundWaveBufferIndex = 0;
+	uint16 _soundBufferStateIndex = 0;
+	byte *_soundPackedState = nullptr;
+	byte *_soundBufferState = nullptr;
 	Common::Array<byte> _soundDecoderData;
 	uint32 _soundStreamPosition = 0;
 	uint32 _soundEventArgument = 0;
 	int32 _soundEventLength = 0;
 	uint32 _soundDataBase = 0;
 	uint32 _soundDataEnd = 0;
+	uint32 _soundHeaderEnd = 0;
 	uint32 _soundPlayPosition = 0;
+	uint32 _soundSourceBase = 0;
+	uint32 _soundSourceWindowStart = 0;
+	uint32 _soundSourceWindowEnd = 0;
+	uint32 _soundDecodeBlockSize = 0;
 	uint32 _soundLoopPosition = 0;
 	uint32 _soundCursor = 0;
 	uint32 _soundBlockBase = 0;
-	uint32 _soundRate = 0;
 	uint16 _soundFillCount = 0;
+	uint32 _soundEventRemaining = 0;
 	int16 _soundLoopCount = 0;
 	byte _soundSample = 0xA5;
 	byte _soundNextSample = 0;
 	bool _soundStopped = true;
 	bool _soundStarted = false;
+	bool _soundCounterEnabled = true;
 	uint16 _soundBitOffset = 0;
 	uint16 _soundLoopBitOffset = 0;
 	uint16 _soundBlockOffset = 0;
@@ -774,10 +781,23 @@ private:
 	byte _soundBitWidth = 4;
 	byte _soundPredictorDistance = 1;
 	bool _soundNeedInit = false;
+	bool _soundFinished = false;
+	bool _soundFault = false;
+	byte *_soundWritePointer = nullptr;
+	Common::Array<byte> _soundHistory;
+	uint32 _soundRate = 0;
+	Common::Array<byte> _soundInterleaveStorage;
+	byte *_soundInterleavePointer = nullptr;
+	uint32 _soundBufferStreamPosition[2] = {0, 0};
+	uint32 _soundBufferPosition[2] = {0, 0};
+	uint32 _soundBufferLoopPosition[2] = {0, 0};
+	uint32 _soundBufferEventRemaining[2] = {0, 0};
+	uint16 _soundBufferFillRemaining[2] = {0, 0};
+	int16 _soundBufferLoopCount[2] = {0, 0};
+	bool _soundBufferStarted[2] = {false, false};
 	Common::Array<byte> _soundPcmBlocks[2];
-	uint16 _soundEntryCount = 0;
-	uint32 _soundSampleRate = 0x2B11;
-	uint _soundNextCue = 0;
+	uint16 _soundTileStride = 0;
+	uint32 _soundSampleRate = 11025;
 	bool _soundCompressed = false;
 	bool _soundUsesAnimData = false;
 	bool _soundPaused = false;
@@ -939,8 +959,8 @@ private:
 	void midiShutdown();
 	void midiFileGetEntryTableParams(uint16 *entryCount, uint16 *entrySize);
 	void midiFileReadEntries(byte *destination);
-	byte *soundReadHeaderTable();
-	void soundGetHeaderTableParams(uint16 *entryCount, uint16 *entrySize);
+	byte *soundReadTiledData();
+	void soundGetTileParams(uint16 *tileStride, uint16 *fieldCount);
 	bool soundOpenVocFile();
 	void spriteCache(int16 spriteId);
 	SpriteResource *spriteLookup(uint16 spriteId, int16 x, int16 y);
@@ -1045,6 +1065,7 @@ private:
 	void animFrameClear();
 	void animFilePackState(byte *state);
 	void animFileRestoreStreamPosition(const byte *state);
+	void animFileRestoreSoundStorage(uint32 soundPosition);
 	void animFileRebuildStorage(uint32 targetSize);
 	void animFileUnpackState(const byte *state);
 	void animFrameInvalidateActorRect();
@@ -1096,17 +1117,69 @@ private:
 	void setMediaMode(byte mode);
 	void restoreWaveStateAfterSceneStart();
 	bool soundInit();
+	bool vocQueueInit();
 	void soundShutdown();
-	void soundHeaderReadFromXms(byte *destination, uint16 index, uint16 size);
+	void soundInitOutput();
+	void soundAllocBuffers(uint16 size);
+	void soundFreePcmBuf();
+	void soundPauseOutput();
+	void soundResumeOutput();
+	void soundPauseOrResume(byte pause);
+	void soundStopAllAndReset();
+	void soundPrepareQueuePlayback();
+	void soundStopPlayback();
+	void soundCloseVocFile();
+	void soundFreeBuffer();
+	ObjFile *soundLoadSoundData(const Common::Path &path, uint16 blockSize, uint32 maximumBytes);
+	void waveOutReset();
+	void waveOutOpen();
+	void waveOutPause();
+	void waveOutRestart();
+	bool waveOutSubmitBuffer(uint16 bufferIndex);
+	bool waveOutStartPlayback();
+	void soundSetSampleRate(uint32 sampleRate);
+	void soundReadHeader(byte *destination, uint16 index, uint16 size);
 	void soundUpdateVocTiming();
 	void soundServiceWaveBuffers();
 	bool soundLoadEntry(uint16 index);
-	bool soundPrepareDecoderState(uint16 index);
-	bool soundDecodePcmBlock(uint16 bufferIndex, byte *&buffer, uint32 &decodedSize);
-	bool soundQueuePcmBlock(uint16 bufferIndex);
-	void soundPackState(byte *state);
-	void soundUnpackState(byte *state);
+	byte soundOpenEntry(uint16 index);
+	void soundPlayFromPtr(const byte *source);
+	byte soundReadSourceByte(uint32 position);
+	bool soundLoadSourceWindow(uint32 size);
+	uint32 soundCalcSampleRate(byte &sample);
+	uint16 soundBitRead(uint16 bits);
+	uint32 soundBitRead32(uint16 bits);
+	void soundResetBitState();
+	void soundDecodeBits(uint16 size, byte mode);
+	void soundReadParam(uint16 &value);
+	void soundReadFreqWord(uint16 &value);
+	byte soundReadSampleByte();
+	void soundSaveLoopPosition();
+	void soundDecompressBlock(uint16 size);
+	void soundLoadDataBlock(uint16 size);
+	void soundSeekToLoop(uint16 size);
+	void soundReadLoopEntry(uint16 &frequency, byte &sample);
+	void soundBeginEvent(bool loop);
+	uint16 soundParseCommand();
+	void soundCopyPcm(byte *destination, uint16 size);
+	void soundAdvancePlayPosition();
+	void soundLoadChunk();
+	void soundPreloadChunk();
+	void soundInitRuntimeState(byte *state);
+	void soundSetBufferStatePointer(byte *state);
+	void soundSaveStreamPositions(uint16 bufferIndex);
+	void soundRestoreBufferState();
+	void soundSaveActiveBufferState(uint16 bufferIndex);
+	void soundSaveBufferState(uint16 bufferIndex);
+	void soundPushCue(uint16 value, int32 streamPosition);
+	void soundPackCueEntries(byte *state, uint32 playbackPosition);
+	void soundFillPcmBuffer(uint16 bufferIndex, uint16 size);
+	void soundPackState();
+	void soundUnpackState();
+	uint16 soundGetStateSize();
 	void soundPlayEntry(uint16 index);
+	void soundUnprepareHeader();
+	void soundCueTick();
 	void soundAdvanceTick();
 
 #ifdef USE_IMGUI
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index e40eeea40d5..d0b66326d8c 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -322,18 +322,6 @@ void ComfyEngine::midiFileReadEntries(byte *destination) {
 	_midiFileStream->read(destination, size);
 }
 
-byte *ComfyEngine::soundReadHeaderTable() {
-	return _vocFile ? objFileReadTiled(4, (uint32)_soundEntryCount * 8, _vocFile) : nullptr;
-}
-
-void ComfyEngine::soundGetHeaderTableParams(uint16 *entryCount, uint16 *entrySize) {
-	if (entryCount)
-		*entryCount = _soundEntryCount;
-
-	if (entrySize)
-		*entrySize = 8;
-}
-
 void ComfyEngine::stringTableSetCount(uint16 count) {
 	_stringCount = count + 1;
 }
@@ -443,7 +431,7 @@ bool ComfyEngine::sceneFrameInitTables(uint16 sceneCount, uint16 actorCount, uin
 		midiInitInstance();
 	}
 
-	if (!soundInit())
+	if (!((_isPanther || _engineVersion == 3) ? vocQueueInit() : soundInit()))
 		return false;
 
 	if (_isPanther || _engineVersion == 3) {
@@ -534,10 +522,10 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	uint16 midiEntrySize = 0;
 	midiFileGetEntryTableParams(&midiEntryCount, &midiEntrySize);
 	uint32 midiHeaderBytes = assetsAlignEven32((uint32)midiEntryCount * midiEntrySize);
-	uint16 soundEntryCount = 0;
-	uint16 soundEntrySize = 0;
-	soundGetHeaderTableParams(&soundEntryCount, &soundEntrySize);
-	uint32 soundHeaderBytes = assetsAlignEven32((uint32)soundEntryCount * soundEntrySize);
+	uint16 soundTileStride = 0;
+	uint16 soundFieldCount = 0;
+	soundGetTileParams(&soundTileStride, &soundFieldCount);
+	uint32 soundHeaderBytes = assetsAlignEven32((uint32)soundTileStride * soundFieldCount);
 	uint32 objectTableBytes = assetsAlignEven32((uint32)_numObjects * 0x11);
 	uint32 headerTotalBytes = midiHeaderBytes + soundHeaderBytes + objectTableBytes;
 	uint16 headerPages = (uint16)((headerTotalBytes + 0x400) / 0x400);
@@ -667,7 +655,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	_headerXmsSoundHeadersBytes = soundHeaderBytes;
 
 	if (soundHeaderBytes) {
-		byte *soundHeaderTable = soundReadHeaderTable();
+		byte *soundHeaderTable = soundReadTiledData();
 		if (!soundHeaderTable)
 			return false;
 
diff --git a/engines/comfy/midi.cpp b/engines/comfy/midi.cpp
index d70221d4d80..c20f02f4706 100644
--- a/engines/comfy/midi.cpp
+++ b/engines/comfy/midi.cpp
@@ -82,7 +82,8 @@ uint16 ComfyEngine::midiTick() {
 	}
 
 	while (_midiEvents.nextIndex != 999 && (int32)_midiInstanceEventTime >= _midiEvents.nextTime) {
-		keyBitSet(_midiEvents.entries[_midiEvents.nextIndex].id);
+		uint16 eventId = _midiEvents.entries[_midiEvents.nextIndex].id;
+		keyBitSet(eventId);
 		_midiEvents.count--;
 		_midiEvents.entries[_midiEvents.nextIndex] = _midiEvents.entries[_midiEvents.count];
 		midiFindNext(_midiEvents);
@@ -510,11 +511,7 @@ int16 ComfyEngine::midiApproachTarget(int16 current, int16 target, int16 &ticksL
 void ComfyEngine::musicSetEnabled(byte value) {
 	_musicEnabled = value;
 	if (!_animFrameReady || !_animUsesWaveVocCounter || value) {
-		_soundPaused = value != 0;
-		_mixer->pauseHandle(_soundHandle, _soundPaused);
-
-		if (_midiPlyrDriver)
-			_midiPlyrDriver->setIncreaseVocCounter(_soundPaused ? 0 : 1);
+		soundPauseOrResume(value);
 	}
 
 	if (!_midiPlyrDriver)
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index b2d570925d0..6d6c2e40f8b 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -91,7 +91,7 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 
 		WRITE_LE_UINT16(soundState + 0x68, _soundEventIndex);
 		WRITE_LE_UINT16(soundState + 0x6A, _soundEventMaximum);
-		soundPackState(soundState + 0x6C);
+		soundPackState();
 	}
 
 	byte *sceneEntries = &_sceneMemoryBlock[_sceneEntryListOffset];
@@ -224,6 +224,9 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 
 	if ((_engineVersion == 3 || _isPanther) && _usesAnimFile)
 		animFilePackState(&_sceneMemoryBlock[_sceneAnimStateOffset]);
+
+	if (_engineVersion == 3)
+		soundPackState();
 }
 
 void ComfyEngine::environmentPackToXms(byte *source, uint16 index) {
@@ -319,9 +322,14 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 
 		_soundEventIndex = READ_LE_UINT16(soundState + 0x68) % COMFY_PANTHER_VOC_QUEUE_CAPACITY;
 		_soundEventMaximum = READ_LE_UINT16(soundState + 0x6A) % COMFY_PANTHER_VOC_QUEUE_CAPACITY;
-		soundUnpackState(soundState + 0x6C);
 	}
 
+	if ((_engineVersion == 3 || _isPanther) && _usesAnimFile)
+		animFileUnpackState(&_sceneMemoryBlock[_sceneAnimStateOffset]);
+
+	if (_isPanther || _engineVersion == 3)
+		soundUnpackState();
+
 	byte *sceneEntries = &_sceneMemoryBlock[_sceneEntryListOffset];
 	_sceneEntryListActive = sceneEntries[0] != 0;
 	_sceneEntryCount = READ_LE_UINT16(sceneEntries + 1);
@@ -446,10 +454,6 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 
 	if (_keyBits && _keyBitsSize)
 		memcpy(_keyBits, &_sceneMemoryBlock[_sceneKeyBitsOffset], _keyBitsSize);
-
-	if ((_engineVersion == 3 || _isPanther) && _usesAnimFile)
-		animFileUnpackState(&_sceneMemoryBlock[_sceneAnimStateOffset]);
-
 }
 
 void ComfyEngine::sceneEntryInit(uint16 count) {
diff --git a/engines/comfy/sound.cpp b/engines/comfy/sound.cpp
index 8db112b26c7..8553db8d5c9 100644
--- a/engines/comfy/sound.cpp
+++ b/engines/comfy/sound.cpp
@@ -18,7 +18,6 @@
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
  */
-
 #include "comfy/comfy.h"
 #include "comfy/midiplyr/midiplyr.h"
 
@@ -27,783 +26,1229 @@
 #include "common/debug.h"
 #include "common/endian.h"
 
-#define COMFY_ANM_COMMAND_END 0x2145
-#define COMFY_ANM_COMMAND_STORE_FRAME_BYTES 0x4356
-#define COMFY_ANM_COMMAND_FRAME 0x5246
+#define SOUND_CMD_START 0
+#define SOUND_CMD_BEGIN_EVENT 1
+#define SOUND_CMD_BEGIN_LOOP_EVENT 2
+#define SOUND_CMD_FILL_OR_SAMPLE_DELAY 3
+#define SOUND_CMD_PITCH_CHANGE 4
+#define SOUND_CMD_LOOP_START 6
+#define SOUND_CMD_LOOP_END 7
+#define SOUND_CMD_SET_SAMPLE 99
 
 namespace Comfy {
 
-struct SoundDecoderState {
-public:
-	// soundPrepareDecoderState() collects an embedded ANM sound into one temporary buffer.
-	// This constructor copies those bytes, so decoding no longer needs the engine or a file...
-	SoundDecoderState(const byte *data, uint32 size, bool compressed) {
-		_data.resize(size);
-		if (size)
-			memcpy(&_data[0], data, size);
-
-		_compressed = compressed;
-		_end = size;
-		_windowEnd = size;
-
-		if (_compressed) {
-			if (size < 5) {
-				_fault = true;
-				return;
-			}
+byte ComfyEngine::soundOpenEntry(uint16 index) {
+	uint32 dataSize = 0;
+	uint32 dataOffset = 0;
 
-			setSample(_data[4]);
-			_position = 5;
-		} else if (size >= 6 && _data[0] == 1) {
-			setSample(_data[4]);
-		} else {
-			setSample(_sample);
+	_soundFault = false;
+	_soundFinished = false;
+	_soundHistory.clear();
+	_soundSourceWindowStart = 0;
+	_soundSourceWindowEnd = 0;
+	_soundDecoderData.clear();
+	_soundUsesAnimData = index == 0xFFFF;
+	_soundRate = 0;
+
+	if (_soundUsesAnimData) {
+		uint32 storedSize = READ_LE_UINT32(_animFrameHeader + 4);
+		if (!storedSize) {
+			_soundFault = true;
+			return 0;
 		}
-	}
 
-	// A regular VOC entry remains in VOCFILE.DAT. This constructor retains the engine and
-	// file object so loadSourceWindow() can read each block through objFileReadTiledCore().
-	SoundDecoderState(ComfyEngine *engine, ComfyEngine::ObjFile *objectFile, uint32 sourceBase, uint32 size, bool compressed) {
-		_engine = engine;
-		_objectFile = objectFile;
-		_sourceBase = sourceBase;
-		_compressed = compressed;
-		_end = size;
+		dataSize = storedSize;
+		_soundDataBase = 0;
+		_soundHeaderEnd = dataSize;
+		_soundDataEnd = dataSize;
+		_soundCompressed = false;
+		animFileRestoreSoundStorage(0);
 
-		if (!loadSourceWindow(6)) {
-			_fault = true;
-			return;
+		if (_soundFault)
+			return 0;
+	} else {
+		byte header[8];
+		memset(header, 0, sizeof(header));
+		soundReadHeader(header, index, sizeof(header));
+		dataSize = READ_LE_UINT32(header);
+		dataOffset = READ_LE_UINT32(header + 4);
+
+		if (!_vocFile || dataOffset > _vocFile->fileSize || dataSize > _vocFile->fileSize - dataOffset) {
+			_soundFault = true;
+			return 0;
 		}
 
-		if (_compressed) {
-			if (size < 5) {
-				_fault = true;
-				return;
-			}
+		_soundDataBase = dataOffset;
+		_soundSourceBase = dataOffset;
+		_soundHeaderEnd = dataSize;
+	}
 
-			setSample(sourceByte(4));
-			_position = 5;
-		} else if (size >= 6 && sourceByte(0) == 1) {
-			setSample(sourceByte(4));
-		} else {
-			setSample(_sample);
+	_soundDataEnd = dataSize;
+	_soundPlayPosition = 0;
+	_soundCursor = 0;
+	_soundBlockBase = 0;
+	_soundLoopPosition = 0;
+	_soundBitOffset = 0;
+	_soundLoopBitOffset = 0;
+	_soundBlockOffset = 0;
+	_soundBitAccumulator = 1;
+	_soundBitWidth = 4;
+	_soundPredictorDistance = 1;
+	_soundNeedInit = false;
+	_soundFillCount = 0;
+	_soundEventLength = 0;
+	_soundEventRemaining = 0;
+	_soundLoopCount = 0;
+	_soundStarted = false;
+	_soundDecodeBlockSize = _isPanther ? COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES :
+		(_engineVersion == 3 ? COMFY_V3_SOUND_PCM_BLOCK_BYTES : COMFY_SOUND_PCM_BLOCK_BYTES);
+
+	if (_soundCompressed) {
+		if (dataSize < 5) {
+			_soundFault = true;
+			return 0;
 		}
+
+		byte compressedHeader[4];
+		objFileReadFieldCore(compressedHeader, dataOffset, sizeof(compressedHeader), _vocFile);
+		_soundHeaderEnd = READ_LE_UINT32(compressedHeader);
+		objFileReadFieldCore(&_soundSample, dataOffset + 4, 1, _vocFile);
+		_soundPlayPosition = 5;
 	}
 
-	uint32 decode(byte *buffer, uint32 size) {
-		_decodeBlockSize = size;
-		if (_objectFile && !_started && !loadSourceWindow(size))
-			return 0;
+	return _soundFault ? 0 : _soundSample;
+}
 
-		uint32 written = 0;
-		while (written < size && !_fault && !_finished) {
-			byte sample = 0x80;
-			if (!readSample(sample))
-				break;
 
-			buffer[written++] = sample;
+void ComfyEngine::setWaveBalancePercent(uint16 value) {
+	if ((int16)value < 0) {
+		value = 0;
+	} else if (value > 100) {
+		value = 100;
+	}
+
+	_v3SceneWaveBalancePercent = (byte)value;
+	_v3WaveBalancePercent = value;
+}
+
+void ComfyEngine::setWaveLeftPercent(uint16 value) {
+	if (value == 0x00FF)
+		return;
+
+	if ((int16)value < 0) {
+		value = 0;
+	} else if (value > 100) {
+		value = 100;
+	}
+
+	_v3SceneWaveLeftPercent = (byte)value;
+	_v3WaveLeftPercent = value;
+}
+
+void ComfyEngine::setWaveRightPercent(uint16 value) {
+	if (value == 0x00FF)
+		return;
+
+	if ((int16)value < 0) {
+		value = 0;
+	} else if (value > 100) {
+		value = 100;
+	}
+
+	_v3SceneWaveRightPercent = (byte)value;
+	_v3WaveRightPercent = value;
+}
+
+void ComfyEngine::setMixerVolumePercent(uint16 value) {
+	if (value == 0x00FF)
+		return;
+
+	if ((int16)value < 0) {
+		value = 0;
+	} else if (value > 100) {
+		value = 100;
+	}
+
+	_v3SceneMixerVolumePercent = (byte)value;
+	_v3MixerVolumePercent = value;
+}
+
+void ComfyEngine::setMediaRangePercent(uint16 value) {
+	if ((int16)value < 0) {
+		value = 0;
+	} else if (value > 100) {
+		value = 100;
+	}
+
+	_v3MixerAltPercent = value;
+}
+
+void ComfyEngine::setMediaMode(byte mode) {
+	if (mode == 1 || mode == 3) {
+		_v3SceneMediaModeEnabled = 1;
+
+		if (!_v3MediaValueAvailable) {
+			_v3MediaValue = 0;
+			_v3MediaValueAvailable = true;
 		}
+	} else if (mode == 2) {
+		_v3SceneMediaModeEnabled = 0;
+		_v3MediaValue = 0;
+		_v3MediaValueAvailable = false;
+	}
+}
+
+void ComfyEngine::restoreWaveStateAfterSceneStart() {
+	setWaveBalancePercent(_v3SceneWaveBalancePercent);
+	setWaveLeftPercent(_v3SceneWaveLeftPercent);
+	setWaveRightPercent(_v3SceneWaveRightPercent);
+	setMixerVolumePercent(_v3SceneMixerVolumePercent);
 
-		return written;
+	if (_v3SceneMediaModeEnabled) {
+		setMediaMode(2);
+		setMediaMode(1);
+	} else {
+		setMediaMode(2);
 	}
+}
 
-	uint32 getRate() {
-		return _sampleRate;
+bool ComfyEngine::soundOpenVocFile() {
+	soundFreeBuffer();
+	uint32 maximumBytes = 0x40000;
+
+	if (sysGetExtMemKB() < 4000)
+		maximumBytes /= 2;
+
+	_vocFile = soundLoadSoundData(Common::Path("VOCFILE.DAT"), 0x8000, maximumBytes);
+	if (!_vocFile)
+		return false;
+
+	byte header[4];
+	memset(header, 0, sizeof(header));
+	objFileReadFieldCore(header, 0, sizeof(header), _vocFile);
+
+	if (header[0] != 'C' || (header[1] != 'V' && header[1] != 'W')) {
+		objFileClose(_vocFile);
+		return false;
 	}
 
-	void copyCues(Common::Array<ComfyEngine::SoundCue> &cues) {
-		cues = _cues;
+	_soundCompressed = !_isPanther && header[1] == 'W';
+	_soundUsesAnimData = false;
+	_soundTileStride = READ_LE_UINT16(header + 2);
+	return true;
+}
+
+bool ComfyEngine::soundInit() {
+	_soundEventIndex = 0;
+	_soundEventMaximum = 0;
+	waveOutOpen();
+
+	return soundOpenVocFile();
+}
+
+bool ComfyEngine::vocQueueInit() {
+	_soundEventIndex = 0;
+	_soundEventMaximum = 0;
+
+	if (_isPanther) {
+		soundInitRuntimeState(&_sceneMemoryBlock[_sceneSoundStateOffset + 0x6C]);
+	} else if (_engineVersion == 3) {
+		soundInitRuntimeState(&_sceneMemoryBlock[_sceneMidiInstanceOffset + COMFY_SCENE_MIDI_INSTANCE_BYTES + 0x1FB]);
 	}
 
-	bool fault() {
-		return _fault;
+	soundInitOutput();
+
+	if (!soundOpenVocFile())
+		return false;
+
+	if (_engineVersion == 3)
+		setMediaMode(2);
+
+	return true;
+}
+
+void ComfyEngine::soundInitOutput() {
+	uint32 blockSize = _isPanther ? COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES :
+		(_engineVersion == 3 ? COMFY_V3_SOUND_PCM_BLOCK_BYTES : COMFY_SOUND_PCM_BLOCK_BYTES);
+
+	soundAllocBuffers((uint16)blockSize);
+	_soundStopped = true;
+}
+
+void ComfyEngine::waveOutOpen() {
+	soundAllocBuffers((uint16)COMFY_SOUND_PCM_BLOCK_BYTES);
+	_soundStopped = true;
+}
+
+void ComfyEngine::soundAllocBuffers(uint16 size) {
+	// The original allocates one block with 0x80 bytes of headroom and uses two
+	// aliases into it for the compressed decoder's interleave operation...
+	_soundPcmBlocks[0].resize(size);
+	_soundPcmBlocks[1].resize(size);
+	_soundInterleaveStorage.resize((uint32)size * 4 + 0x80);
+	_soundInterleavePointer = &_soundInterleaveStorage[0] + 0x80;
+}
+
+void ComfyEngine::soundFreePcmBuf() {
+	_soundPcmBlocks[0].clear();
+	_soundPcmBlocks[1].clear();
+	_soundInterleaveStorage.clear();
+	_soundInterleavePointer = nullptr;
+	_soundRate = 0;
+}
+
+void ComfyEngine::soundPauseOutput() {
+	if (_engineVersion == 3)
+		_soundCounterEnabled = false;
+
+	if (_midiPlyrDriver)
+		_midiPlyrDriver->setIncreaseVocCounter(0);
+
+	_soundPaused = true;
+
+	if ((_engineVersion != 3 && !_isPanther) || !_soundStopped)
+		waveOutPause();
+}
+
+void ComfyEngine::soundResumeOutput() {
+	if (_engineVersion == 3) {
+		_soundCounterEnabled = true;
 	}
 
-	void saveBufferState(uint16 bufferIndex) {
-		if (bufferIndex >= 2)
-			return;
+	if (_midiPlyrDriver)
+		_midiPlyrDriver->setIncreaseVocCounter(1);
 
-		BufferState &state = _bufferStates[bufferIndex];
-		state.streamPosition = _streamPosition;
-		state.position = _position;
-		state.loopPosition = _loopPosition;
-		state.eventRemaining = _eventRemaining;
-		state.fillRemaining = _fillRemaining;
-		state.loopCount = _loopCount;
-		state.started = _started;
+	_soundPaused = false;
+
+	if (_engineVersion == 3) {
+		if (!_soundStopped)
+			waveOutRestart();
+
+		_soundTimingPaused = true;
+	} else if (!_isPanther || !_soundStopped) {
+		waveOutRestart();
 	}
 
-	uint32 getBufferStreamPosition(uint16 bufferIndex) {
-		return bufferIndex < 2 ? _bufferStates[bufferIndex].streamPosition : 0;
+	if (_isPanther)
+		_soundTimingPaused = true;
+}
+
+void ComfyEngine::soundPauseOrResume(byte pause) {
+	if (pause) {
+		soundPauseOutput();
+	} else {
+		soundResumeOutput();
 	}
+}
 
-	void packState(byte *packedState, uint16 bufferIndex, uint32 playbackPosition, uint32 vocCounter,
-			bool stopped, bool usesAnimData, Common::Array<ComfyEngine::SoundCue> &cues, uint nextCue) {
+void ComfyEngine::soundStopAllAndReset() {
+	_soundStopped = true;
+	waveOutReset();
+	_soundCues.clear();
+}
 
-		memset(packedState, 0, 0x52);
-		packedState[0x3F] = stopped;
-		if (stopped || bufferIndex >= 2)
-			return;
+void ComfyEngine::soundPrepareQueuePlayback() {
+	soundStopAllAndReset();
+	_soundCounterEnabled = false;
+	_soundEventSubIndex = 0;
+	_midiCounterAdjustment = 0;
 
-		BufferState &state = _bufferStates[bufferIndex];
-		WRITE_LE_UINT32(packedState, state.streamPosition);
-		packedState[4] = state.started;
-		WRITE_LE_UINT16(packedState + 5, (uint16)state.fillRemaining);
-		WRITE_LE_UINT32(packedState + 7, state.eventRemaining);
-		WRITE_LE_UINT16(packedState + 0x0B, (uint16)state.loopCount);
-		WRITE_LE_UINT32(packedState + 0x0D, playbackPosition);
-		WRITE_LE_UINT32(packedState + 0x11, vocCounter);
-		uint16 packedCueCount = 0;
-
-		while (nextCue < cues.size() && packedCueCount < 4 && cues[nextCue].streamPosition < playbackPosition) {
-			WRITE_LE_UINT16(packedState + 0x15 + packedCueCount * 2, cues[nextCue].value);
-			WRITE_LE_UINT32(packedState + 0x1D + packedCueCount * 4, cues[nextCue].streamPosition);
-			WRITE_LE_UINT32(packedState + 0x2D + packedCueCount * 4, cues[nextCue].counterThreshold);
-			packedCueCount++;
-			nextCue++;
-		}
+	if (_midiPlyrDriver)
+		_midiPlyrDriver->vocSrResetBlockNo();
+}
+
+void ComfyEngine::soundStopPlayback() {
+	soundStopAllAndReset();
 
-		WRITE_LE_UINT16(packedState + 0x3D, packedCueCount);
-		packedState[0x40] = _sample;
-		WRITE_LE_UINT32(packedState + 0x41, state.position);
-		WRITE_LE_UINT32(packedState + 0x45, state.loopPosition);
-		WRITE_LE_UINT32(packedState + 0x49, _end);
-		WRITE_LE_UINT32(packedState + 0x4D, 0);
-		packedState[0x51] = usesAnimData;
+	if (_isPanther) {
+		_soundVocTimingDelta = 0;
+
+		if (_midiPlyrDriver)
+			_midiPlyrDriver->vocSrResetBlockNo();
 	}
+}
 
-	bool unpackState(byte *packedState, Common::Array<ComfyEngine::SoundCue> &cues,
-			uint32 &vocCounter) {
-		if (packedState[0x3F])
-			return false;
+void ComfyEngine::soundCloseVocFile() {
+	objFileClose(_vocFile);
+}
 
-		_streamPosition = READ_LE_UINT32(packedState);
-		_started = packedState[4] != 0;
-		_fillRemaining = READ_LE_UINT16(packedState + 5);
-		_eventRemaining = READ_LE_UINT32(packedState + 7);
-		_loopCount = (int16)READ_LE_UINT16(packedState + 0x0B);
-		uint32 playbackPosition = READ_LE_UINT32(packedState + 0x0D);
-		vocCounter = READ_LE_UINT32(packedState + 0x11);
-		setSample(packedState[0x40]);
-		_position = READ_LE_UINT32(packedState + 0x41);
-		_loopPosition = READ_LE_UINT32(packedState + 0x45);
-		uint32 packedEnd = READ_LE_UINT32(packedState + 0x49);
-
-		if (_position > _end || _loopPosition > _end || packedEnd > _end)
-			return false;
+void ComfyEngine::soundFreeBuffer() {
+	objFileClose(_vocFile);
+}
 
-		_end = packedEnd;
-		_bitOffset = 0;
-		_loopBitOffset = 0;
-		_blockOffset = 0;
-		_fault = false;
-		_finished = false;
-		_cues.clear();
+ComfyEngine::ObjFile *ComfyEngine::soundLoadSoundData(const Common::Path &path, uint16 blockSize, uint32 maximumBytes) {
+	return objFileOpen(path, blockSize, maximumBytes);
+}
 
-		uint16 advanceSize = (uint16)(playbackPosition - _streamPosition);
-		if (advanceSize > COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES)
-			advanceSize = COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES;
+void ComfyEngine::waveOutReset() {
+	_mixer->stopHandle(_soundHandle);
+	_soundQueueStream = nullptr;
+}
 
-		if (advanceSize) {
-			Common::Array<byte> discardedPcm;
-			discardedPcm.resize(advanceSize);
+void ComfyEngine::waveOutPause() {
+	_mixer->pauseHandle(_soundHandle, true);
+}
 
-			if (decode(&discardedPcm[0], advanceSize) != advanceSize)
-				return false;
-		}
+void ComfyEngine::waveOutRestart() {
+	_mixer->pauseHandle(_soundHandle, false);
+}
 
-		_cues.clear();
-		cues.clear();
-		uint16 cueCount = MIN<uint16>(READ_LE_UINT16(packedState + 0x3D), 4);
+void ComfyEngine::soundShutdown() {
+	if (_isPanther) {
+		soundStopPlayback();
+	} else {
+		soundStopAllAndReset();
+	}
 
-		for (uint16 i = 0; i < cueCount; i++) {
-			ComfyEngine::SoundCue cue;
-			cue.value = READ_LE_UINT16(packedState + 0x15 + i * 2);
-			cue.streamPosition = READ_LE_UINT32(packedState + 0x1D + i * 4);
-			cue.counterThreshold = READ_LE_UINT32(packedState + 0x2D + i * 4);
-			_cues.push_back(cue);
-			cues.push_back(cue);
-		}
+	soundFreePcmBuf();
+	_soundDecoderData.clear();
+	_soundHistory.clear();
+	_soundFault = false;
+	_soundFinished = false;
+	_soundCues.clear();
 
-		return true;
+	if (_isPanther) {
+		soundCloseVocFile();
+	} else {
+		soundFreeBuffer();
 	}
 
-private:
-	struct BufferState {
-		uint32 streamPosition = 0;
-		uint32 position = 0;
-		uint32 loopPosition = 0;
-		uint32 eventRemaining = 0;
-		uint32 fillRemaining = 0;
-		int16 loopCount = 0;
-		bool started = false;
-	};
+	_soundTileStride = 0;
+	_soundHeaderEnd = 0;
+	_soundStopped = true;
+	_soundPaused = false;
+	_soundCounterEnabled = false;
+	_soundUsesAnimData = false;
+	_soundTimingPaused = false;
+	_soundVocBlockCount = 0;
+	_soundVocCounterSnapshot = 0;
+	_soundPackedState = nullptr;
+	_soundBufferState = nullptr;
 
-	bool loadSourceWindow(uint32 size) {
-		if (!_objectFile)
-			return true;
+	if (_midiPlyrDriver)
+		_midiPlyrDriver->setIncreaseVocCounter(0);
+}
 
-		if (!_engine || _position > _end)
-			return false;
+void ComfyEngine::soundReadHeader(byte *destination, uint16 index, uint16 size) {
+	objHdrReadFromXms(destination, _headerXmsSoundHeadersBase, size, index);
+}
 
-		uint32 remaining = _end - _position;
-		uint32 readSize = MIN<uint32>(size, remaining);
+byte *ComfyEngine::soundReadTiledData() {
+	return _vocFile ? objFileReadTiled(4, (uint32)_soundTileStride * 8, _vocFile) : nullptr;
+}
 
-		if (!_compressed)
-			readSize += 0xC8;
+void ComfyEngine::soundGetTileParams(uint16 *tileStride, uint16 *fieldCount) {
+	if (tileStride)
+		*tileStride = _soundTileStride;
 
-		uint32 fileOffset = _sourceBase + _position;
-		if (fileOffset > _objectFile->fileSize)
-			return false;
+	if (fieldCount)
+		*fieldCount = 8;
+}
 
-		if (readSize > _objectFile->fileSize - fileOffset)
-			readSize = _objectFile->fileSize - fileOffset;
+bool ComfyEngine::soundLoadSourceWindow(uint32 size) {
+	if (_soundUsesAnimData)
+		return _soundPlayPosition <= _soundDataEnd;
 
-		if (!readSize) {
-			_data.clear();
-			_windowStart = _position;
-			_windowEnd = _position;
-			return true;
-		}
+	if (!_vocFile || _soundPlayPosition > _soundDataEnd)
+		return false;
 
-		byte *source = _engine->objFileReadTiledCore(fileOffset, readSize, _objectFile);
-		if (!source)
-			return false;
+	uint32 remaining = _soundDataEnd - _soundPlayPosition;
+	uint32 readSize = MIN<uint32>(size, remaining);
 
-		_data.resize(readSize);
-		memcpy(&_data[0], source, readSize);
-		_windowStart = _position;
-		_windowEnd = _position + readSize;
+	if (!_soundCompressed)
+		readSize += 0xC8;
+
+	uint32 fileOffset = _soundSourceBase + _soundPlayPosition;
+	if (fileOffset > _vocFile->fileSize)
+		return false;
+
+	if (readSize > _vocFile->fileSize - fileOffset)
+		readSize = _vocFile->fileSize - fileOffset;
+
+	if (!readSize) {
+		_soundDecoderData.clear();
+		_soundSourceWindowStart = _soundPlayPosition;
+		_soundSourceWindowEnd = _soundPlayPosition;
 		return true;
 	}
 
-	byte sourceByte(uint32 position) {
-		if (position >= _end) {
-			_fault = true;
+	byte *source = objFileReadTiledCore(fileOffset, readSize, _vocFile);
+	if (!source)
+		return false;
+
+	_soundDecoderData.resize(readSize);
+	memcpy(&_soundDecoderData[0], source, readSize);
+	_soundSourceWindowStart = _soundPlayPosition;
+	_soundSourceWindowEnd = _soundPlayPosition + readSize;
+
+	return true;
+}
+
+byte ComfyEngine::soundReadSourceByte(uint32 position) {
+	if (position >= _soundDataEnd) {
+		_soundFault = true;
+		return 0;
+	}
+
+	if (_soundUsesAnimData) {
+		if (position >= _soundDecoderData.size()) {
+			_soundFault = true;
 			return 0;
 		}
 
-		if (_objectFile && (position < _windowStart || position >= _windowEnd)) {
-			uint32 savedPosition = _position;
-			_position = position;
-			bool loaded = loadSourceWindow(_decodeBlockSize ? _decodeBlockSize : 6);
-			_position = savedPosition;
+		return _soundDecoderData[position];
+	}
 
-			if (!loaded) {
-				_fault = true;
-				return 0;
-			}
+	if (position < _soundSourceWindowStart || position >= _soundSourceWindowEnd) {
+		bool loaded = false;
+
+		if (_isPanther || _engineVersion == 3) {
+			uint32 savedPosition = _soundPlayPosition;
+			uint32 savedCursor = _soundCursor;
+			uint32 savedBlockBase = _soundBlockBase;
+			uint16 savedBitOffset = _soundBitOffset;
+			_soundPlayPosition = position;
+			soundLoadDataBlock((uint16)(_soundDecodeBlockSize ? _soundDecodeBlockSize : 6));
+			loaded = !_soundFault;
+			_soundPlayPosition = savedPosition;
+			_soundCursor = savedCursor;
+			_soundBlockBase = savedBlockBase;
+			_soundBitOffset = savedBitOffset;
+		} else {
+			uint32 savedPosition = _soundPlayPosition;
+			_soundPlayPosition = position;
+			loaded = soundLoadSourceWindow(_soundDecodeBlockSize ? _soundDecodeBlockSize : 6);
+			_soundPlayPosition = savedPosition;
 		}
 
-		uint32 offset = position - _windowStart;
-		if (offset >= _data.size()) {
-			_fault = true;
+		if (!loaded) {
+			_soundFault = true;
 			return 0;
 		}
+	}
 
-		return _data[offset];
+	uint32 offset = position - _soundSourceWindowStart;
+	if (offset >= _soundDecoderData.size()) {
+		_soundFault = true;
+		return 0;
 	}
 
-	static uint32 calcSampleRate(byte sample) {
-		uint32 denominator = 256 - sample;
-		uint32 rate = denominator ? 1000000 / denominator : 11025;
-		if (rate > 10000 && rate < 12000)
-			return 11025;
+	return _soundDecoderData[offset];
+}
+
+uint32 ComfyEngine::soundCalcSampleRate(byte &sample) {
+	if (_engineVersion != 3 && !_isPanther && _midiPlyrDriver) {
+		uint32 timeFrac = 0;
+		uint16 blockNo = 0;
 
-		if (rate > 20000 && rate < 24000)
-			return 22050;
+		_midiPlyrDriver->vocSrGetCounters(timeFrac, blockNo);
 
-		return rate;
+		if (blockNo && timeFrac)
+			return ((uint32)blockNo * 0x1E8480) / timeFrac;
 	}
 
-	void setSample(byte sample) {
-		_sample = sample;
-		_sampleRate = calcSampleRate(sample);
-		if (_sampleRate == 11025)
-			_sample = 0xA5;
-		else if (_sampleRate == 22050)
-			_sample = 0xD3;
+	uint32 denominator = 0x100 - sample;
+	uint32 rate = 1000000 / denominator;
+
+	if (rate > 10000 && rate < 12000) {
+		rate = 11025;
+		sample = 0xA5;
+	} else if (rate > 20000 && rate < 24000) {
+		rate = 22050;
+		sample = 0xD3;
 	}
 
-	bool readSample(byte &sample) {
-		for (;;) {
-			if (_started) {
-				_streamPosition++;
-				sample = 0x80;
-				return true;
-			}
+	return rate;
+}
 
-			if (_fillRemaining) {
-				_fillRemaining--;
-				_streamPosition++;
-				sample = 0x80;
-				return true;
-			}
+uint16 ComfyEngine::soundBitRead(uint16 bits) {
+	uint16 raw = (uint16)soundReadSourceByte(_soundCursor) | (uint16)(soundReadSourceByte(_soundCursor + 1) << 8);
+	raw >>= _soundBitOffset;
+	raw &= (uint16)((1U << bits) - 1);
+	_soundBitOffset = (uint16)(_soundBitOffset + bits);
+	_soundCursor += _soundBitOffset >> 3;
+	_soundBitOffset &= 7;
 
-			if (_eventRemaining) {
-				if (!copySample(sample))
-					return false;
+	return raw;
+}
 
-				_eventRemaining--;
-				_streamPosition++;
-				return true;
-			}
+uint32 ComfyEngine::soundBitRead32(uint16 bits) {
+	uint32 raw = (uint32)soundReadSourceByte(_soundCursor) |
+			((uint32)soundReadSourceByte(_soundCursor + 1) << 8) |
+			((uint32)soundReadSourceByte(_soundCursor + 2) << 16) |
+			((uint32)soundReadSourceByte(_soundCursor + 3) << 24);
 
-			uint16 command = parseCommand();
-			if (_fault)
-				return false;
-
-			switch (command) {
-			case 0:
-				pushCue(0);
-				_started = true;
-				break;
-
-			case 1:
-				beginEvent(false);
-				break;
-
-			case 2:
-				beginEvent(true);
-				break;
-
-			case 3:
-				readFillCommand();
-				break;
-
-			case 4:
-				pushCue(readParam());
-				break;
-
-			case 6:
-				_loopCount = (int16)readWord();
-				_loopPosition = _position;
-				_loopBitOffset = _bitOffset;
-				break;
-
-			case 7:
-				if (_loopCount > 0) {
-					_loopCount--;
-					// The original reloads the loop position twice...
-					seekToLoop();
-					seekToLoop();
-				}
-				break;
-
-			case 99:
-				setSample((byte)readBits(8));
-				break;
-
-			default:
-				break;
-			}
-		}
+	raw >>= _soundBitOffset;
+	raw &= (1U << bits) - 1;
+	_soundCursor += bits >> 3;
+	_soundBitOffset = (uint16)(_soundBitOffset + (bits & 7));
+
+	if (_soundBitOffset >= 8) {
+		_soundBitOffset = (uint16)(_soundBitOffset - 8);
+		_soundCursor++;
 	}
 
-	void seekToLoop() {
-		_position = _loopPosition;
-		_bitOffset = _loopBitOffset;
+	return raw;
+}
+
+void ComfyEngine::soundResetBitState() {
+	_soundBitAccumulator = 1;
+	_soundBitWidth = 4;
+}
 
-		if (_objectFile && !loadSourceWindow(_decodeBlockSize))
-			_fault = true;
+void ComfyEngine::soundReadFreqWord(uint16 &value) {
+	if (_soundCompressed) {
+		value = (uint16)soundBitRead32(16);
+		return;
 	}
 
-	uint16 parseCommand() {
-		_eventArgument = 0;
-		if (!_compressed) {
-			if (_position >= _end) {
-				_fault = true;
-				return 0;
-			}
+	value = (uint16)(soundReadSourceByte(_soundCursor) | (soundReadSourceByte(_soundCursor + 1) << 8));
+	_soundCursor += 2;
+}
 
-			uint16 command = sourceByte(_position++);
-			if (command) {
-				if (_end - _position < 3) {
-					_fault = true;
-					return 0;
-				}
+void ComfyEngine::soundReadParam(uint16 &value) {
+	if (!_soundCompressed) {
+		soundReadFreqWord(value);
+		return;
+	}
 
-				_eventArgument = (uint32)sourceByte(_position) | ((uint32)sourceByte(_position + 1) << 8) |
-					((uint32)sourceByte(_position + 2) << 16);
-				_position += 3;
-			}
+	switch (soundBitRead(2)) {
+	case 0:
+		value = 1;
+		break;
+	case 1:
+		value = 2;
+		break;
+	case 2:
+		value = soundBitRead(8);
+		break;
+	case 3:
+		value = soundBitRead(16);
+		break;
+	default:
+		value = 0;
+		break;
+	}
+}
 
-			return command;
-		}
+byte ComfyEngine::soundReadSampleByte() {
+	return (byte)soundBitRead(8);
+}
 
-		uint16 command = (uint16)readBits(2);
-		if (!command) {
-			uint16 subcommand = (uint16)readBits(2);
-			if (!subcommand)
-				return 0;
+void ComfyEngine::soundSaveLoopPosition() {
+	_soundLoopPosition = _soundPlayPosition;
+	if (_soundCompressed)
+		_soundLoopBitOffset = _soundBitOffset;
+}
 
-			if (subcommand == 1) {
-				command = (uint16)readBits(8);
-				_eventArgument = readBits(20);
-				return command;
-			}
+void ComfyEngine::soundSeekToLoop(uint16 size) {
+	_soundPlayPosition = _soundLoopPosition;
+
+	if (_isPanther || _engineVersion == 3) {
+		soundLoadDataBlock(size);
+	} else {
+		soundDecompressBlock(size);
+	}
 
-			return subcommand == 2 ? 7 : 99;
+	if (_soundCompressed)
+		_soundBitOffset = _soundLoopBitOffset;
+}
+
+void ComfyEngine::soundReadLoopEntry(uint16 &frequency, byte &sample) {
+	if (_soundCompressed) {
+		frequency = (uint16)soundBitRead32(0x10);
+		sample = _soundSample;
+		return;
+	}
+
+	frequency = (uint16)(soundReadSourceByte(_soundCursor) | (soundReadSourceByte(_soundCursor + 1) << 8));
+	sample = soundReadSourceByte(_soundCursor + 2);
+	_soundCursor += 3;
+}
+
+void ComfyEngine::soundBeginEvent(bool loop) {
+	_soundEventLength = (int32)_soundEventArgument;
+	if (_soundCompressed) {
+		_soundNeedInit = true;
+		return;
+	}
+
+	if (loop)
+		return;
+
+	if (_soundEventLength < 2 || _soundCursor + 2 > _soundDataEnd) {
+		_soundFault = true;
+		return;
+	}
+
+	_soundEventLength -= 2;
+	_soundSample = soundReadSourceByte(_soundCursor);
+	_soundCursor += 2;
+}
+
+uint16 ComfyEngine::soundParseCommand() {
+	_soundEventArgument = 0;
+
+	if (!_soundCompressed) {
+		uint16 command = soundReadSourceByte(_soundCursor++);
+		if (command) {
+			_soundEventArgument = (uint32)soundReadSourceByte(_soundCursor) |
+					((uint32)soundReadSourceByte(_soundCursor + 1) << 8) |
+					((uint32)soundReadSourceByte(_soundCursor + 2) << 16);
 		}
 
-		if (command == 1) {
-			_eventArgument = readBits(20);
-			return 1;
+		_soundCursor += 3;
+		return command;
+	}
+
+	uint16 command = soundBitRead(2);
+	bool hasArgument = false;
+	switch (command) {
+	case 0:
+		switch (soundBitRead(2)) {
+		case 0:
+			command = SOUND_CMD_START;
+			break;
+		case 1:
+			command = soundBitRead(8);
+			hasArgument = true;
+			break;
+		case 2:
+			command = SOUND_CMD_LOOP_END;
+			break;
+		case 3:
+			command = SOUND_CMD_SET_SAMPLE;
+			break;
 		}
 
-		return command == 2 ? 3 : 4;
+		break;
+	case 1:
+		command = SOUND_CMD_BEGIN_EVENT;
+		hasArgument = true;
+		break;
+	case 2:
+		command = SOUND_CMD_FILL_OR_SAMPLE_DELAY;
+		break;
+	case 3:
+		command = SOUND_CMD_PITCH_CHANGE;
+		break;
 	}
 
-	void beginEvent(bool loop) {
-		_eventRemaining = _eventArgument;
-		if (_compressed) {
-			_needInit = true;
-			return;
+	if (hasArgument)
+		_soundEventArgument = soundBitRead32(20);
+
+	return command;
+}
+
+void ComfyEngine::soundDecodeBits(uint16 size, byte mode) {
+	if (!_soundWritePointer || !size)
+		return;
+
+	uint32 source = _soundCursor;
+	uint16 bitOffset = _soundBitOffset;
+	uint32 raw = (uint32)soundReadSourceByte(source) |
+			((uint32)soundReadSourceByte(source + 1) << 8) |
+			((uint32)soundReadSourceByte(source + 2) << 16) |
+			((uint32)soundReadSourceByte(source + 3) << 24);
+
+	raw >>= bitOffset & 7;
+
+	if (mode & 1) {
+		if (raw & 1) {
+			raw >>= 1;
+			_soundBitWidth = (byte)(raw & 7);
+			bitOffset = (uint16)(bitOffset + 3);
+			raw >>= 2;
 		}
 
-		if (loop)
-			return;
+		raw >>= 1;
+		bitOffset = (uint16)(bitOffset + 1);
+
+		if (!_soundBitWidth) {
+			source += bitOffset >> 3;
+			bitOffset &= 7;
 
-		if (_eventRemaining < 2 || _end - _position < 2) {
-			_fault = true;
+			while (size--) {
+				uint16 sampleWord = (uint16)(soundReadSourceByte(source) | (soundReadSourceByte(source + 1) << 8));
+				byte sample = (byte)(sampleWord >> bitOffset);
+				_soundHistory.push_back(sample);
+				*_soundWritePointer++ = sample;
+				source++;
+			}
+
+			_soundCursor = source;
+			_soundBitOffset = bitOffset;
 			return;
 		}
 
-		_eventRemaining -= 2;
-		setSample(sourceByte(_position));
-		_position += 2;
+		if (raw & 1) {
+			raw >>= 1;
+			bitOffset = (uint16)(bitOffset + 7);
+			// The original writes only the low byte of this word-sized global...
+			_soundBitAccumulator = (byte)raw;
+		}
+
+		bitOffset = (uint16)(bitOffset + 1);
 	}
 
-	void readFillCommand() {
-		uint16 count = readWord();
-		byte nextSample = _compressed ? _sample : readByte();
-		if (_fault)
-			return;
+	if (!_soundBitWidth) {
+		source += bitOffset >> 3;
+		bitOffset &= 7;
 
-		_fillRemaining = count;
-		if (nextSample != _sample) {
-			uint32 oldRate = calcSampleRate(_sample);
-			uint32 newRate = calcSampleRate(nextSample);
-			if (newRate)
-				_fillRemaining = ((uint32)_fillRemaining * oldRate) / newRate;
+		while (size--) {
+			uint16 sampleWord = (uint16)(soundReadSourceByte(source) | (soundReadSourceByte(source + 1) << 8));
+			byte sample = (byte)(sampleWord >> bitOffset);
+			_soundHistory.push_back(sample);
+			*_soundWritePointer++ = sample;
+			source++;
 		}
+
+		_soundCursor = source;
+		_soundBitOffset = bitOffset;
+		return;
 	}
 
-	bool copySample(byte &sample) {
-		if (!_compressed) {
-			if (_position >= _end) {
-				_fault = true;
-				return false;
-			}
+	uint32 predictorIndex = _soundHistory.size() >= _soundBitAccumulator ? _soundHistory.size() - _soundBitAccumulator : 0;
+	uint16 mask = (uint16)((1U << _soundBitWidth) - 1);
+	uint16 sign = (uint16)(1U << (_soundBitWidth - 1));
+
+	if (source & 1) {
+		source--;
+		bitOffset = (uint16)(bitOffset + 8);
+	}
+
+	raw = (uint32)soundReadSourceByte(source) |
+		((uint32)soundReadSourceByte(source + 1) << 8) |
+		((uint32)soundReadSourceByte(source + 2) << 16) |
+		((uint32)soundReadSourceByte(source + 3) << 24);
+
+	raw >>= bitOffset;
+
+	while (size--) {
+		if (bitOffset & 0x10) {
+			raw <<= bitOffset;
+			source += 2;
+			raw = (raw & 0xFFFF0000) |
+				(uint16)(soundReadSourceByte(source + 2) |
+				((uint16)soundReadSourceByte(source + 3) << 8));
+
+			uint16 rotate = bitOffset & 31;
 
-			sample = sourceByte(_position++);
-			_history.push_back(sample);
-			return true;
+			if (rotate)
+				raw = (raw >> rotate) | (raw << (32 - rotate));
+
+			bitOffset = (uint16)(bitOffset - 0x10);
 		}
 
-		if (_needInit) {
-			_needInit = false;
-			_bitWidth = 4;
-			_predictorDistance = 1;
-			sample = (byte)readBits(8);
-			_blockOffset = 1;
+		uint16 delta = (uint16)raw & mask;
+		bitOffset = (uint16)(bitOffset + _soundBitWidth);
+		raw >>= _soundBitWidth;
+		byte sample;
+
+		if (!delta) {
+			sample = (byte)raw;
+			raw >>= 8;
+			bitOffset = (uint16)(bitOffset + 8);
 		} else {
-			if (_blockOffset == 0 || _blockOffset >= 0x20) {
-				if (readBits(1))
-					_bitWidth = (byte)readBits(3);
+			byte predictor = predictorIndex < _soundHistory.size() ? _soundHistory[predictorIndex] : 0x80;
+			sample = predictor + (byte)(delta - sign);
+		}
 
-				if (_bitWidth && readBits(1))
-					_predictorDistance = (byte)readBits(7);
+		_soundHistory.push_back(sample);
+		*_soundWritePointer++ = sample;
+		predictorIndex++;
+	}
 
-				_blockOffset = 0;
-			}
+	source += bitOffset >> 3;
+	_soundCursor = source;
+	_soundBitOffset = bitOffset & 7;
+}
 
-			if (!_bitWidth) {
-				sample = (byte)readBits(8);
-			} else {
-				uint16 delta = (uint16)readBits(_bitWidth);
-				if (!delta) {
-					sample = (byte)readBits(8);
-				} else {
-					byte predictor = _history.size() >= _predictorDistance ? _history[_history.size() - _predictorDistance] : 0x80;
-					sample = predictor + (byte)(delta - (1 << (_bitWidth - 1)));
-				}
+void ComfyEngine::soundCopyPcm(byte *destination, uint16 size) {
+	_soundWritePointer = destination;
+
+	if (_soundCompressed) {
+		if (_soundNeedInit) {
+			_soundNeedInit = false;
+			soundResetBitState();
+
+			if (size) {
+				*_soundWritePointer++ = (byte)soundBitRead(8);
+				_soundHistory.push_back(*(_soundWritePointer - 1));
+				--size;
 			}
+		} else if (_soundBlockOffset < 0x20 && size) {
+			uint16 copied = MIN<uint16>((uint16)(0x20 - _soundBlockOffset), size);
+			soundDecodeBits(copied, 0);
+			_soundBlockOffset = copied;
+			size = (uint16)(size - copied);
+		}
 
-			_blockOffset++;
+		while (size) {
+			uint16 copied = MIN<uint16>(0x20, size);
+			soundDecodeBits(copied, 1);
+			size = (uint16)(size - copied);
+			_soundBlockOffset = copied;
 		}
 
-		_history.push_back(sample);
-		return !_fault;
+		_soundWritePointer = nullptr;
+		return;
 	}
 
-	uint32 readBits(uint bits) {
-		uint32 value = 0;
-		for (uint bit = 0; bit < bits; bit++) {
-			if (_position >= _end) {
-				_fault = true;
-				return value;
-			}
+	while (size--) {
+		byte sample = soundReadSourceByte(_soundCursor++);
+		*_soundWritePointer++ = sample;
+	}
 
-			value |= (uint32)((sourceByte(_position) >> _bitOffset) & 1) << bit;
-			_bitOffset++;
-			if (_bitOffset == 8) {
-				_bitOffset = 0;
-				_position++;
-			}
-		}
+	_soundWritePointer = nullptr;
+}
 
-		return value;
+void ComfyEngine::soundAdvancePlayPosition() {
+	_soundPlayPosition += (uint16)(_soundCursor - _soundBlockBase);
+}
+
+void ComfyEngine::soundDecompressBlock(uint16 size) {
+	if (_soundPlayPosition >= _soundDataEnd) {
+		_soundFault = true;
+		return;
 	}
 
-	uint16 readParam() {
-		if (!_compressed)
-			return readWord();
+	_soundBlockBase = _soundPlayPosition;
+	_soundCursor = _soundPlayPosition;
+	_soundDecodeBlockSize = size;
 
-		switch (readBits(2)) {
-		case 0:
-			return 1;
-		case 1:
-			return 2;
-		case 2:
-			return (uint16)readBits(8);
-		case 3:
-			return (uint16)readBits(16);
-		default:
-			return 0;
+	if (!_soundUsesAnimData && !soundLoadSourceWindow(size)) {
+		_soundFault = true;
+		return;
+	}
+
+	if (_soundCompressed) {
+		if ((_soundRate & 1) == 0 && _soundRate > 0 && _soundInterleavePointer) {
+			memcpy(_soundInterleavePointer - 0x80, _soundInterleavePointer + (uint32)size * 2 - 0x80, 0x80);
 		}
+
+		_soundRate++;
 	}
 
-	uint16 readWord() {
-		if (_compressed)
-			return (uint16)readBits(16);
+}
 
-		if (_end - _position < 2) {
-			_fault = true;
-			return 0;
-		}
+void ComfyEngine::soundLoadDataBlock(uint16 size) {
+	if (_soundPlayPosition >= _soundDataEnd) {
+		_soundFault = true;
+		return;
+	}
 
-		uint16 value = (uint16)(sourceByte(_position) | ((uint16)sourceByte(_position + 1) << 8));
-		_position += 2;
-		return value;
+	if (_soundUsesAnimData) {
+		// The original reads this range through ANMFILE storage; We keep the
+		// current reconstructed sound range in _soundDecoderData instead...
+		_soundBlockBase = _soundPlayPosition;
+		_soundCursor = _soundPlayPosition;
+		_soundSourceWindowStart = 0;
+		_soundSourceWindowEnd = _soundDecoderData.size();
+		_soundDecodeBlockSize = size;
+		return;
 	}
 
-	byte readByte() {
-		if (_position >= _end) {
-			_fault = true;
-			return 0;
-		}
+	if (!_vocFile) {
+		_soundFault = true;
+		return;
+	}
 
-		return sourceByte(_position++);
-	}
-
-	void pushCue(uint16 value) {
-		// The original keeps at most 0x13 pending pitch entries, but consumes them
-		// while refilling wave buffers. Our decoder stores the full cue timeline,
-		// so applying that pending-entry limit here would drop later cues...
-		ComfyEngine::SoundCue cue;
-		cue.value = value;
-		cue.streamPosition = _streamPosition;
-		cue.counterThreshold = _sampleRate ? (_streamPosition * 100) / _sampleRate : 0;
-		_cues.push_back(cue);
-	}
-
-	Common::Array<byte> _data;
-	Common::Array<byte> _history;
-	Common::Array<ComfyEngine::SoundCue> _cues;
-	ComfyEngine *_engine = nullptr;
-	ComfyEngine::ObjFile *_objectFile = nullptr;
-	uint32 _sourceBase = 0;
-	uint32 _windowStart = 0;
-	uint32 _windowEnd = 0;
-	uint32 _decodeBlockSize = 0;
-	uint32 _end = 0;
-	uint32 _position = 0;
-	uint32 _streamPosition = 0;
-	uint32 _eventArgument = 0;
-	uint32 _eventRemaining = 0;
-	uint32 _fillRemaining = 0;
-	uint32 _loopPosition = 0;
-	uint32 _sampleRate = 11025;
-	int16 _loopCount = 0;
-	byte _sample = 0xA5;
-	byte _bitOffset = 0;
-	byte _loopBitOffset = 0;
-	byte _bitWidth = 4;
-	byte _predictorDistance = 1;
-	byte _blockOffset = 0;
-	bool _compressed = false;
-	bool _needInit = false;
-	bool _started = false;
-	bool _finished = false;
-	bool _fault = false;
-	BufferState _bufferStates[2];
-};
+	uint32 sourcePosition = _soundDataBase + _soundPlayPosition;
+	uint16 alignment = (sourcePosition & 1) ? 1 : 0;
+	if (sourcePosition < alignment)
+		alignment = 0;
 
-void ComfyEngine::setWaveBalancePercent(uint16 value) {
-	if ((int16)value < 0)
-		value = 0;
-	else if (value > 100)
-		value = 100;
+	sourcePosition -= alignment;
 
-	_v3SceneWaveBalancePercent = (byte)value;
-	_v3WaveBalancePercent = value;
-}
+	uint32 available = _soundDataEnd - _soundPlayPosition + alignment;
+	uint32 readSize = MIN<uint32>((uint32)size + 0xC8, available);
 
-void ComfyEngine::setWaveLeftPercent(uint16 value) {
-	if (value == 0x00FF)
+	if (sourcePosition > _vocFile->fileSize) {
+		readSize = 0;
+	} else if (readSize > _vocFile->fileSize - sourcePosition) {
+		readSize = _vocFile->fileSize - sourcePosition;
+	}
+
+	if (!readSize) {
+		_soundFault = true;
 		return;
+	}
 
-	if ((int16)value < 0)
-		value = 0;
-	else if (value > 100)
-		value = 100;
+	byte *source = objFileReadTiledCore(sourcePosition, readSize, _vocFile);
+	if (!source) {
+		_soundFault = true;
+		return;
+	}
 
-	_v3SceneWaveLeftPercent = (byte)value;
-	_v3WaveLeftPercent = value;
+	uint32 logicalSize = readSize - alignment;
+	_soundDecoderData.resize(logicalSize);
+	memcpy(&_soundDecoderData[0], source + alignment, logicalSize);
+	_soundSourceWindowStart = _soundPlayPosition;
+	_soundSourceWindowEnd = _soundPlayPosition + logicalSize;
+	_soundBlockBase = _soundPlayPosition;
+	_soundCursor = _soundPlayPosition;
+	_soundDecodeBlockSize = size;
 }
 
-void ComfyEngine::setWaveRightPercent(uint16 value) {
-	if (value == 0x00FF)
+void ComfyEngine::soundLoadChunk() {
+	if (_soundUsesAnimData || !_soundDataEnd || !_vocFile)
 		return;
 
-	if ((int16)value < 0)
-		value = 0;
-	else if (value > 100)
-		value = 100;
+	uint32 preloadOffset = _engineVersion == 3 ? 0x4000 : 0x5000;
+	uint32 endMargin = _engineVersion == 3 ? 2 : 1;
+	uint32 position = _soundPlayPosition + preloadOffset;
+	uint32 lastPosition = _soundDataEnd > endMargin ? _soundDataEnd - endMargin : 0;
 
-	_v3SceneWaveRightPercent = (byte)value;
-	_v3WaveRightPercent = value;
+	if (position >= lastPosition)
+		position = lastPosition;
+
+	uint32 fileOffset = _soundDataBase + position;
+	if (fileOffset > _vocFile->fileSize || 2 > _vocFile->fileSize - fileOffset)
+		return;
+
+	byte probe[2];
+	objFileReadFieldCore(probe, fileOffset, sizeof(probe), _vocFile);
 }
 
-void ComfyEngine::setMixerVolumePercent(uint16 value) {
-	if (value == 0x00FF)
+void ComfyEngine::soundPreloadChunk() {
+	if (!_isPanther || _soundUsesAnimData || !_soundDataEnd || !_vocFile)
 		return;
 
-	if ((int16)value < 0)
-		value = 0;
-	else if (value > 100)
-		value = 100;
+	uint32 position = _soundPlayPosition + 0x4000;
+	if (position >= _soundDataEnd)
+		position = _soundDataEnd > 2 ? _soundDataEnd - 2 : 0;
 
-	_v3SceneMixerVolumePercent = (byte)value;
-	_v3MixerVolumePercent = value;
+	uint32 fileOffset = _soundDataBase + position;
+	if (fileOffset > _vocFile->fileSize || 2 > _vocFile->fileSize - fileOffset)
+		return;
+
+	byte preload[2];
+	objFileReadFieldCore(preload, fileOffset, sizeof(preload), _vocFile);
 }
 
-void ComfyEngine::setMediaRangePercent(uint16 value) {
-	if ((int16)value < 0)
-		value = 0;
-	else if (value > 100)
-		value = 100;
+void ComfyEngine::soundInitRuntimeState(byte *state) {
+	_soundPackedState = state;
+	soundSetBufferStatePointer(state ? state + 0x41 : nullptr);
+}
 
-	_v3MixerAltPercent = value;
+void ComfyEngine::soundSetBufferStatePointer(byte *state) {
+	_soundBufferState = state;
 }
 
-void ComfyEngine::setMediaMode(byte mode) {
-	if (mode == 1 || mode == 3) {
-		_v3SceneMediaModeEnabled = 1;
+void ComfyEngine::soundSaveStreamPositions(uint16 bufferIndex) {
+	bufferIndex &= 1;
+	_soundBufferPosition[bufferIndex] = _soundPlayPosition;
+	_soundBufferLoopPosition[bufferIndex] = _soundLoopPosition;
+}
 
-		if (!_v3MediaValueAvailable) {
-			_v3MediaValue = 0;
-			_v3MediaValueAvailable = true;
-		}
-	} else if (mode == 2) {
-		_v3SceneMediaModeEnabled = 0;
-		_v3MediaValue = 0;
-		_v3MediaValueAvailable = false;
+void ComfyEngine::soundRestoreBufferState() {
+	if (!_soundBufferState)
+		return;
+
+	_soundPlayPosition = READ_LE_UINT32(_soundBufferState);
+	_soundLoopPosition = READ_LE_UINT32(_soundBufferState + 4);
+	_soundDataEnd = READ_LE_UINT32(_soundBufferState + 8);
+	_soundDataBase = READ_LE_UINT32(_soundBufferState + 0x0C);
+	_soundSourceBase = _soundDataBase;
+	_soundUsesAnimData = _soundBufferState[0x10] != 0;
+
+	if (_soundUsesAnimData) {
+		animFileRestoreSoundStorage(_soundPlayPosition);
+		_soundSourceWindowStart = 0;
+		_soundSourceWindowEnd = _soundDecoderData.size();
+	} else {
+		_soundSourceWindowStart = 0;
+		_soundSourceWindowEnd = 0;
 	}
 }
 
-void ComfyEngine::restoreWaveStateAfterSceneStart() {
-	setWaveBalancePercent(_v3SceneWaveBalancePercent);
-	setWaveLeftPercent(_v3SceneWaveLeftPercent);
-	setWaveRightPercent(_v3SceneWaveRightPercent);
-	setMixerVolumePercent(_v3SceneMixerVolumePercent);
+void ComfyEngine::soundSaveActiveBufferState(uint16 bufferIndex) {
+	if (!_soundBufferState)
+		return;
+
+	_soundBufferStateIndex = bufferIndex & 1;
+	WRITE_LE_UINT32(_soundBufferState, _soundBufferPosition[_soundBufferStateIndex]);
+	WRITE_LE_UINT32(_soundBufferState + 4, _soundBufferLoopPosition[_soundBufferStateIndex]);
+	WRITE_LE_UINT32(_soundBufferState + 8, _soundDataEnd);
+	WRITE_LE_UINT32(_soundBufferState + 0x0C, _soundDataBase);
+	_soundBufferState[0x10] = _soundUsesAnimData;
+}
+
+void ComfyEngine::soundSaveBufferState(uint16 bufferIndex) {
+	_soundBufferStateIndex = bufferIndex & 1;
+	_soundBufferStreamPosition[bufferIndex] = _soundStreamPosition;
+	_soundBufferPosition[bufferIndex] = _soundPlayPosition;
+	_soundBufferLoopPosition[bufferIndex] = _soundLoopPosition;
+	_soundBufferEventRemaining[bufferIndex] = (uint32)_soundEventLength;
+	_soundBufferFillRemaining[bufferIndex] = _soundFillCount;
+	_soundBufferLoopCount[bufferIndex] = _soundLoopCount;
+	_soundBufferStarted[bufferIndex] = _soundStarted;
+
+	soundSaveStreamPositions(bufferIndex);
+}
+
+void ComfyEngine::soundPackCueEntries(byte *state, uint32 playbackPosition) {
+	uint16 packedCueCount = 0;
+
+	while (packedCueCount < _soundCues.size() && _soundCues[packedCueCount].streamPosition < playbackPosition) {
+		SoundCue &cue = _soundCues[packedCueCount];
+		WRITE_LE_UINT16(state + 0x15 + packedCueCount * 2, cue.value);
+		WRITE_LE_UINT32(state + 0x1D + packedCueCount * 4, cue.streamPosition);
+		WRITE_LE_UINT32(state + 0x2D + packedCueCount * 4, cue.counterThreshold);
+		packedCueCount++;
+	}
+
+	WRITE_LE_UINT16(state + 0x3D, packedCueCount);
+}
+
+void ComfyEngine::soundPushCue(uint16 value, int32 streamPosition) {
+	if (_engineVersion == 3) {
+		if (_soundCues.size() == COMFY_V3_SOUND_MAX_CUES) {
+			_soundCues.remove_at(_soundCues.size() - 1);
+		}
 
-	if (_v3SceneMediaModeEnabled) {
-		setMediaMode(2);
-		setMediaMode(1);
-	} else {
-		setMediaMode(2);
+		if (!_soundCues.empty() && _soundCues[_soundCues.size() - 1].value == value) {
+			return;
+		}
+	} else if (_soundCues.size() >= COMFY_SOUND_MAX_CUES) {
+		return;
 	}
+
+	_soundSampleRate = soundCalcSampleRate(_soundSample);
+	SoundCue cue;
+	cue.value = value;
+	cue.streamPosition = streamPosition;
+	cue.counterThreshold = _soundSampleRate ? (streamPosition * 100) / (int32)_soundSampleRate : 0;
+	_soundCues.push_back(cue);
 }
 
-bool ComfyEngine::soundOpenVocFile() {
-	objFileClose(_vocFile);
-	uint32 maximumBytes = 0x40000;
-	if (sysGetExtMemKB() < 4000)
-		maximumBytes /= 2;
+void ComfyEngine::soundFillPcmBuffer(uint16 bufferIndex, uint16 size) {
+	if (bufferIndex >= 2 || _soundStopped)
+		return;
 
-	_vocFile = objFileOpen(Common::Path("VOCFILE.DAT"), 0x8000, maximumBytes);
-	if (!_vocFile)
-		return false;
+	uint32 blockSize = _isPanther ? COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES :
+		(_engineVersion == 3 ? COMFY_V3_SOUND_PCM_BLOCK_BYTES : COMFY_SOUND_PCM_BLOCK_BYTES);
 
-	byte header[4];
-	memset(header, 0, sizeof(header));
-	objFileReadFieldCore(header, 0, sizeof(header), _vocFile);
+	uint16 fillSize = (_isPanther || _engineVersion == 3) ? size : (uint16)COMFY_SOUND_PCM_BLOCK_BYTES;
 
-	if (header[0] != 'C' || (header[1] != 'V' && header[1] != 'W')) {
-		objFileClose(_vocFile);
-		return false;
+	if (_soundPcmBlocks[bufferIndex].size() != blockSize)
+		_soundPcmBlocks[bufferIndex].resize(blockSize);
+
+	if (_isPanther || _engineVersion == 3)
+		soundSaveBufferState(bufferIndex);
+
+	byte *destination = &_soundPcmBlocks[bufferIndex][0];
+	uint16 destinationPosition = 0;
+	uint16 remaining = fillSize;
+
+	if (!_soundStarted) {
+		if (_isPanther || _engineVersion == 3) {
+			soundLoadDataBlock(size);
+		} else {
+			soundDecompressBlock((uint16)blockSize);
+		}
 	}
 
-	_soundCompressed = header[1] == 'W';
-	_soundUsesAnimData = false;
-	_soundEntryCount = READ_LE_UINT16(header + 2);
-	return true;
-}
+	while (remaining && !_soundFault) {
+		uint16 copied = 0;
+		if (_soundStarted) {
+			_soundFillCount = fillSize;
+		}
 
-bool ComfyEngine::soundInit() {
-	if (!soundOpenVocFile())
-		return false;
+		if (_soundFillCount) {
+			copied = MIN<uint16>(_soundFillCount, remaining);
+			_soundFillCount = (uint16)(_soundFillCount - copied);
+			memset(destination + destinationPosition, 0x80, copied);
 
-	_soundEventIndex = 0;
-	_soundEventMaximum = 0;
-	_soundEventSubIndex = 0xFFFF;
-	_soundEventPreviousSubIndex = 0xFFFF;
-	_soundTimingPaused = false;
-	_soundVocBlockCount = 0;
-	_soundVocCounterSnapshot = 0;
-	_soundVocTimingDelta = 0;
+			if (_soundCompressed) {
+				for (uint16 i = 0; i < copied; i++)
+				_soundHistory.push_back(0x80);
+			}
+		} else if (_soundEventLength) {
+			if ((int32)remaining <= _soundEventLength) {
+				copied = remaining;
+			} else {
+				copied = (uint16)_soundEventLength;
+			}
 
-	for (uint i = 0; i < COMFY_VOC_QUEUE_CAPACITY; i++) {
-		_vocQueue[i] = VocQueueEntry();
-		_vocQueueV3[i] = VocQueueEntryV3();
-	}
+			_soundEventLength -= copied;
+			soundCopyPcm(destination + destinationPosition, copied);
+		}
 
-	_v3SceneWaveBalancePercent = 0;
-	_v3SceneMediaModeEnabled = 0;
-	_v3SceneWaveLeftPercent = 0;
-	_v3SceneWaveRightPercent = 0;
-	_v3SceneMixerVolumePercent = 0;
-	return true;
-}
+		if (copied) {
+			destinationPosition = (uint16)(destinationPosition + copied);
+			remaining = (uint16)(remaining - copied);
+			_soundStreamPosition += copied;
+			continue;
+		}
 
-void ComfyEngine::soundShutdown() {
-	_mixer->stopHandle(_soundHandle);
-	_soundQueueStream = nullptr;
-	delete _soundDecoderState;
-	_soundDecoderState = nullptr;
-	_soundCues.clear();
-	objFileClose(_vocFile);
-	_soundEntryCount = 0;
-	_soundNextCue = 0;
-	_soundPaused = false;
-	_soundUsesAnimData = false;
-	_soundTimingPaused = false;
-	_soundVocBlockCount = 0;
-	_soundVocCounterSnapshot = 0;
-	_soundVocTimingDelta = 0;
+		uint16 command = soundParseCommand();
+
+		switch (command) {
+		case SOUND_CMD_BEGIN_EVENT:
+			soundBeginEvent(false);
+			break;
+		case SOUND_CMD_BEGIN_LOOP_EVENT:
+			soundBeginEvent(true);
+			break;
+		case SOUND_CMD_PITCH_CHANGE: {
+			uint16 value = 0;
+			soundReadParam(value);
+			soundPushCue(value, (int32)_soundStreamPosition);
+			break;
+		}
+		case SOUND_CMD_FILL_OR_SAMPLE_DELAY: {
+			uint16 fillCount = 0;
+			byte nextSample = 0;
+			soundReadLoopEntry(fillCount, nextSample);
+			_soundFillCount = fillCount;
+
+			if (_engineVersion == 3 && !_soundSample)
+				_soundSample = nextSample;
+
+			if (nextSample != _soundSample) {
+				uint32 oldRate = soundCalcSampleRate(_soundSample);
+				uint32 newRate = 1000000 / (0x100 - nextSample);
+				if (newRate)
+					_soundFillCount = (uint16)(((uint32)_soundFillCount * oldRate) / newRate);
+			}
 
-	if (_midiPlyrDriver)
-		_midiPlyrDriver->setIncreaseVocCounter(0);
-}
+			break;
+		}
+		case SOUND_CMD_LOOP_START: {
+			uint16 loopCount = 0;
+			soundReadFreqWord(loopCount);
+			_soundLoopCount = (int16)loopCount;
+			soundSaveLoopPosition();
+			break;
+		}
+		case SOUND_CMD_LOOP_END:
+			if (_soundLoopCount > 0) {
+				_soundLoopCount--;
+				soundSeekToLoop((uint16)blockSize);
+				soundSeekToLoop((uint16)blockSize);
+			}
 
-void ComfyEngine::soundHeaderReadFromXms(byte *destination, uint16 index, uint16 size) {
-	objHdrReadFromXms(destination, _headerXmsSoundHeadersBase, size, index);
+			break;
+		case SOUND_CMD_SET_SAMPLE:
+			_soundSample = soundReadSampleByte();
+			break;
+		case SOUND_CMD_START:
+			soundPushCue(0, (int32)_soundStreamPosition);
+			_soundStarted = true;
+			break;
+		default:
+			break;
+		}
+	}
+
+	_soundEventRemaining = (uint32)_soundEventLength;
+	soundAdvancePlayPosition();
 }
 
 void ComfyEngine::soundUpdateVocTiming() {
-	if (_soundTimingPaused || !_midiPlyrDriver)
+	if (_soundTimingPaused || (_engineVersion == 3 && !_soundCounterEnabled) || !_midiPlyrDriver)
 		return;
 
 	uint32 timeFrac = 0;
@@ -818,8 +1263,18 @@ void ComfyEngine::soundUpdateVocTiming() {
 	timeFrac -= _soundVocCounterSnapshot;
 	_midiPlyrDriver->vocSrResetBlockNo();
 	uint32 sampleRate = _soundSampleRate ? _soundSampleRate : 11025;
+
+	if (_isPanther || _engineVersion == 3)
+		sampleRate = soundCalcSampleRate(_soundSample);
+
 	uint32 expected = ((uint32)_soundVocBlockCount * 0x186A00) / sampleRate;
-	_soundVocTimingDelta = (int16)((uint16)expected - (uint16)timeFrac);
+	int16 timingDelta = (int16)((uint16)expected - (uint16)timeFrac);
+
+	if (_isPanther) {
+		_soundVocTimingDelta = timingDelta;
+	} else {
+		_midiCounterAdjustment = timingDelta;
+	}
 }
 
 void ComfyEngine::soundServiceWaveBuffers() {
@@ -827,196 +1282,240 @@ void ComfyEngine::soundServiceWaveBuffers() {
 		return;
 
 	uint32 queuedBlocks = _soundQueueStream->numQueuedStreams();
+	if (queuedBlocks >= 2)
+		return;
+
+	if (_soundStopped)
+		return;
+
 	if (_midiPlyrDriver) {
-		for (uint32 i = queuedBlocks; i < 2; i++)
-			_midiPlyrDriver->vocSrUpdateCounters();
+		_midiPlyrDriver->vocSrUpdateCounters();
 	}
 
-	while (_soundQueueStream->numQueuedStreams() < 2) {
-		if (!soundQueuePcmBlock(_soundWaveBufferIndex))
+	if (_isPanther || _engineVersion == 3) {
+		soundFillPcmBuffer(_soundWaveBufferIndex, (uint16)(_isPanther ? COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES : COMFY_V3_SOUND_PCM_BLOCK_BYTES));
+		if (_soundFault)
 			return;
+	}
+
+	if (!waveOutSubmitBuffer(_soundWaveBufferIndex))
+		return;
 
-		_soundWaveBufferIndex = 1 - _soundWaveBufferIndex;
+	_soundWaveBufferIndex = 1 - _soundWaveBufferIndex;
+
+	if (_isPanther) {
+		soundPreloadChunk();
+	} else if (_engineVersion == 3) {
+		soundLoadChunk();
 	}
 }
 
 bool ComfyEngine::soundLoadEntry(uint16 index) {
 	byte header[8];
+	byte scratch[2];
 	memset(header, 0, sizeof(header));
-	soundHeaderReadFromXms(header, index, sizeof(header));
-	uint32 size = READ_LE_UINT32(header);
-	uint32 offset = READ_LE_UINT32(header + 4);
-	return _vocFile && offset <= _vocFile->fileSize && size <= _vocFile->fileSize - offset;
-}
+	memset(scratch, 0, sizeof(scratch));
 
-bool ComfyEngine::soundPrepareDecoderState(uint16 index) {
-	Common::Array<byte> animationSoundData;
-	byte *data = nullptr;
-	ObjFile *objectFile = nullptr;
-	uint32 fileSize = 0;
-	uint32 dataSize = 0;
-	uint32 dataOffset = 0;
-	bool compressed = _soundCompressed;
+	soundReadHeader(header, index, sizeof(header));
 
-	if (index == 0xFFFF) {
-		uint32 storedSize = READ_LE_UINT32(_animFrameHeader + 4);
-		if (!storedSize)
-			return false;
+	uint32 size = READ_LE_UINT32(header);
+	uint32 offset = READ_LE_UINT32(header + 4);
 
-		animationSoundData.resize(storedSize);
-		if (storedSize <= _animFrameStorage.size()) {
-			memcpy(&animationSoundData[0], &_animFrameStorage[0], storedSize);
-		} else {
-			// The original streams embedded ANM sound through the file object while VC
-			// chunks arrive; our decoder owns its source buffer, so we rebuild only
-			// the embedded sound stream without changing the animation command cursor...
-			if (_animCurrentIndex >= _animIndexTable.size())
-				return false;
-
-			uint32 copied = 0;
-			uint32 position = _animIndexTable[_animCurrentIndex] + COMFY_ANMFILE_HEADER_BYTES;
-			while (copied < storedSize) {
-				uint32 headerSize = _animPantherFormat ? 8 : 4;
-
-				if (position > _animFileData.size() || headerSize > _animFileData.size() - position)
-					return false;
-
-				byte *header = &_animFileData[position];
-				uint16 command = READ_LE_UINT16(header);
-				uint32 rawCommandSize = _animPantherFormat ? READ_LE_UINT32(header + 2) : READ_LE_UINT16(header + 2);
-				int32 signedCommandSize = _animPantherFormat ? (int32)rawCommandSize : (int32)(uint16)rawCommandSize;
-				uint32 commandSize = rawCommandSize;
-
-				if (_animPantherFormat && command == COMFY_ANM_COMMAND_FRAME && signedCommandSize <= (int32)headerSize) {
-					position += headerSize;
-					continue;
-				}
-
-				if (commandSize < headerSize || commandSize > _animFileData.size() - position)
-					return false;
-
-				uint32 payloadSize = commandSize - headerSize;
-				if (command == COMFY_ANM_COMMAND_STORE_FRAME_BYTES) {
-					uint32 copySize = MIN<uint32>(payloadSize, storedSize - copied);
-					if (copySize)
-						memcpy(&animationSoundData[copied], header + headerSize, copySize);
-
-					copied += copySize;
-				} else if (command == COMFY_ANM_COMMAND_END) {
-					break;
-				}
-
-				position += commandSize;
-			}
+	if (!_vocFile || offset > _vocFile->fileSize || size > _vocFile->fileSize - offset)
+		return false;
 
-			if (copied < storedSize)
-				return false;
-		}
+	objFileReadFieldCore(scratch, offset, sizeof(scratch), _vocFile);
 
-		data = &animationSoundData[0];
-		fileSize = animationSoundData.size();
-		dataSize = fileSize;
-		compressed = false;
-		_soundUsesAnimData = true;
-	} else {
-		byte header[8];
-		memset(header, 0, sizeof(header));
-		soundHeaderReadFromXms(header, index, sizeof(header));
-		dataSize = READ_LE_UINT32(header);
-		dataOffset = READ_LE_UINT32(header + 4);
+	return true;
+}
 
-		if (!_vocFile || dataOffset > _vocFile->fileSize || dataSize > _vocFile->fileSize - dataOffset)
-			return false;
+void ComfyEngine::soundPlayFromPtr(const byte *source) {
+	if (!source || !_vocFile)
+		return;
 
-		objectFile = _vocFile;
-		fileSize = _vocFile->fileSize;
-		_soundUsesAnimData = false;
-	}
+	uint16 tileId = READ_LE_UINT16(source);
+	tileLoadAndCache(_vocFile, source + 2, tileId);
+}
 
-	if (dataOffset > fileSize || dataSize > fileSize - dataOffset)
+bool ComfyEngine::waveOutSubmitBuffer(uint16 bufferIndex) {
+	if (!_soundQueueStream)
 		return false;
 
-	delete _soundDecoderState;
+	if (bufferIndex >= 2)
+		return false;
 
-	if (objectFile) {
-		_soundDecoderState = new SoundDecoderState(this, objectFile, dataOffset, dataSize, compressed);
-	} else {
-		_soundDecoderState = new SoundDecoderState(data + dataOffset, dataSize, compressed);
+	if (!_isPanther && _engineVersion != 3) {
+		soundFillPcmBuffer(bufferIndex, COMFY_SOUND_PCM_BLOCK_BYTES);
+		if (_soundFault)
+			return false;
 	}
 
-	if (_soundDecoderState->fault()) {
-		delete _soundDecoderState;
-		_soundDecoderState = nullptr;
-		return false;
-	}
+	uint32 blockSize = _isPanther ? COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES :
+		(_engineVersion == 3 ? COMFY_V3_SOUND_PCM_BLOCK_BYTES : COMFY_SOUND_PCM_BLOCK_BYTES);
+
+	_soundQueueStream->queueBuffer(&_soundPcmBlocks[bufferIndex][0], blockSize, DisposeAfterUse::NO, Audio::FLAG_UNSIGNED);
 
-	_soundSampleRate = _soundDecoderState->getRate();
-	_soundCues.clear();
-	_soundNextCue = 0;
 	return true;
 }
 
-bool ComfyEngine::soundDecodePcmBlock(uint16 bufferIndex, byte *&buffer, uint32 &decodedSize) {
-	buffer = nullptr;
-	decodedSize = 0;
-
-	if (!_soundDecoderState)
-		return false;
-
-	_soundDecoderState->saveBufferState(bufferIndex);
-	uint32 blockSize = _isPanther ? COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES : COMFY_SOUND_PCM_BLOCK_BYTES;
-	buffer = (byte *)malloc(blockSize);
-	if (!buffer)
-		return false;
-
-	decodedSize = _soundDecoderState->decode(buffer, blockSize);
-	_soundDecoderState->copyCues(_soundCues);
+void ComfyEngine::soundSetSampleRate(uint32 sampleRate) {
+	if (sampleRate == _soundSampleRate)
+		return;
 
-	if (!decodedSize) {
-		free(buffer);
-		buffer = nullptr;
-		return false;
+	if (sampleRate > 9000 && sampleRate < 12000) {
+		sampleRate = 11025;
+	} else if (sampleRate > 20000 && sampleRate < 23000) {
+		sampleRate = 22050;
 	}
 
-	return true;
+	_soundSampleRate = sampleRate;
 }
 
-bool ComfyEngine::soundQueuePcmBlock(uint16 bufferIndex) {
+bool ComfyEngine::waveOutStartPlayback() {
+	soundSetSampleRate(soundCalcSampleRate(_soundSample));
+	_soundQueueStream = Audio::makeQueuingAudioStream(_soundSampleRate, false);
 	if (!_soundQueueStream)
 		return false;
 
-	byte *buffer = nullptr;
-	uint32 decodedSize = 0;
-	if (!soundDecodePcmBlock(bufferIndex, buffer, decodedSize))
-		return false;
+	uint32 blockSize = _isPanther ? COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES :
+		(_engineVersion == 3 ? COMFY_V3_SOUND_PCM_BLOCK_BYTES : COMFY_SOUND_PCM_BLOCK_BYTES);
+
+	_soundQueueStream->queueBuffer(&_soundPcmBlocks[0][0], blockSize, DisposeAfterUse::NO, Audio::FLAG_UNSIGNED);
+	_soundQueueStream->queueBuffer(&_soundPcmBlocks[1][0], blockSize, DisposeAfterUse::NO, Audio::FLAG_UNSIGNED);
 
-	_soundQueueStream->queueBuffer(buffer, decodedSize, DisposeAfterUse::YES, Audio::FLAG_UNSIGNED);
+	_mixer->playStream(Audio::Mixer::kPlainSoundType, &_soundHandle, _soundQueueStream, -1, Audio::Mixer::kMaxChannelVolume, 0, DisposeAfterUse::YES);
 	return true;
 }
 
-void ComfyEngine::soundPackState(byte *state) {
-	bool stopped = !_soundDecoderState || !_mixer->isSoundHandleActive(_soundHandle);
-	if (stopped) {
-		memset(state, 0, 0x52);
-		state[0x3F] = 1;
+void ComfyEngine::soundPackState() {
+	if (!_soundPackedState)
+		return;
+
+	if (_engineVersion == 3 && _musicEnabled)
+		return;
+
+	if (_soundStopped) {
+		_soundPackedState[0x3F] = 1;
 		return;
 	}
 
+	_soundSampleRate = soundCalcSampleRate(_soundSample);
 	uint32 vocCounter = _midiPlyrDriver ? _midiPlyrDriver->getVocCounter() : (uint32)((_mixer->getSoundElapsedTime(_soundHandle) + 9) / 10);
 	uint32 playbackPosition = (vocCounter * _soundSampleRate) / 100;
 	uint16 bufferIndex = _soundWaveBufferIndex;
-	if ((int32)(_soundDecoderState->getBufferStreamPosition(bufferIndex) - COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES) < (int32)playbackPosition)
+	uint32 blockSize = _isPanther ? COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES : (_engineVersion == 3 ? COMFY_V3_SOUND_PCM_BLOCK_BYTES : COMFY_SOUND_PCM_BLOCK_BYTES);
+	if ((int32)(_soundStreamPosition - blockSize) < (int32)playbackPosition)
 		bufferIndex = 1 - bufferIndex;
 
-	_soundDecoderState->packState(state, bufferIndex, playbackPosition, vocCounter,
-		stopped, _soundUsesAnimData, _soundCues, _soundNextCue);
+	soundSaveActiveBufferState(bufferIndex);
+
+	_soundPackedState[0x3F] = 0;
+	WRITE_LE_UINT32(_soundPackedState, _soundBufferStreamPosition[bufferIndex]);
+	_soundPackedState[4] = _soundBufferStarted[bufferIndex];
+	WRITE_LE_UINT16(_soundPackedState + 5, _soundBufferFillRemaining[bufferIndex]);
+	WRITE_LE_UINT32(_soundPackedState + 7, _soundBufferEventRemaining[bufferIndex]);
+	WRITE_LE_UINT16(_soundPackedState + 0x0B, (uint16)_soundBufferLoopCount[bufferIndex]);
+	WRITE_LE_UINT32(_soundPackedState + 0x0D, playbackPosition);
+	WRITE_LE_UINT32(_soundPackedState + 0x11, vocCounter);
+
+	soundPackCueEntries(_soundPackedState, playbackPosition);
+	_soundPackedState[0x40] = _soundSample;
 }
 
-void ComfyEngine::soundUnpackState(byte *state) {
-	_mixer->stopHandle(_soundHandle);
-	_soundQueueStream = nullptr;
+uint16 ComfyEngine::soundGetStateSize() {
+	return _isPanther ? COMFY_PANTHER_SOUND_STATE_BYTES : 0x52;
+}
+
+void ComfyEngine::soundUnpackState() {
+	if (!_soundPackedState)
+		return;
+
+	if (_engineVersion == 3) {
+		if (_musicEnabled)
+			return;
+
+		soundPrepareQueuePlayback();
+
+		if (_soundPackedState[0x3F]) {
+			_soundStopped = true;
+			_soundCues.clear();
+			return;
+		}
+
+		_soundStopped = false;
+		_soundFault = false;
+		soundRestoreBufferState();
+
+		if (_soundFault)
+			return;
+
+		_soundStreamPosition = READ_LE_UINT32(_soundPackedState);
+		_soundStarted = _soundPackedState[4] != 0;
+		_soundFillCount = READ_LE_UINT16(_soundPackedState + 5);
+		_soundEventRemaining = READ_LE_UINT32(_soundPackedState + 7);
+		_soundEventLength = (int32)_soundEventRemaining;
+		_soundLoopCount = (int16)READ_LE_UINT16(_soundPackedState + 0x0B);
+		uint32 playbackPosition = READ_LE_UINT32(_soundPackedState + 0x0D);
+		uint32 vocCounter = READ_LE_UINT32(_soundPackedState + 0x11);
+		_soundSample = _soundPackedState[0x40];
+		_soundCursor = _soundPlayPosition;
+		_soundBitOffset = 0;
+		_soundLoopBitOffset = 0;
+		_soundBlockOffset = 0;
+		_soundFinished = false;
+		_soundHistory.clear();
+		_soundCues.clear();
+
+		uint16 advance = (uint16)(playbackPosition - _soundStreamPosition);
+		if (advance >= COMFY_V3_SOUND_PCM_BLOCK_BYTES)
+			advance = COMFY_V3_SOUND_PCM_BLOCK_BYTES;
+
+		soundFillPcmBuffer(0, advance);
+		if (_soundFault)
+			return;
+
+		uint16 cueCount = MIN<uint16>(READ_LE_UINT16(_soundPackedState + 0x3D), COMFY_V3_SOUND_MAX_CUES);
+		for (uint16 i = 0; i < cueCount; i++) {
+			SoundCue cue;
+			cue.value = READ_LE_UINT16(_soundPackedState + 0x15 + i * 2);
+			cue.streamPosition = READ_LE_UINT32(_soundPackedState + 0x1D + i * 4);
+			cue.counterThreshold = READ_LE_UINT32(_soundPackedState + 0x2D + i * 4);
+			_soundCues.push_back(cue);
+		}
+
+		_soundEventSubIndex = 0xFFFF;
+
+		soundFillPcmBuffer(0, COMFY_V3_SOUND_PCM_BLOCK_BYTES);
+		if (_soundFault)
+			return;
+
+		soundFillPcmBuffer(1, COMFY_V3_SOUND_PCM_BLOCK_BYTES);
+		if (_soundFault)
+			return;
+
+		if (!waveOutStartPlayback())
+			return;
+
+		_soundWaveBufferIndex = 0;
+		_soundVocCounterSnapshot = vocCounter;
+		_soundVocBlockCount = 0;
+
+		if (_midiPlyrDriver) {
+			_midiPlyrDriver->setVocCounter(vocCounter);
+			_midiPlyrDriver->setIncreaseVocCounter(1);
+			_midiPlyrDriver->vocSrResetCounters();
+		}
+
+		_soundCounterEnabled = true;
+		return;
+	}
+
+	soundStopPlayback();
+
+	if (_soundPackedState[0x3F]) {
+		_soundStopped = true;
+		_soundCues.clear();
 
-	if (state[0x3F] || !_soundDecoderState) {
 		if (_midiPlyrDriver) {
 			_midiPlyrDriver->setIncreaseVocCounter(0);
 			_midiPlyrDriver->vocSrResetBlockNo();
@@ -1025,151 +1524,236 @@ void ComfyEngine::soundUnpackState(byte *state) {
 		return;
 	}
 
-	uint32 vocCounter = 0;
-	if (!_soundDecoderState->unpackState(state, _soundCues, vocCounter)) {
+	_soundStopped = false;
+	_soundDecodeBlockSize = _isPanther ? COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES : (_engineVersion == 3 ? COMFY_V3_SOUND_PCM_BLOCK_BYTES : COMFY_SOUND_PCM_BLOCK_BYTES);
+	_soundFault = false;
+
+	soundRestoreBufferState();
+
+	if (_soundFault) {
+		_soundEventSubIndex = 0;
+		return;
+	}
+
+	_soundStreamPosition = READ_LE_UINT32(_soundPackedState);
+	_soundStarted = _soundPackedState[4] != 0;
+	_soundFillCount = READ_LE_UINT16(_soundPackedState + 5);
+	_soundEventRemaining = READ_LE_UINT32(_soundPackedState + 7);
+	_soundEventLength = (int32)_soundEventRemaining;
+	_soundLoopCount = (int16)READ_LE_UINT16(_soundPackedState + 0x0B);
+	uint32 playbackPosition = READ_LE_UINT32(_soundPackedState + 0x0D);
+	uint32 vocCounter = READ_LE_UINT32(_soundPackedState + 0x11);
+	_soundSample = _soundPackedState[0x40];
+	_soundCursor = _soundPlayPosition;
+	_soundBitOffset = 0;
+	_soundLoopBitOffset = 0;
+	_soundBlockOffset = 0;
+	_soundFinished = false;
+	_soundHistory.clear();
+	_soundCues.clear();
+
+	if (_isPanther || _engineVersion == 3) {
+		uint16 advance = (uint16)(playbackPosition - _soundStreamPosition);
+		uint16 blockSize = (uint16)(_isPanther ? COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES : COMFY_V3_SOUND_PCM_BLOCK_BYTES);
+
+		if (advance >= blockSize)
+			advance = blockSize;
+
+		soundFillPcmBuffer(0, advance);
+	} else {
+		soundFillPcmBuffer(0, COMFY_SOUND_PCM_BLOCK_BYTES);
+	}
+
+	if (_soundFault) {
 		_soundEventSubIndex = 0;
 		return;
 	}
 
-	_soundUsesAnimData = state[0x51] != 0;
-	_soundNextCue = 0;
-	byte *buffers[2] = {nullptr, nullptr};
-	uint32 decodedSizes[2] = {0, 0};
+	uint16 cueCount = MIN<uint16>(READ_LE_UINT16(_soundPackedState + 0x3D), COMFY_SOUND_MAX_CUES);
+	for (uint16 i = 0; i < cueCount; i++) {
+		SoundCue cue;
+		cue.value = READ_LE_UINT16(_soundPackedState + 0x15 + i * 2);
+		cue.streamPosition = READ_LE_UINT32(_soundPackedState + 0x1D + i * 4);
+		cue.counterThreshold = READ_LE_UINT32(_soundPackedState + 0x2D + i * 4);
+		_soundCues.push_back(cue);
+	}
+
+	_soundEventSubIndex = 0xFFFF;
+	soundFillPcmBuffer(0, (uint16)(_isPanther ? COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES : (_engineVersion == 3 ? COMFY_V3_SOUND_PCM_BLOCK_BYTES : COMFY_SOUND_PCM_BLOCK_BYTES)));
 
-	if (!soundDecodePcmBlock(0, buffers[0], decodedSizes[0]) ||
-			!soundDecodePcmBlock(1, buffers[1], decodedSizes[1])) {
-		free(buffers[0]);
-		free(buffers[1]);
+	if (_soundFault) {
 		_soundEventSubIndex = 0;
 		return;
 	}
 
-	_soundSampleRate = _soundDecoderState->getRate();
-	_soundQueueStream = Audio::makeQueuingAudioStream(_soundSampleRate, false);
+	soundFillPcmBuffer(1, (uint16)(_isPanther ? COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES : (_engineVersion == 3 ? COMFY_V3_SOUND_PCM_BLOCK_BYTES : COMFY_SOUND_PCM_BLOCK_BYTES)));
 
-	if (!_soundQueueStream) {
-		free(buffers[0]);
-		free(buffers[1]);
+	if (_soundFault) {
 		_soundEventSubIndex = 0;
 		return;
 	}
 
-	_soundQueueStream->queueBuffer(buffers[0], decodedSizes[0], DisposeAfterUse::YES, Audio::FLAG_UNSIGNED);
-	_soundQueueStream->queueBuffer(buffers[1], decodedSizes[1], DisposeAfterUse::YES, Audio::FLAG_UNSIGNED);
+	if (!waveOutStartPlayback()) {
+		_soundEventSubIndex = 0;
+		return;
+	}
 
 	_soundWaveBufferIndex = 0;
-	_soundEventSubIndex = 0xFFFF;
+	_soundVocCounterSnapshot = vocCounter;
+	_soundVocBlockCount = 0;
 
 	if (_midiPlyrDriver) {
 		_midiPlyrDriver->setVocCounter(vocCounter);
 		_midiPlyrDriver->setIncreaseVocCounter(1);
 		_midiPlyrDriver->vocSrResetCounters();
 	}
-
-	_mixer->playStream(Audio::Mixer::kSpeechSoundType, &_soundHandle, _soundQueueStream, -1,
-		Audio::Mixer::kMaxChannelVolume, 0, DisposeAfterUse::YES);
 }
 
 void ComfyEngine::soundPlayEntry(uint16 index) {
-	_mixer->stopHandle(_soundHandle);
-	_soundQueueStream = nullptr;
-
-	if (!soundPrepareDecoderState(index)) {
-		_soundEventSubIndex = 0;
-		return;
-	}
+	waveOutReset();
 
+	_soundEventSubIndex = 0xFFFF;
 	_soundTimingPaused = false;
 	_soundVocBlockCount = 0;
 	_soundVocCounterSnapshot = 0;
-	_soundVocTimingDelta = 0;
+	_soundStreamPosition = 0;
+	_soundPlayPosition = 0;
+	_soundFillCount = 0;
+	_soundEventLength = 0;
+	_soundEventRemaining = 0;
+	_soundLoopCount = 0;
+	_soundStopped = false;
+	_soundStarted = false;
+
+	if (_engineVersion == 3)
+		_soundCounterEnabled = true;
+
+	_soundFault = false;
+	_soundCues.clear();
 
-	byte *buffers[2] = {nullptr, nullptr};
-	uint32 decodedSizes[2] = {0, 0};
+	if (_midiPlyrDriver)
+		_midiPlyrDriver->vocSrResetCounters();
 
-	if (!soundDecodePcmBlock(0, buffers[0], decodedSizes[0]) || !soundDecodePcmBlock(1, buffers[1], decodedSizes[1])) {
-		free(buffers[0]);
-		free(buffers[1]);
-		delete _soundDecoderState;
-		_soundDecoderState = nullptr;
+	byte initialSample = soundOpenEntry(index);
+	if (!initialSample && _soundFault) {
 		_soundEventSubIndex = 0;
+		_soundStopped = true;
 		return;
 	}
 
-	_soundSampleRate = _soundDecoderState->getRate();
-	_soundQueueStream = Audio::makeQueuingAudioStream(_soundSampleRate, false);
+	_soundSample = _engineVersion == 3 ? 0 : (_isPanther ? 0xA5 : initialSample);
+	if (!_soundSample)
+		_soundSample = 0xA5;
+
+	soundFillPcmBuffer(0, (uint16)(_isPanther ? COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES :
+		(_engineVersion == 3 ? COMFY_V3_SOUND_PCM_BLOCK_BYTES : COMFY_SOUND_PCM_BLOCK_BYTES)));
 
-	if (!_soundQueueStream) {
-		free(buffers[0]);
-		free(buffers[1]);
-		delete _soundDecoderState;
-		_soundDecoderState = nullptr;
+	if (_soundFault) {
 		_soundEventSubIndex = 0;
 		return;
 	}
 
-	_soundQueueStream->queueBuffer(buffers[0], decodedSizes[0], DisposeAfterUse::YES, Audio::FLAG_UNSIGNED);
-	_soundQueueStream->queueBuffer(buffers[1], decodedSizes[1], DisposeAfterUse::YES, Audio::FLAG_UNSIGNED);
+	if (_soundNextSample)
+		_soundSample = _soundNextSample;
 
-	_mixer->playStream(Audio::Mixer::kSpeechSoundType, &_soundHandle, _soundQueueStream, -1,
-		Audio::Mixer::kMaxChannelVolume, 0, DisposeAfterUse::YES);
+	soundFillPcmBuffer(1, (uint16)(_isPanther ? COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES :
+		(_engineVersion == 3 ? COMFY_V3_SOUND_PCM_BLOCK_BYTES : COMFY_SOUND_PCM_BLOCK_BYTES)));
+
+	if (_soundFault) {
+		_soundEventSubIndex = 0;
+		return;
+	}
+
+	if (_soundNextSample)
+		_soundSample = _soundNextSample;
 
-	_soundPaused = false;
 	_soundWaveBufferIndex = 0;
-	_soundEventSubIndex = 0xFFFF;
 
 	if (_midiPlyrDriver) {
-		_midiPlyrDriver->vocSrResetCounters();
 		_midiPlyrDriver->setVocCounter(0);
 		_midiPlyrDriver->setIncreaseVocCounter(1);
 	}
+
+	_soundSampleRate = soundCalcSampleRate(_soundSample);
+
+	if (!waveOutStartPlayback()) {
+		_soundEventSubIndex = 0;
+		return;
+	}
+
+	_soundPaused = false;
+	_soundStopped = false;
+	_soundEventSubIndex = 0xFFFF;
 }
 
-void ComfyEngine::soundAdvanceTick() {
+void ComfyEngine::soundUnprepareHeader() {
 	if (_soundPaused)
 		return;
 
-	soundUpdateVocTiming();
-
 	if (!_mixer->isSoundHandleActive(_soundHandle)) {
 		_soundQueueStream = nullptr;
-
-		if (_soundDecoderState && _soundEventSubIndex != 0) {
-			_soundEventSubIndex = 0;
-		}
-
 		return;
 	}
 
-	uint32 counter = _midiPlyrDriver ? _midiPlyrDriver->getVocCounter() : (uint32)((_mixer->getSoundElapsedTime(_soundHandle) + 9) / 10);
+	uint32 queuedBlocks = _soundQueueStream->numQueuedStreams();
 	soundServiceWaveBuffers();
 
+	if (!_isPanther && _soundQueueStream->numQueuedStreams() > queuedBlocks)
+		soundLoadChunk();
+}
+
+void ComfyEngine::soundCueTick() {
+	uint32 counter = _midiPlyrDriver ? _midiPlyrDriver->getVocCounter() : (uint32)((_mixer->getSoundElapsedTime(_soundHandle) + 9) / 10);
 	int32 compareCounter = (int32)(counter - 2);
-	bool phaseCueSeen = false;
 
-	while (_soundNextCue < _soundCues.size() && compareCounter > (int32)_soundCues[_soundNextCue].counterThreshold &&
-			(_soundCues[_soundNextCue].value == 1 || _soundCues[_soundNextCue].value == 2)) {
-		phaseCueSeen = true;
-		_soundEventSubIndex = _soundCues[_soundNextCue].value;
-		_soundNextCue++;
+	bool removedPhaseCue = false;
+
+	while (!_soundCues.empty() && compareCounter > (int32)_soundCues[0].counterThreshold &&
+			(_soundCues[0].value == 1 || _soundCues[0].value == 2)) {
+		_soundEventSubIndex = _soundCues[0].value;
+		_soundCues.remove_at(0);
+		removedPhaseCue = true;
 	}
 
-	if (phaseCueSeen || _soundNextCue == _soundCues.size() || compareCounter <= (int32)_soundCues[_soundNextCue].counterThreshold)
+	if (removedPhaseCue || _soundCues.empty() || compareCounter <= (int32)_soundCues[0].counterThreshold)
 		return;
 
-	_soundEventSubIndex = _soundCues[_soundNextCue].value;
-	_soundNextCue++;
-
+	_soundEventSubIndex = _soundCues[0].value;
 	if (!_soundEventSubIndex) {
-		_mixer->stopHandle(_soundHandle);
-		_soundQueueStream = nullptr;
-		_soundCues.clear();
-		_soundNextCue = 0;
-		_soundVocTimingDelta = 0;
-		if (_midiPlyrDriver) {
-			_midiPlyrDriver->vocSrResetBlockNo();
+		if (_engineVersion == 3) {
+			soundPrepareQueuePlayback();
+		} else if (_isPanther) {
+			soundStopPlayback();
+		} else {
+			waveOutReset();
 		}
+
+		_soundStopped = true;
+		_soundCues.clear();
+		return;
+	}
+
+	_soundCues.remove_at(0);
+}
+
+void ComfyEngine::soundAdvanceTick() {
+	if (_engineVersion == 3) {
+		if (_soundCounterEnabled)
+			soundUpdateVocTiming();
+
+		soundServiceWaveBuffers();
+		soundCueTick();
+		return;
 	}
+
+	if (_isPanther) {
+		soundUpdateVocTiming();
+		soundServiceWaveBuffers();
+	} else {
+		soundUnprepareHeader();
+	}
+
+	soundCueTick();
 }
 
 } // End of namespace Comfy
diff --git a/engines/comfy/timer.cpp b/engines/comfy/timer.cpp
index f90d9db5107..a8188fe610f 100644
--- a/engines/comfy/timer.cpp
+++ b/engines/comfy/timer.cpp
@@ -53,8 +53,6 @@ uint16 ComfyEngine::timerTick() {
 	while (callbacks--) {
 		if (shouldQuit())
 			return 0;
-
-		soundAdvanceTick();
 	}
 
 	_timer2 = _timer1;


Commit: 02b54958009b655cc36c3ba36d02d62dbb0cf77e
    https://github.com/scummvm/scummvm/commit/02b54958009b655cc36c3ba36d02d62dbb0cf77e
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Add detection for Christmas in ComfyLand

Changed paths:
    engines/comfy/detection_tables.h
    engines/comfy/game.cpp


diff --git a/engines/comfy/detection_tables.h b/engines/comfy/detection_tables.h
index 1ad0e65d214..1c4cdfe41f2 100644
--- a/engines/comfy/detection_tables.h
+++ b/engines/comfy/detection_tables.h
@@ -23,6 +23,7 @@ namespace Comfy {
 
 const PlainGameDescriptor comfyGames[] = {
 	{ "comfyland", "ComfyLand" },
+	{ "christmas", "Christmas in ComfyLand" },
 	{ "boo", "Comfy Touch-n-See: Didi and Boo" },
 	{ "first", "Comfy Touch-n-See: The First Step" },
 	{ "match", "Comfy Max: A Purrfect Match" },
@@ -72,6 +73,24 @@ const ComfyGameDescription gameDescriptions[] = {
 		0x100
 	},
 
+	{
+		{
+		"christmas",
+		nullptr,
+		AD_ENTRY3s("CHRISTMS/ENGLISH/COMFY.OBJ",    "14d538b948297ddafc14d7a5977de223", 71680,
+				   "CHRISTMS/ENGLISH/MIDIFILE.DAT", "3920eede90b15a36ffb57f7c634d50e7", 155719,
+				   "INTRO/COMFY.OBJ",               "b8fb0c9d325ec4db8ce37ef0d08da130", 4096),
+		Common::UNK_LANG,
+		Common::kPlatformWindows,
+		ADGF_UNSTABLE,
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
+			GAMEOPTION_USE_IMGUI_KEYBOARD)
+		},
+		1,
+		0,
+		0
+	},
+
 	{
 		{
 		"boo",
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index d0b66326d8c..a7cee09f77e 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -79,6 +79,9 @@ void ComfyEngine::gameConfigInit() {
 	if (!strcmp(_game->desc.gameId, "comfyland")) {
 		_gameDirectory = Common::Path("COMFY1");
 		_introDirectory = Common::Path("INTRO");
+	} else if (!strcmp(_game->desc.gameId, "christmas")) {
+		_gameDirectory = Common::Path("CHRISTMS");
+		_introDirectory = Common::Path("INTRO");
 	} else if (!strcmp(_game->desc.gameId, "boo")) {
 		_gameDirectory = Common::Path("BOO");
 		_introDirectory = Common::Path("FINTRO");


Commit: c7d034fe98b55ef6ab9477f1c8f3bde0dc4a0a23
    https://github.com/scummvm/scummvm/commit/c7d034fe98b55ef6ab9477f1c8f3bde0dc4a0a23
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Clean up detection code

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/detection.h
    engines/comfy/detection_tables.h
    engines/comfy/script_vm.cpp
    engines/comfy/video.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 43fa13998b7..bec133fa902 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -118,6 +118,20 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ComfyGameDescription *gameDesc) :
 		_isPanther = true;
 		_backgroundBufferEnabled = true;
 		_vocQueueCapacity = COMFY_PANTHER_VOC_QUEUE_CAPACITY;
+		_scriptFeatures = COMFY_SCRIPT_OPCODE_31 | COMFY_SCRIPT_OPCODE_32;
+		_dirtyRectMergeThreshold = 0x40;
+	} else if (!strcmp(gameDesc->desc.gameId, "boo")) {
+		_scriptFeatures = COMFY_SCRIPT_OPCODE_31;
+		_dirtyRectMergeThreshold = 0x100;
+	} else if (!strcmp(gameDesc->desc.gameId, "first") && gameDesc->version == 2) {
+		_scriptFeatures = COMFY_SCRIPT_OPCODE_31 | COMFY_SCRIPT_OPCODE_33;
+		_dirtyRectMergeThreshold = 0x100;
+	} else if (!strcmp(gameDesc->desc.gameId, "match")) {
+		_scriptFeatures = 0;
+		_dirtyRectMergeThreshold = 0x40;
+	} else {
+		_scriptFeatures = 0;
+		_dirtyRectMergeThreshold = gameDesc->version >= 2 ? 0x100 : 0;
 	}
 
 	g_engine = this;
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index f848ddcc8c8..326f6cfc5cf 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -506,6 +506,8 @@ private:
 
 	const ComfyGameDescription *_game;
 	byte _engineVersion;
+	byte _scriptFeatures;
+	uint16 _dirtyRectMergeThreshold;
 	bool _isPanther = false;
 	bool _backgroundBufferEnabled = false;
 	uint16 _vocQueueCapacity = COMFY_VOC_QUEUE_CAPACITY;
diff --git a/engines/comfy/detection.h b/engines/comfy/detection.h
index ef143843007..23c387e00c2 100644
--- a/engines/comfy/detection.h
+++ b/engines/comfy/detection.h
@@ -45,8 +45,6 @@ struct ComfyGameDescription {
 
 	ADGameDescription desc;
 	byte version;
-	byte scriptFeatures;
-	uint16 dirtyRectMergeThreshold;
 };
 
 #define COMFY_SCRIPT_OPCODE_31 (1 << 0)
diff --git a/engines/comfy/detection_tables.h b/engines/comfy/detection_tables.h
index 1c4cdfe41f2..124af7ec206 100644
--- a/engines/comfy/detection_tables.h
+++ b/engines/comfy/detection_tables.h
@@ -48,9 +48,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
 			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
-		1,
-		0,
-		0
+		1
 	},
 
 	{
@@ -68,9 +66,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
 			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
-		3,
-		0,
-		0x100
+		3
 	},
 
 	{
@@ -86,9 +82,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
 			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
-		1,
-		0,
-		0
+		1
 	},
 
 	{
@@ -104,9 +98,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
 			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
-		2,
-		COMFY_SCRIPT_OPCODE_31,
-		0x100
+		2
 	},
 
 	{
@@ -121,9 +113,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
 			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
-		2,
-		COMFY_SCRIPT_OPCODE_31 | COMFY_SCRIPT_OPCODE_33,
-		0x100
+		2
 	},
 
 	{
@@ -138,9 +128,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
 			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
-		1,
-		0,
-		0
+		1
 	},
 
 	{
@@ -155,9 +143,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
 			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
-		2,
-		0,
-		0x40
+		2
 	},
 
 	{
@@ -173,9 +159,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
 			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
-		3,
-		0,
-		0x100
+		3
 	},
 
 	{
@@ -191,9 +175,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
 			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
-		3,
-		0,
-		0x100
+		3
 	},
 
 	{
@@ -209,9 +191,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
 			GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
-		3,
-		0,
-		0x100
+		3
 	},
 
 	{
@@ -226,12 +206,10 @@ const ComfyGameDescription gameDescriptions[] = {
 		ADGF_UNSTABLE,
 		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
-		2,
-		COMFY_SCRIPT_OPCODE_31 | COMFY_SCRIPT_OPCODE_32,
-		0x40
+		2
 	},
 
-	{ AD_TABLE_END_MARKER, 0, 0, 0 }
+	{ AD_TABLE_END_MARKER, 0 }
 };
 
 } // End of namespace Comfy
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 854945f711c..25e4560b0d7 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -813,9 +813,9 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	case O_MOUSE_SET_ACTOR:
 	case O_HOST_MEDIA_CONTROL:
 		if (!((_engineVersion == 3) ||
-			(opcode == O_SET_LAST_VOC_ARGUMENTS && (_game->scriptFeatures & COMFY_SCRIPT_OPCODE_31)) ||
-			(opcode == O_UNUSED_32 && (_game->scriptFeatures & COMFY_SCRIPT_OPCODE_32)) ||
-			(opcode == O_SKIP_TABLE_BLOCK && (_game->scriptFeatures & COMFY_SCRIPT_OPCODE_33))))
+			(opcode == O_SET_LAST_VOC_ARGUMENTS && (_scriptFeatures & COMFY_SCRIPT_OPCODE_31)) ||
+			(opcode == O_UNUSED_32 && (_scriptFeatures & COMFY_SCRIPT_OPCODE_32)) ||
+			(opcode == O_SKIP_TABLE_BLOCK && (_scriptFeatures & COMFY_SCRIPT_OPCODE_33))))
 			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
 	{
 		switch (opcode) {
diff --git a/engines/comfy/video.cpp b/engines/comfy/video.cpp
index df255d076e4..8d56a50a456 100644
--- a/engines/comfy/video.cpp
+++ b/engines/comfy/video.cpp
@@ -107,7 +107,7 @@ void ComfyEngine::renderInvalidateFullFrame() {
 
 void ComfyEngine::renderAddDirtyRectMerged(ComfyRect record) {
 	int16 alignment = _isPanther ? 4 : 2;
-	uint32 mergeThreshold = _game->dirtyRectMergeThreshold;
+	uint32 mergeThreshold = _dirtyRectMergeThreshold;
 
 	record.left = CLIP<int16>(record.left, 0, _logicalScreenWidth);
 	record.left = record.left / alignment * alignment;


Commit: 65fa374a2b97d5201899d33d94408dc401f54983
    https://github.com/scummvm/scummvm/commit/65fa374a2b97d5201899d33d94408dc401f54983
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Remove useless _scriptFeatures member

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/detection.h
    engines/comfy/script_vm.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index bec133fa902..da6f6adb36f 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -118,19 +118,10 @@ ComfyEngine::ComfyEngine(OSystem *syst, const ComfyGameDescription *gameDesc) :
 		_isPanther = true;
 		_backgroundBufferEnabled = true;
 		_vocQueueCapacity = COMFY_PANTHER_VOC_QUEUE_CAPACITY;
-		_scriptFeatures = COMFY_SCRIPT_OPCODE_31 | COMFY_SCRIPT_OPCODE_32;
 		_dirtyRectMergeThreshold = 0x40;
-	} else if (!strcmp(gameDesc->desc.gameId, "boo")) {
-		_scriptFeatures = COMFY_SCRIPT_OPCODE_31;
-		_dirtyRectMergeThreshold = 0x100;
-	} else if (!strcmp(gameDesc->desc.gameId, "first") && gameDesc->version == 2) {
-		_scriptFeatures = COMFY_SCRIPT_OPCODE_31 | COMFY_SCRIPT_OPCODE_33;
-		_dirtyRectMergeThreshold = 0x100;
 	} else if (!strcmp(gameDesc->desc.gameId, "match")) {
-		_scriptFeatures = 0;
 		_dirtyRectMergeThreshold = 0x40;
 	} else {
-		_scriptFeatures = 0;
 		_dirtyRectMergeThreshold = gameDesc->version >= 2 ? 0x100 : 0;
 	}
 
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 326f6cfc5cf..c7001058401 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -506,7 +506,6 @@ private:
 
 	const ComfyGameDescription *_game;
 	byte _engineVersion;
-	byte _scriptFeatures;
 	uint16 _dirtyRectMergeThreshold;
 	bool _isPanther = false;
 	bool _backgroundBufferEnabled = false;
diff --git a/engines/comfy/detection.h b/engines/comfy/detection.h
index 23c387e00c2..5f9ebdfbc5e 100644
--- a/engines/comfy/detection.h
+++ b/engines/comfy/detection.h
@@ -47,9 +47,6 @@ struct ComfyGameDescription {
 	byte version;
 };
 
-#define COMFY_SCRIPT_OPCODE_31 (1 << 0)
-#define COMFY_SCRIPT_OPCODE_32 (1 << 1)
-#define COMFY_SCRIPT_OPCODE_33 (1 << 2)
 
 extern const PlainGameDescriptor comfyGames[];
 
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 25e4560b0d7..02b71f845cd 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -812,14 +812,9 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	case O_CONFIG_STRING_COMMAND:
 	case O_MOUSE_SET_ACTOR:
 	case O_HOST_MEDIA_CONTROL:
-		if (!((_engineVersion == 3) ||
-			(opcode == O_SET_LAST_VOC_ARGUMENTS && (_scriptFeatures & COMFY_SCRIPT_OPCODE_31)) ||
-			(opcode == O_UNUSED_32 && (_scriptFeatures & COMFY_SCRIPT_OPCODE_32)) ||
-			(opcode == O_SKIP_TABLE_BLOCK && (_scriptFeatures & COMFY_SCRIPT_OPCODE_33))))
-			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
 	{
 		switch (opcode) {
-		case O_SET_LAST_VOC_ARGUMENTS: {
+		case O_SET_LAST_VOC_ARGUMENTS: { // Added in version 2
 			uint16 count = scriptReadStringIndex(pc);
 			pc += 2;
 			if (_animUsesWaveVocCounter) {
@@ -841,12 +836,12 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 			break;
 		}
-		case O_UNUSED_32:
+		case O_UNUSED_32: // Added in version 2 (Panther only)
 			scriptReadStringIndex(pc);
 			scriptReadStringIndex(pc + 2);
 			pc += 4;
 			break;
-		case O_SKIP_TABLE_BLOCK: {
+		case O_SKIP_TABLE_BLOCK: { // Added in version 2 (First Step 1997 only)
 			pc += 4;
 			byte inlineBytes = scriptReadByte(pc++);
 			byte tripleCount = scriptReadByte(pc++);


Commit: 3f519f137363c4c0d4aa37f4cd61c32deea4287f
    https://github.com/scummvm/scummvm/commit/3f519f137363c4c0d4aa37f4cd61c32deea4287f
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Remove console.cpp/.h

Changed paths:
  R engines/comfy/console.cpp
  R engines/comfy/console.h
    engines/comfy/comfy.cpp
    engines/comfy/module.mk


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index da6f6adb36f..2feb7b9b68b 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -21,7 +21,6 @@
 
 #include "comfy/comfy.h"
 #include "comfy/detection.h"
-#include "comfy/console.h"
 #include "common/scummsys.h"
 #include "common/config-manager.h"
 #include "common/debug.h"
@@ -138,7 +137,6 @@ Common::String ComfyEngine::getGameId() const {
 }
 
 Common::Error ComfyEngine::run() {
-	setDebugger(new Console());
 	return gameInit();
 }
 
diff --git a/engines/comfy/console.cpp b/engines/comfy/console.cpp
deleted file mode 100644
index f9d4075dfee..00000000000
--- a/engines/comfy/console.cpp
+++ /dev/null
@@ -1,38 +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 "comfy/console.h"
-
-namespace Comfy {
-
-Console::Console() : GUI::Debugger() {
-	registerCmd("test",   WRAP_METHOD(Console, Cmd_test));
-}
-
-Console::~Console() {
-}
-
-bool Console::Cmd_test(int argc, const char **argv) {
-	debugPrintf("Test\n");
-	return true;
-}
-
-} // End of namespace Comfy
diff --git a/engines/comfy/console.h b/engines/comfy/console.h
deleted file mode 100644
index 39e0fe5a79e..00000000000
--- a/engines/comfy/console.h
+++ /dev/null
@@ -1,40 +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 COMFY_CONSOLE_H
-#define COMFY_CONSOLE_H
-
-#include "gui/debugger.h"
-
-namespace Comfy {
-
-class Console : public GUI::Debugger {
-private:
-	bool Cmd_test(int argc, const char **argv);
-public:
-	Console();
-	~Console() override;
-};
-
-} // End of namespace Comfy
-
-#endif // COMFY_CONSOLE_H
diff --git a/engines/comfy/module.mk b/engines/comfy/module.mk
index 75faaf4bc84..babcee89696 100644
--- a/engines/comfy/module.mk
+++ b/engines/comfy/module.mk
@@ -5,7 +5,6 @@ MODULE_OBJS = \
 	anim_file.o \
 	comfy.o \
 	comfy_keyboard_ui.o \
-	console.o \
 	debug.o \
 	expr.o \
 	game.o \
@@ -14,7 +13,7 @@ MODULE_OBJS = \
 	memory.o \
 	metaengine.o \
 	midi.o \
-	midiplyr/midiplyr.o \
+	midiplyr.o \
 	object_file.o \
 	palette.o \
 	scene.o \


Commit: fcfdbbc002ab3b434021c7c0b8df70827b55a076
    https://github.com/scummvm/scummvm/commit/fcfdbbc002ab3b434021c7c0b8df70827b55a076
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Add credits

Changed paths:
    engines/comfy/credits.pl


diff --git a/engines/comfy/credits.pl b/engines/comfy/credits.pl
index 731f5190b80..e993a13a29d 100644
--- a/engines/comfy/credits.pl
+++ b/engines/comfy/credits.pl
@@ -1,3 +1,3 @@
 begin_section("Comfy");
-	add_person("Name 1", "Handle 1", "");
+	add_person("Andrea Boscarino", "Bosca", "");
 end_section();


Commit: 204f371c5b76464b9cf4feb1f8cf4a1cd8d71077
    https://github.com/scummvm/scummvm/commit/204f371c5b76464b9cf4feb1f8cf4a1cd8d71077
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Move midiplyr driver to main folder

Changed paths:
  A engines/comfy/midiplyr.cpp
  A engines/comfy/midiplyr.h
  R engines/comfy/midiplyr/midiplyr.cpp
  R engines/comfy/midiplyr/midiplyr.h
    engines/comfy/anim_file.cpp
    engines/comfy/comfy.h
    engines/comfy/input.cpp
    engines/comfy/midi.cpp
    engines/comfy/sound.cpp


diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
index ae7f35ffa1f..9b19e3610ea 100644
--- a/engines/comfy/anim_file.cpp
+++ b/engines/comfy/anim_file.cpp
@@ -20,7 +20,7 @@
  */
 
 #include "comfy/comfy.h"
-#include "comfy/midiplyr/midiplyr.h"
+#include "comfy/midiplyr.h"
 
 #include "common/debug.h"
 #include "common/endian.h"
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index c7001058401..1891e657427 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -37,7 +37,7 @@
 #include "audio/mixer.h"
 
 #include "comfy/detection.h"
-#include "comfy/midiplyr/midiplyr.h"
+#include "comfy/midiplyr.h"
 
 namespace Audio {
 class QueuingAudioStream;
diff --git a/engines/comfy/input.cpp b/engines/comfy/input.cpp
index 590c130ef3f..be3af251d78 100644
--- a/engines/comfy/input.cpp
+++ b/engines/comfy/input.cpp
@@ -20,7 +20,7 @@
  */
 
 #include "comfy/comfy.h"
-#include "comfy/midiplyr/midiplyr.h"
+#include "comfy/midiplyr.h"
 
 
 namespace Comfy {
diff --git a/engines/comfy/midi.cpp b/engines/comfy/midi.cpp
index c20f02f4706..82471df351d 100644
--- a/engines/comfy/midi.cpp
+++ b/engines/comfy/midi.cpp
@@ -20,7 +20,7 @@
  */
 
 #include "comfy/comfy.h"
-#include "comfy/midiplyr/midiplyr.h"
+#include "comfy/midiplyr.h"
 
 #include "common/endian.h"
 
diff --git a/engines/comfy/midiplyr/midiplyr.cpp b/engines/comfy/midiplyr.cpp
similarity index 99%
rename from engines/comfy/midiplyr/midiplyr.cpp
rename to engines/comfy/midiplyr.cpp
index a09396bcda8..6756d52156a 100644
--- a/engines/comfy/midiplyr/midiplyr.cpp
+++ b/engines/comfy/midiplyr.cpp
@@ -19,7 +19,7 @@
  *
  */
 
-#include "comfy/midiplyr/midiplyr.h"
+#include "comfy/midiplyr.h"
 
 #include "audio/mididrv.h"
 #include "common/endian.h"
diff --git a/engines/comfy/midiplyr/midiplyr.h b/engines/comfy/midiplyr.h
similarity index 100%
rename from engines/comfy/midiplyr/midiplyr.h
rename to engines/comfy/midiplyr.h
diff --git a/engines/comfy/sound.cpp b/engines/comfy/sound.cpp
index 8553db8d5c9..4d0c1fdba79 100644
--- a/engines/comfy/sound.cpp
+++ b/engines/comfy/sound.cpp
@@ -19,7 +19,7 @@
  *
  */
 #include "comfy/comfy.h"
-#include "comfy/midiplyr/midiplyr.h"
+#include "comfy/midiplyr.h"
 
 #include "audio/decoders/raw.h"
 #include "audio/audiostream.h"


Commit: d9b78e99eb995595bd75073aa2d2ef5e4e35d162
    https://github.com/scummvm/scummvm/commit/d9b78e99eb995595bd75073aa2d2ef5e4e35d162
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Remove cstdarg dev leftover from script.cpp and rename to script_utils.cpp

Changed paths:
  A engines/comfy/script_utils.cpp
  R engines/comfy/script.cpp
    engines/comfy/module.mk


diff --git a/engines/comfy/module.mk b/engines/comfy/module.mk
index babcee89696..076e6ad9d95 100644
--- a/engines/comfy/module.mk
+++ b/engines/comfy/module.mk
@@ -17,7 +17,7 @@ MODULE_OBJS = \
 	object_file.o \
 	palette.o \
 	scene.o \
-	script.o \
+	script_utils.o \
 	script_vm.o \
 	sound.o \
 	timer.o \
diff --git a/engines/comfy/script.cpp b/engines/comfy/script_utils.cpp
similarity index 99%
rename from engines/comfy/script.cpp
rename to engines/comfy/script_utils.cpp
index 87153732acd..f652e21c0dd 100644
--- a/engines/comfy/script.cpp
+++ b/engines/comfy/script_utils.cpp
@@ -23,8 +23,6 @@
 
 #include "common/endian.h"
 
-#include <cstdarg>
-
 namespace Comfy {
 
 byte ComfyEngine::scriptReadByte(uint32 pc) {


Commit: 4a26af3017e66c2dfd77f5d4593c6477657c7b2d
    https://github.com/scummvm/scummvm/commit/4a26af3017e66c2dfd77f5d4593c6477657c7b2d
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Add "hires" to deps in configure.engine

Even though panther is the only hires target, I see no point in creating
a subengine just for that if platforms have to support ImGui in the first
place just to run any of these games...

Changed paths:
    engines/comfy/configure.engine


diff --git a/engines/comfy/configure.engine b/engines/comfy/configure.engine
index 0cb27a516e5..a3fc7cc122b 100644
--- a/engines/comfy/configure.engine
+++ b/engines/comfy/configure.engine
@@ -1,3 +1,3 @@
 # This file is included from the main "configure" script
 # add_engine [name] [desc] [build-by-default] [subengines] [base games] [deps] [components]
-add_engine comfy "Comfy" no "" "" "" "imgui"
+add_engine comfy "Comfy" no "" "" "highres" "imgui"


Commit: 3d646495a633bdf00a49ac7d53e20685f7927398
    https://github.com/scummvm/scummvm/commit/3d646495a633bdf00a49ac7d53e20685f7927398
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: DETECTION: Remove _directoryGlobs and _maxScanDepth assignments

Changed paths:
    engines/comfy/detection.cpp


diff --git a/engines/comfy/detection.cpp b/engines/comfy/detection.cpp
index 0c8c8665981..c4b566c3b36 100644
--- a/engines/comfy/detection.cpp
+++ b/engines/comfy/detection.cpp
@@ -38,24 +38,9 @@ const DebugChannelDef ComfyMetaEngineDetection::debugFlagList[] = {
 	DEBUG_CHANNEL_END
 };
 
-static const char *const directoryGlobs[] = {
-	"BOO",
-	"COLORS",
-	"COMFY1",
-	"CONCERT",
-	"ENGLISH",
-	"FIRST",
-	"FRIENDS",
-	"MATCH",
-	"PANTHER",
-	nullptr
-};
-
 ComfyMetaEngineDetection::ComfyMetaEngineDetection() : AdvancedMetaEngineDetection(
 	Comfy::gameDescriptions, Comfy::comfyGames) {
 	_flags = kADFlagMatchFullPaths;
-	_maxScanDepth = 2;
-	_directoryGlobs = directoryGlobs;
 }
 
 REGISTER_PLUGIN_STATIC(COMFY_DETECTION, PLUGIN_TYPE_ENGINE_DETECTION, ComfyMetaEngineDetection);


Commit: 037876745e76221c576664a2ba3d229be2d08e98
    https://github.com/scummvm/scummvm/commit/037876745e76221c576664a2ba3d229be2d08e98
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Add ComfyRect equals() method to avoid huge if clauses

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/comfy.h


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index bab9cfcfd68..ce5fa5c4a83 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -1662,16 +1662,10 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 					ComfyRect &currentRect = _keymaskRects[i];
 					ComfyRect &previousRect = _keymaskOldRects[i];
 
-					bool equal = currentRect.left == previousRect.left &&
-						currentRect.top == previousRect.top &&
-						currentRect.right == previousRect.right &&
-						currentRect.bottom == previousRect.bottom &&
-						currentRect.area == previousRect.area;
-
-					if (!equal)
+					if (!currentRect.equals(previousRect))
 						renderAddDirtyRect(previousRect);
 
-					renderQueueDrawCommand(currentRect.left, currentRect.top, currentRect.area, equal ? 1 : 0, actorIndex);
+					renderQueueDrawCommand(currentRect.left, currentRect.top, currentRect.area, currentRect.equals(previousRect) ? 1 : 0, actorIndex);
 				}
 			}
 
@@ -1681,10 +1675,7 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 			return;
 		}
 
-		bool changed = oldSelector != selector || oldRect.left != newRect.left ||
-			oldRect.top != newRect.top || oldRect.right != newRect.right ||
-			oldRect.bottom != newRect.bottom || oldRect.area != newRect.area ||
-			oldVisible != (visible ? 1 : 0);
+		bool changed = oldSelector != selector || !oldRect.equals(newRect) || oldVisible != (visible ? 1 : 0);
 
 		if (changed) {
 			if (visible && selector) {
@@ -1863,8 +1854,7 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 		byte newVisible = visible ? 1 : 0;
 		bool changed = oldSelector != selector || oldVisible != newVisible;
 
-		if (oldRect.left  != newRect.left  || oldRect.top    != newRect.top    ||
-			oldRect.right != newRect.right || oldRect.bottom != newRect.bottom || oldRect.area != newRect.area)
+		if (!oldRect.equals(newRect))
 			changed = true;
 
 		uint16 oldScriptedLastRect = 0xFFFF;
@@ -1888,8 +1878,7 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 				for (uint i = 0; i <= last; i++) {
 					ComfyRect *oldItem = i <= oldScriptedLastRect ? &_keymaskOldRects[i] : nullptr;
 					ComfyRect *newItem = i <= scriptedLastRect ? &_keymaskRects[i] : nullptr;
-					bool equal = oldItem && newItem && oldItem->left == newItem->left && oldItem->top == newItem->top &&
-						oldItem->right == newItem->right && oldItem->bottom == newItem->bottom && oldItem->area == newItem->area;
+					bool equal = oldItem && newItem && oldItem->equals(*newItem);
 
 					if (!equal) {
 						if (oldItem) {
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 1891e657427..ca2b337b663 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -146,6 +146,14 @@ struct ComfyRect {
 		bottom = 0;
 		area = 0;
 	}
+
+	bool equals(ComfyRect otherRect) {
+		return left == otherRect.left &&
+			   top == otherRect.top &&
+			   right == otherRect.right &&
+			   bottom == otherRect.bottom &&
+			   area == otherRect.area;
+	}
 };
 
 class ComfyEngine : public Engine {


Commit: 5e313745e958b1e576cfa56ca0d38bb315adcab1
    https://github.com/scummvm/scummvm/commit/5e313745e958b1e576cfa56ca0d38bb315adcab1
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Clean up script_vm.cpp further

This removes the odd nested switches when there were no subops

Changed paths:
    engines/comfy/script_vm.cpp


diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 02b71f845cd..5bdc2e2a0c5 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -754,10 +754,10 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case O_ANIMATION_CONTROL:
+	case O_ANIMATION_CONTROL: {
 		if (!_usesAnimFile)
 			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
-	{
+
 		byte subop = scriptReadByte(pc++);
 		switch (subop) {
 		case SO_ANIM_SHUTDOWN:
@@ -806,232 +806,205 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
-	case O_SET_LAST_VOC_ARGUMENTS:
-	case O_UNUSED_32:
-	case O_SKIP_TABLE_BLOCK:
-	case O_CONFIG_STRING_COMMAND:
-	case O_MOUSE_SET_ACTOR:
-	case O_HOST_MEDIA_CONTROL:
-	{
-		switch (opcode) {
-		case O_SET_LAST_VOC_ARGUMENTS: { // Added in version 2
-			uint16 count = scriptReadStringIndex(pc);
-			pc += 2;
-			if (_animUsesWaveVocCounter) {
-				uint16 slot = _soundEventMaximum ? _soundEventMaximum - 1 : _vocQueueCapacity - 1;
-				if (_engineVersion == 3) {
-					VocQueueEntryV3 &entry = _vocQueueV3[slot];
-					entry.argumentCount = MIN<uint16>(count, COMFY_VOC_ARG_CAPACITY_V3);
-					for (uint i = 0; i < entry.argumentCount; i++)
-						entry.arguments[i] = scriptReadWord(pc + i * 2);
-				} else {
-					VocQueueEntry &entry = _vocQueue[slot];
-					entry.argumentCount = MIN<uint16>(count, COMFY_VOC_ARG_CAPACITY);
-					for (uint i = 0; i < entry.argumentCount; i++)
-						entry.arguments[i] = scriptReadWord(pc + i * 2);
-				}
+	case O_SET_LAST_VOC_ARGUMENTS: { // Added in version 2
+		uint16 count = scriptReadStringIndex(pc);
+		pc += 2;
+		if (_animUsesWaveVocCounter) {
+			uint16 slot = _soundEventMaximum ? _soundEventMaximum - 1 : _vocQueueCapacity - 1;
+			if (_engineVersion == 3) {
+				VocQueueEntryV3 &entry = _vocQueueV3[slot];
+				entry.argumentCount = MIN<uint16>(count, COMFY_VOC_ARG_CAPACITY_V3);
+				for (uint i = 0; i < entry.argumentCount; i++)
+					entry.arguments[i] = scriptReadWord(pc + i * 2);
+			} else {
+				VocQueueEntry &entry = _vocQueue[slot];
+				entry.argumentCount = MIN<uint16>(count, COMFY_VOC_ARG_CAPACITY);
+				for (uint i = 0; i < entry.argumentCount; i++)
+					entry.arguments[i] = scriptReadWord(pc + i * 2);
 			}
+		}
 
-			pc += (uint32)count * 2;
+		pc += (uint32)count * 2;
 
-			break;
-		}
-		case O_UNUSED_32: // Added in version 2 (Panther only)
-			scriptReadStringIndex(pc);
-			scriptReadStringIndex(pc + 2);
-			pc += 4;
-			break;
-		case O_SKIP_TABLE_BLOCK: { // Added in version 2 (First Step 1997 only)
-			pc += 4;
-			byte inlineBytes = scriptReadByte(pc++);
-			byte tripleCount = scriptReadByte(pc++);
-			pc += inlineBytes + (uint32)tripleCount * 3;
-			break;
-		}
-		case O_CONFIG_STRING_COMMAND: {
-			byte subop = scriptReadByte(pc++);
-			uint16 value = scriptReadWord(pc);
-			pc += 2;
-			Common::String key;
-			for (byte character = scriptReadByte(pc++); character; character = scriptReadByte(pc++))
-				key += (char)character;
+		return kScriptContinue;
+	}
 
-			switch (subop) {
-			case SO_CONFIG_READ_INT:
-				if (value < _stringTable.size())
-					_stringTable[value] = ConfMan.hasKey(key) ? ConfMan.getInt(key) : 0;
+	case O_UNUSED_32: // Added in version 2 (Panther only)
+		scriptReadStringIndex(pc);
+		scriptReadStringIndex(pc + 2);
+		pc += 4;
+		return kScriptContinue;
 
-				break;
-			case SO_CONFIG_WRITE_INT:
-				ConfMan.setInt(key, value);
-				if (key.equalsIgnoreCase("SENSITIVITY"))
-					_v3Sensitivity = value;
+	case O_SKIP_TABLE_BLOCK: { // Added in version 2 (First Step 1997 only)
+		pc += 4;
+		byte inlineBytes = scriptReadByte(pc++);
+		byte tripleCount = scriptReadByte(pc++);
+		pc += inlineBytes + (uint32)tripleCount * 3;
+		return kScriptContinue;
+	}
 
-				ConfMan.flushToDisk();
-				break;
-			case SO_CONFIG_SUSPEND_ACTOR:
-			case SO_CONFIG_RUN_COMMAND:
-				_v3ConfigCommandPending = true;
-				_v3ConfigCommandSubop = subop;
-				_v3ConfigCommandValue = value;
-				_v3ConfigCommandText = key;
-
-				if (subop == SO_CONFIG_SUSPEND_ACTOR) {
-					Actor *configActor = actorGetPtr(sceneGetHandle(1));
-					if (configActor)
-						configActor->active = 0;
-				} else {
-					configRunPendingCommand();
-				}
+	case O_CONFIG_STRING_COMMAND: {
+		byte subop = scriptReadByte(pc++);
+		uint16 value = scriptReadWord(pc);
+		pc += 2;
+		Common::String key;
+		for (byte character = scriptReadByte(pc++); character; character = scriptReadByte(pc++))
+			key += (char)character;
 
-				break;
-			case SO_CONFIG_TEST_VALUE:
-				if (ConfMan.hasKey(key) && !ConfMan.get(key).equalsIgnoreCase("?????"))
-					keyBitSet(value);
-				else
-					keyBitClear(value);
+		switch (subop) {
+		case SO_CONFIG_READ_INT:
+			if (value < _stringTable.size())
+				_stringTable[value] = ConfMan.hasKey(key) ? ConfMan.getInt(key) : 0;
 
-				break;
-			case SO_CONFIG_TEST_FILE: {
-				Common::SeekableReadStream *stream = pathFOpen(Common::Path(key), true);
-				if (stream)
-					keyBitSet(value);
-				else
-					keyBitClear(value);
-
-				delete stream;
-				break;
-			}
-			case SO_CONFIG_SET_LANGUAGE_DATA_SUBDIRECTORY:
-				if (value < _stringTable.size())
-					_stringTable[value] = languageSetDataSubdirectory(key);
+			break;
+		case SO_CONFIG_WRITE_INT:
+			ConfMan.setInt(key, value);
+			if (key.equalsIgnoreCase("SENSITIVITY"))
+				_v3Sensitivity = value;
 
-				break;
-			default:
-				error("Unknown script opcode 0x34 subopcode 0x%02X near script PC 0x%08X", subop, pc);
+			ConfMan.flushToDisk();
+			break;
+		case SO_CONFIG_SUSPEND_ACTOR:
+		case SO_CONFIG_RUN_COMMAND:
+			_v3ConfigCommandPending = true;
+			_v3ConfigCommandSubop = subop;
+			_v3ConfigCommandValue = value;
+			_v3ConfigCommandText = key;
+
+			if (subop == SO_CONFIG_SUSPEND_ACTOR) {
+				Actor *configActor = actorGetPtr(sceneGetHandle(1));
+				if (configActor)
+					configActor->active = 0;
+			} else {
+				configRunPendingCommand();
 			}
 
 			break;
-		}
-		case O_MOUSE_SET_ACTOR: {
-			uint32 opcodePc = pc - 1;
-			byte subop = 0;
-			Actor *mouseActor = nullptr;
-			pc = scriptReadArgs(pc, _currentActor, "CO", &subop, &mouseActor);
-			switch (subop) {
-			case SO_MOUSE_SET_ACTOR:
-				mouseSetActor(mouseActor);
-				break;
-			case SO_MOUSE_CLEAR_ACTOR:
-				mouseSetActor(nullptr);
-				break;
-			default:
-				error("Unknown script opcode 0x35 subopcode 0x%02X at script PC 0x%08X", subop, opcodePc);
-			}
+		case SO_CONFIG_TEST_VALUE:
+			if (ConfMan.hasKey(key) && !ConfMan.get(key).equalsIgnoreCase("?????"))
+				keyBitSet(value);
+			else
+				keyBitClear(value);
 
 			break;
+		case SO_CONFIG_TEST_FILE: {
+			Common::SeekableReadStream *stream = pathFOpen(Common::Path(key), true);
+			if (stream)
+				keyBitSet(value);
+			else
+				keyBitClear(value);
+
+			delete stream;
+			break;
 		}
-		case O_HOST_MEDIA_CONTROL: {
-			byte subop = scriptReadByte(pc++);
-			switch (subop) {
-			case SO_HOST_MEDIA_START_INPUT:
-				setMediaMode(subop);
-				break;
-			case SO_HOST_MEDIA_STOP_INPUT:
-				setMediaMode(subop);
-				_v3MediaRecording = false;
-				break;
-			case SO_HOST_MEDIA_START_RECORDING_2_ARGS:
-			case SO_HOST_MEDIA_START_RECORDING_3_ARGS:
-			case SO_HOST_MEDIA_START_RECORDING_4_ARGS:
-				_v3MediaRecordingArg0 = scriptReadStringIndex(pc);
-				_v3MediaRecordingArg1 = scriptReadWord(pc + 2);
-				pc += 4;
-				_v3MediaRecording = true;
-				if (!_v3SceneMediaModeEnabled)
-					setMediaMode(SO_HOST_MEDIA_START_INPUT);
-
-				if (subop != SO_HOST_MEDIA_START_RECORDING_2_ARGS) {
-					_v3MediaRecordingArg2 = scriptReadStringIndex(pc);
-					pc += 2;
-				}
+		case SO_CONFIG_SET_LANGUAGE_DATA_SUBDIRECTORY:
+			if (value < _stringTable.size())
+				_stringTable[value] = languageSetDataSubdirectory(key);
 
-				if (subop == SO_HOST_MEDIA_START_RECORDING_4_ARGS) {
-					_v3MediaRecordingArg3 = scriptReadStringIndex(pc);
-					pc += 2;
-				}
+			break;
+		default:
+			error("Unknown script opcode 0x34 subopcode 0x%02X near script PC 0x%08X", subop, pc);
+		}
 
-				break;
-			default:
-				error("Unknown script opcode 0x36 subopcode 0x%02X at script PC 0x%08X", subop, pc - 2);
-			}
+		return kScriptContinue;
+	}
 
+	case O_MOUSE_SET_ACTOR: {
+		uint32 opcodePc = pc - 1;
+		byte subop = 0;
+		Actor *mouseActor = nullptr;
+		pc = scriptReadArgs(pc, _currentActor, "CO", &subop, &mouseActor);
+		switch (subop) {
+		case SO_MOUSE_SET_ACTOR:
+			mouseSetActor(mouseActor);
 			break;
-		}
-		default:
+		case SO_MOUSE_CLEAR_ACTOR:
+			mouseSetActor(nullptr);
 			break;
+		default:
+			error("Unknown script opcode 0x35 subopcode 0x%02X at script PC 0x%08X", subop, opcodePc);
 		}
 
 		return kScriptContinue;
 	}
 
-	case O_ANIMATION_AUDIO_CONTROL:
-	case O_PRELOAD_SPRITE_CONV_RANGE:
-		if (_engineVersion != 3)
-			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
-	{
-		switch (opcode) {
-		case O_ANIMATION_AUDIO_CONTROL: {
-			byte subop = scriptReadByte(pc++);
-			if (subop < SO_ANIMATION_INDEX_OFFSET || subop > SO_MIXER_VOLUME)
-				error("Unknown script opcode 0x46 subopcode 0x%02X at script PC 0x%08X", subop, pc - 2);
-
-			switch (subop) {
-			case SO_ANIMATION_INDEX_OFFSET:
-				_v3AnimIndexOffset = scriptReadStringIndex(pc);
-				pc += 2;
-				break;
-			case SO_WAVE_BALANCE:
-				setWaveBalancePercent(scriptReadStringIndex(pc));
-				pc += 2;
-				break;
-			case SO_ANIMATION_ACTOR_SCENE:
-				_v3AnimActorSceneHandle = scriptReadWord(pc);
-				pc += 2;
-				break;
-			case SO_WAVE_LEFT:
-				setWaveLeftPercent(scriptReadStringIndex(pc));
-				pc += 2;
-				break;
-			case SO_WAVE_RIGHT:
-				setWaveRightPercent(scriptReadStringIndex(pc));
-				pc += 2;
-				break;
-			case SO_ANIMATION_AUDIO_NOOP:
-				break;
-			case SO_HOST_MEDIA_RANGE:
-				setMediaRangePercent(scriptReadStringIndex(pc));
+	case O_HOST_MEDIA_CONTROL: {
+		byte subop = scriptReadByte(pc++);
+		switch (subop) {
+		case SO_HOST_MEDIA_START_INPUT:
+			setMediaMode(subop);
+			break;
+		case SO_HOST_MEDIA_STOP_INPUT:
+			setMediaMode(subop);
+			_v3MediaRecording = false;
+			break;
+		case SO_HOST_MEDIA_START_RECORDING_2_ARGS:
+		case SO_HOST_MEDIA_START_RECORDING_3_ARGS:
+		case SO_HOST_MEDIA_START_RECORDING_4_ARGS:
+			_v3MediaRecordingArg0 = scriptReadStringIndex(pc);
+			_v3MediaRecordingArg1 = scriptReadWord(pc + 2);
+			pc += 4;
+			_v3MediaRecording = true;
+			if (!_v3SceneMediaModeEnabled)
+				setMediaMode(SO_HOST_MEDIA_START_INPUT);
+
+			if (subop != SO_HOST_MEDIA_START_RECORDING_2_ARGS) {
+				_v3MediaRecordingArg2 = scriptReadStringIndex(pc);
 				pc += 2;
-				break;
-			case SO_MIXER_VOLUME:
-				setMixerVolumePercent(scriptReadStringIndex(pc));
+			}
+
+			if (subop == SO_HOST_MEDIA_START_RECORDING_4_ARGS) {
+				_v3MediaRecordingArg3 = scriptReadStringIndex(pc);
 				pc += 2;
-				break;
-			default:
-				break;
 			}
 
 			break;
+		default:
+			error("Unknown script opcode 0x36 subopcode 0x%02X at script PC 0x%08X", subop, pc - 2);
 		}
-		case O_PRELOAD_SPRITE_CONV_RANGE: {
-			uint16 first = scriptReadStringIndex(pc);
-			uint16 last = scriptReadStringIndex(pc + 2);
-			pc += 4;
-			for (uint16 spriteId = first; (int16)spriteId <= (int16)last; spriteId++)
-				spriteGetConvPtr((int16)spriteId);
 
+		return kScriptContinue;
+	}
+
+	case O_ANIMATION_AUDIO_CONTROL: {
+		if (_engineVersion != 3)
+			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
+
+		byte subop = scriptReadByte(pc++);
+		if (subop < SO_ANIMATION_INDEX_OFFSET || subop > SO_MIXER_VOLUME)
+			error("Unknown script opcode 0x46 subopcode 0x%02X at script PC 0x%08X", subop, pc - 2);
+
+		switch (subop) {
+		case SO_ANIMATION_INDEX_OFFSET:
+			_v3AnimIndexOffset = scriptReadStringIndex(pc);
+			pc += 2;
+			break;
+		case SO_WAVE_BALANCE:
+			setWaveBalancePercent(scriptReadStringIndex(pc));
+			pc += 2;
+			break;
+		case SO_ANIMATION_ACTOR_SCENE:
+			_v3AnimActorSceneHandle = scriptReadWord(pc);
+			pc += 2;
+			break;
+		case SO_WAVE_LEFT:
+			setWaveLeftPercent(scriptReadStringIndex(pc));
+			pc += 2;
+			break;
+		case SO_WAVE_RIGHT:
+			setWaveRightPercent(scriptReadStringIndex(pc));
+			pc += 2;
+			break;
+		case SO_ANIMATION_AUDIO_NOOP:
+			break;
+		case SO_HOST_MEDIA_RANGE:
+			setMediaRangePercent(scriptReadStringIndex(pc));
+			pc += 2;
+			break;
+		case SO_MIXER_VOLUME:
+			setMixerVolumePercent(scriptReadStringIndex(pc));
+			pc += 2;
 			break;
-		}
 		default:
 			break;
 		}
@@ -1039,6 +1012,19 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		return kScriptContinue;
 	}
 
+	case O_PRELOAD_SPRITE_CONV_RANGE: {
+		if (_engineVersion != 3)
+			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
+
+		uint16 first = scriptReadStringIndex(pc);
+		uint16 last = scriptReadStringIndex(pc + 2);
+		pc += 4;
+		for (uint16 spriteId = first; (int16)spriteId <= (int16)last; spriteId++)
+			spriteGetConvPtr((int16)spriteId);
+
+		return kScriptContinue;
+	}
+
 	case O_STRING_TABLE_COMPARE_SET_KEY: {
 		uint16 lhsIndex = scriptReadWord(pc);
 		uint16 rhsIndex = scriptReadWord(pc + 2);
@@ -1129,10 +1115,10 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	}
 
 	case O_JUMP_IF_KEY_CLEAR_V3:
-	case O_JUMP_IF_KEY_SET_V3:
+	case O_JUMP_IF_KEY_SET_V3: {
 		if (_engineVersion != 3)
 			error("Unknown script opcode 0x%02X at script PC 0x%08X", opcode, pc - 1);
-	{
+
 		uint16 key = scriptReadWord(pc);
 		uint32 targetPc = scriptReadDword(pc + 2);
 		bool jumpWhenSet = opcode == O_JUMP_IF_KEY_SET_V3;
@@ -1351,5 +1337,4 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptStep(Actor &actor, uint32 &
 	return status;
 }
 
-
 } // End of namespace Comfy


Commit: 8d15a1b34cefed7ed9c5a76179793e6061ddd2e5
    https://github.com/scummvm/scummvm/commit/8d15a1b34cefed7ed9c5a76179793e6061ddd2e5
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Formatting clean-up pass

The last one, hopefully...

Changed paths:
    engines/comfy/actor.cpp
    engines/comfy/anim_file.cpp
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/debug.cpp
    engines/comfy/detection_tables.h
    engines/comfy/expr.cpp
    engines/comfy/game.cpp
    engines/comfy/input.cpp
    engines/comfy/keybits.cpp
    engines/comfy/midi.cpp
    engines/comfy/midiplyr.cpp
    engines/comfy/object_file.cpp
    engines/comfy/palette.cpp
    engines/comfy/scene.cpp
    engines/comfy/script_vm.cpp
    engines/comfy/sound.cpp
    engines/comfy/video.cpp


diff --git a/engines/comfy/actor.cpp b/engines/comfy/actor.cpp
index ce5fa5c4a83..a8b3da1261a 100644
--- a/engines/comfy/actor.cpp
+++ b/engines/comfy/actor.cpp
@@ -29,6 +29,7 @@ bool ComfyEngine::spriteDecompressTile(SpriteResource &sprite, const byte *sourc
 	uint32 outputSize = sprite.header.tiledSize;
 	_spriteDecompressLastSize = 0;
 	_spriteDecompressLastComplete = false;
+
 	if (!source || !sourceSize || !sprite.header.width || !sprite.header.height || !outputSize)
 		return false;
 
@@ -64,6 +65,7 @@ bool ComfyEngine::spriteDecompressTile(SpriteResource &sprite, const byte *sourc
 		while (pixelsLeft) {
 			if (!skipCount && !fillCount && !literalCount) {
 				byte op = sourcePos < sourceEnd ? source[sourcePos++] : 0;
+
 				if (op & 0x40) {
 					skipCount = op - 0x40;
 
@@ -126,6 +128,7 @@ bool ComfyEngine::spriteDecompressTile(SpriteResource &sprite, const byte *sourc
 				uint16 count = MIN<uint16>(pixelsLeft, fillCount);
 				count = MIN<uint16>(count, 0x3F);
 				fillCount -= count;
+
 				if (count < 8) {
 					literalCount = count;
 					literalFromFill = true;
@@ -218,6 +221,7 @@ void ComfyEngine::scenePoolEvict() {
 	byte *entry = &_scenePoolData[_scenePoolEvictCursor];
 	int16 id = (int16)READ_LE_UINT16(entry);
 	uint16 slotSize = READ_LE_UINT16(entry + 2);
+
 	if (id > 0) {
 		if ((uint16)id < _spriteResources.size())
 			spriteInvalidateHostCache(_spriteResources[id]);
@@ -234,8 +238,7 @@ void ComfyEngine::scenePoolEvict() {
 	}
 
 	_scenePoolEvictCursor += slotSize;
-	if (_scenePoolEvictCursor < _scenePoolData.size() &&
-			READ_LE_UINT16(&_scenePoolData[_scenePoolEvictCursor]) == 0x8000)
+	if (_scenePoolEvictCursor < _scenePoolData.size() && READ_LE_UINT16(&_scenePoolData[_scenePoolEvictCursor]) == 0x8000)
 		_scenePoolEvictCursor = 0;
 }
 
@@ -347,6 +350,7 @@ void ComfyEngine::spriteCache(int16 spriteId) {
 	uint16 payloadSize = sprite.pixels.size() + (sprite.pixels.size() & 1);
 	uint16 slotSize = payloadSize + 0x0C;
 	scenePoolReserveSlot((uint32)slotSize + 2);
+
 	if (_scenePoolCursor > _scenePoolData.size() || slotSize > _scenePoolData.size() - _scenePoolCursor)
 		return;
 
@@ -390,8 +394,7 @@ ComfyEngine::SpriteResource *ComfyEngine::spriteLookup(uint16 spriteId, int16 x,
 	int16 right = left + (int16)sprite.header.width - 1;
 	int16 bottom = top + (int16)sprite.header.height - 1;
 	bool fullscreen = sprite.header.width == _logicalScreenWidth && sprite.header.height == _logicalScreenHeight;
-	bool offscreen = left > (int16)(_logicalScreenWidth - 1) || right < 0 ||
-		top > (int16)(_logicalScreenHeight - 1) || bottom < 0;
+	bool offscreen = left > (int16)(_logicalScreenWidth - 1) || right < 0 || top > (int16)(_logicalScreenHeight - 1) || bottom < 0;
 
 	if (entry && entry->slotSize == 0xFFFF && !fullscreen && offscreen) {
 		_objFileOffset = _spriteLastHeader.fileOffset;
@@ -428,7 +431,7 @@ ComfyEngine::SpriteResource *ComfyEngine::spriteGetPtr(int16 spriteId) {
 
 	uint16 frameId = (uint16)-spriteId;
 	if (frameId >= _frameCacheEntries.size() || _frameCacheEntries[frameId].slotSize == 0xFFFF ||
-			!_frameSpriteResource.loaded || _frameSpriteResource.id != frameId)
+		!_frameSpriteResource.loaded || _frameSpriteResource.id != frameId)
 		spriteCache(spriteId);
 
 	return _frameSpriteResource.loaded && _frameSpriteResource.id == frameId ? &_frameSpriteResource : nullptr;
@@ -446,6 +449,7 @@ void ComfyEngine::spriteGetConvPtr(int16 spriteId) {
 	SpriteCacheEntry &entry = _objectCacheEntries[spriteId];
 	byte *payload = nullptr;
 	uint16 width = 0;
+
 	if (entry.slotSize != 0xFFFF) {
 		if (entry.poolOffset <= _scenePoolData.size() && entry.slotSize >= 0x0C && 0x0C <= _scenePoolData.size() - entry.poolOffset) {
 			byte *entryData = &_scenePoolData[entry.poolOffset];
@@ -1105,6 +1109,7 @@ bool ComfyEngine::actorRunScript(uint16 actorIndex, bool &descendChildren) {
 		actor->yFixed = (int32)((uint32)actor->yFixed + (uint32)stepDy);
 		actor->moveDx = moveDx - stepDx;
 		actor->moveDy = moveDy - stepDy;
+
 		moveTicks -= stepTicks;
 		if (moveTicks < 0)
 			moveTicks = 0;
@@ -1174,6 +1179,7 @@ bool ComfyEngine::actorTickTree(uint16 actorIndex) {
 	while (child) {
 		Actor *childActor = actorGetPtr(child);
 		uint16 savedNext = childActor ? childActor->nextLink : 0;
+
 		if (actorTickTree(child)) {
 			child = savedNext;
 		} else {
@@ -1257,6 +1263,7 @@ void ComfyEngine::renderFlushDrawCommands() {
 
 			bool coversMouse = animFrameCoversPoint(command.x, command.y, _mouseX, _mouseY);
 			animFrameBlitAt(command.x, command.y);
+
 			if (_engineVersion == 3 && command.actorIndex) {
 				Actor *actor = actorGetPtr(command.actorIndex);
 				if (actor)
@@ -1272,6 +1279,7 @@ void ComfyEngine::renderFlushDrawCommands() {
 
 		bool coversMouse = spriteCoversPoint((int16)command.selector, command.x, command.y, _mouseX, _mouseY);
 		spriteBlitClipped((int16)command.selector, command.x, command.y);
+
 		if (_engineVersion == 3 && command.actorIndex) {
 			Actor *actor = actorGetPtr(command.actorIndex);
 			if (actor)
@@ -1552,6 +1560,7 @@ bool ComfyEngine::actorDrawLegacyInternal(uint16 actorIndex, int16 x, int16 y) {
 			if (spriteId) {
 				int16 spriteX = drawX + dx;
 				int16 spriteY = drawY + dy;
+
 				SpriteResource *sprite = spriteLookup(spriteId, spriteX, spriteY);
 				if (sprite)
 					spriteBlitClipped((int16)spriteId, spriteX - sprite->header.hotspotX,
@@ -1951,5 +1960,4 @@ void ComfyEngine::actorDrawInternal(uint16 actorIndex, int16 x, int16 y, bool vi
 	actorDrawList(actor->childHead, drawX, drawY, visible);
 }
 
-
 } // End of namespace Comfy
diff --git a/engines/comfy/anim_file.cpp b/engines/comfy/anim_file.cpp
index 9b19e3610ea..9afd926ed1c 100644
--- a/engines/comfy/anim_file.cpp
+++ b/engines/comfy/anim_file.cpp
@@ -28,10 +28,10 @@
 namespace Comfy {
 
 enum AnimFileCommand {
-	kAnimCommandEnd = 0x2145,
+	kAnimCommandEnd             = 0x2145,
 	kAnimCommandStoreFrameBytes = 0x4356,
-	kAnimCommandDirtyRect = 0x5842,
-	kAnimCommandFrame = 0x5246
+	kAnimCommandDirtyRect       = 0x5842,
+	kAnimCommandFrame           = 0x5246
 };
 
 bool ComfyEngine::animFrameIsActive() {
@@ -73,8 +73,7 @@ void ComfyEngine::animFrameSetVocCounter(uint32 counter) {
 }
 
 bool ComfyEngine::animFileOpen() {
-	if (!readAssetFile(Common::Path("ANMFILE.DAT"), _animFileData) ||
-			_animFileData.size() < COMFY_ANMFILE_HEADER_BYTES)
+	if (!readAssetFile(Common::Path("ANMFILE.DAT"), _animFileData) || _animFileData.size() < COMFY_ANMFILE_HEADER_BYTES)
 		return false;
 
 	uint16 magic = READ_LE_UINT16(&_animFileData[0]);
@@ -94,6 +93,7 @@ bool ComfyEngine::animFileOpen() {
 	_animIndexLoaded = true;
 	_animActive = false;
 	_animUsesWaveVocCounter = false;
+
 	return true;
 }
 
diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 2feb7b9b68b..3e3f6242f1b 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -40,14 +40,13 @@ namespace Comfy {
 ComfyEngine *g_engine;
 
 void ComfyEngine::configRunPendingCommand() {
-	if (!_v3ConfigCommandPending)
+	if (!_configCommandPending)
 		return;
 
-	_v3ConfigCommandPending = false;
+	_configCommandPending = false;
 
-	// The original starts the stored command with WinExec or ShellExecute, which has no engine-side equivalent.
 	warning("configRunPendingCommand reached, this is probably a dev path! Values: command=%u value=%u text=%s",
-		_v3ConfigCommandSubop, _v3ConfigCommandValue, _v3ConfigCommandText.c_str());
+		_configCommandSubop, _configCommandValue, _configCommandText.c_str());
 }
 
 #ifdef USE_IMGUI
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index ca2b337b663..ee2f06672d6 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -716,31 +716,31 @@ private:
 	uint16 _mouseCursorSpriteId = 0;
 	uint16 _mouseFlags = 0;
 	bool _waveOutputActive = false;
-	byte _v3SceneWaveBalancePercent = 0;
-	byte _v3SceneMediaModeEnabled = 0;
-	byte _v3SceneWaveLeftPercent = 0;
-	byte _v3SceneWaveRightPercent = 0;
-	byte _v3SceneMixerVolumePercent = 0;
+	byte _sceneWaveBalancePercent = 0;
+	byte _sceneMediaModeEnabled = 0;
+	byte _sceneWaveLeftPercent = 0;
+	byte _sceneWaveRightPercent = 0;
+	byte _sceneMixerVolumePercent = 0;
 	bool _v3MediaValueAvailable = false;
 	uint16 _v3MediaValue = 0;
 	uint16 _v3MediaProgress = 0;
-	uint16 _v3Sensitivity = 0;
-	bool _v3ConfigCommandPending = false;
-	byte _v3ConfigCommandSubop = 0;
-	uint16 _v3ConfigCommandValue = 0;
-	Common::String _v3ConfigCommandText;
-	bool _v3MediaRecording = false;
-	uint16 _v3MediaRecordingArg0 = 0;
-	uint16 _v3MediaRecordingArg1 = 0;
-	uint16 _v3MediaRecordingArg2 = 0;
-	uint16 _v3MediaRecordingArg3 = 0;
-	uint16 _v3AnimIndexOffset = 0;
-	uint16 _v3AnimActorSceneHandle = 0;
-	uint16 _v3WaveBalancePercent = 0;
-	uint16 _v3WaveLeftPercent = 0;
-	uint16 _v3WaveRightPercent = 0;
-	uint16 _v3MixerVolumePercent = 0;
-	uint16 _v3MixerAltPercent = 0;
+	uint16 _sensitivity = 0;
+	bool _configCommandPending = false;
+	byte _configCommandSubop = 0;
+	uint16 _configCommandValue = 0;
+	Common::String _configCommandText;
+	bool _mediaRecording = false;
+	uint16 _mediaRecordingArg0 = 0;
+	uint16 _mediaRecordingArg1 = 0;
+	uint16 _mediaRecordingArg2 = 0;
+	uint16 _mediaRecordingArg3 = 0;
+	uint16 _animIndexOffset = 0;
+	uint16 _animActorSceneHandle = 0;
+	uint16 _waveBalancePercent = 0;
+	uint16 _waveLeftPercent = 0;
+	uint16 _waveRightPercent = 0;
+	uint16 _mixerVolumePercent = 0;
+	uint16 _mixerAltPercent = 0;
 	bool _actorDestroyedCurrent = false;
 	uint16 _lastKey = 0xFFFF;
 	VocQueueEntry _vocQueue[COMFY_VOC_QUEUE_CAPACITY];
@@ -961,10 +961,8 @@ private:
 	void selPoolFree();
 	bool assetsLoad(uint32 budget, byte *scenePtr);
 	void assetsUnload(byte freeAudio);
-	bool sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount,
-		uint16 scriptVariableCount, uint32 &numSprites);
-	bool sceneFrameInitTables(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount,
-		uint16 scriptVariableCount, uint32 &numSprites);
+	bool sceneLoadAndInit(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount, uint16 scriptVariableCount, uint32 &numSprites);
+	bool sceneFrameInitTables(uint16 sceneCount, uint16 actorCount, uint16 keyBitCount, uint16 scriptVariableCount, uint32 &numSprites);
 	void midiShutdown();
 	void midiFileGetEntryTableParams(uint16 *entryCount, uint16 *entrySize);
 	void midiFileReadEntries(byte *destination);
@@ -1025,8 +1023,7 @@ private:
 	void actorClearDirtyTree(uint16 actorIndex);
 	void actorSetAllVisible();
 	void actorClearFirstAnimFrameSelector();
-	uint16 actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible, byte active,
-		uint32 pc, int16 x, int16 y, int16 sprite, byte insertAsChild);
+	uint16 actorInit(uint16 sceneSlot, uint16 parentSlot, byte visible, byte active, uint32 pc, int16 x, int16 y, int16 sprite, byte insertAsChild);
 	bool actorRunScript(uint16 actorIndex, bool &descendChildren);
 	bool actorTickTree(uint16 actorIndex);
 	bool actorDraw(uint16 actorIndex, int16 x, int16 y);
@@ -1037,8 +1034,7 @@ private:
 	void renderQueueDrawCommand(int16 x, int16 y, uint32 selector, byte mode, uint16 actorIndex);
 	void renderFlushDrawCommands();
 	void renderFlushCachedDirtyRects();
-	uint16 scriptEvalKeyMask(uint32 pc, uint16 mode, ComfyRect &maskRecord,
-		ComfyRect *rects, int16 baseX, int16 baseY);
+	uint16 scriptEvalKeyMask(uint32 pc, uint16 mode, ComfyRect &maskRecord, ComfyRect *rects, int16 baseX, int16 baseY);
 	void actorEvalFrameSelection(uint16 actorIndex, int16 x, int16 y);
 	void timerInit();
 	void timerShutdown();
@@ -1096,8 +1092,7 @@ private:
 	void midiAddEvent(uint16 id, int16 delta);
 	void midiAddTrack(uint16 id, int16 delta);
 	void midiRemoveTrack(uint16 id);
-	void midiAddTrackEntry(uint16 channel, uint16 songId, uint16 completionKey, byte loadFlag,
-		uint16 frameCount, uint16 *frames);
+	void midiAddTrackEntry(uint16 channel, uint16 songId, uint16 completionKey, byte loadFlag, uint16 frameCount, uint16 *frames);
 	void midiClearLoadedSong(uint16 channel);
 	void midiFireClearMarker(uint16 channel, int16 marker);
 	void midiPollSceneEntries();
diff --git a/engines/comfy/debug.cpp b/engines/comfy/debug.cpp
index 603518861ad..be0947c1492 100644
--- a/engines/comfy/debug.cpp
+++ b/engines/comfy/debug.cpp
@@ -44,8 +44,7 @@ static void debugIncludeMapRect(int16 &mapLeft, int16 &mapTop, int16 &mapRight,
 }
 
 static ImVec2 debugMapPointToCanvas(const ImVec2 &canvasPos, int16 mapLeft, int16 mapTop, float scale, float margin, int16 x, int16 y) {
-	return ImVec2(canvasPos.x + ((float)x - mapLeft) * scale + margin,
-		canvasPos.y + ((float)y - mapTop) * scale + margin);
+	return ImVec2(canvasPos.x + ((float)x - mapLeft) * scale + margin, canvasPos.y + ((float)y - mapTop) * scale + margin);
 }
 
 bool ComfyEngine::debugScriptHasRange(uint32 pc, uint32 width) {
@@ -136,6 +135,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 				int16 dy = debugScriptReadWord(pc + 4);
 				pc += 6;
 				wordsLeft -= 3;
+
 				uint16 spriteId = rawSpriteId;
 				if (spriteId & 0x8000) {
 					if (!debugScriptHasRange(pc, 4))
@@ -238,8 +238,8 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 				int16 dy = debugScriptReadWord(pc + 4);
 				pc += 6;
 				wordsLeft -= 3;
-				uint16 spriteId = rawSpriteId;
 
+				uint16 spriteId = rawSpriteId;
 				if (spriteId & 0x8000) {
 					if (!debugScriptHasRange(pc, 4))
 						break;
@@ -323,6 +323,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 			uint childCount = 0;
 			uint16 child = actor.childHead;
 			uint guard = 0;
+
 			while (child && child < _actors.size() && child < COMFY_ACTOR_COUNT && childCount < COMFY_ACTOR_COUNT && guard++ < COMFY_ACTOR_COUNT) {
 				if (!visited[child]) {
 					children[childCount] = child;
@@ -409,7 +410,7 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 			}
 		}
 	} else if (ImGui::BeginTable("comfy_actor_table", 10, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg |
-			ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY | ImGuiTableFlags_ScrollX, ImVec2(0, 0))) {
+			   ImGuiTableFlags_Resizable | ImGuiTableFlags_ScrollY | ImGuiTableFlags_ScrollX, ImVec2(0, 0))) {
 		ImGui::TableSetupColumn("#", ImGuiTableColumnFlags_WidthFixed, 32.0F);
 		ImGui::TableSetupColumn("Scene", ImGuiTableColumnFlags_WidthFixed, 48.0F);
 		ImGui::TableSetupColumn("Parent", ImGuiTableColumnFlags_WidthFixed, 52.0F);
@@ -546,7 +547,6 @@ void ComfyEngine::drawActorDebugUi(bool *visible) {
 	ImGui::End();
 }
 
-
 #endif
 
 } // End of namespace Comfy
diff --git a/engines/comfy/detection_tables.h b/engines/comfy/detection_tables.h
index 124af7ec206..325db2226cb 100644
--- a/engines/comfy/detection_tables.h
+++ b/engines/comfy/detection_tables.h
@@ -45,8 +45,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
-			GAMEOPTION_USE_IMGUI_KEYBOARD)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		1
 	},
@@ -63,8 +62,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
-			GAMEOPTION_USE_IMGUI_KEYBOARD)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		3
 	},
@@ -79,8 +77,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
-			GAMEOPTION_USE_IMGUI_KEYBOARD)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		1
 	},
@@ -95,8 +92,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
-			GAMEOPTION_USE_IMGUI_KEYBOARD)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		2
 	},
@@ -110,8 +106,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
-			GAMEOPTION_USE_IMGUI_KEYBOARD)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		2
 	},
@@ -125,8 +120,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
-			GAMEOPTION_USE_IMGUI_KEYBOARD)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		1
 	},
@@ -140,8 +134,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
-			GAMEOPTION_USE_IMGUI_KEYBOARD)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		2
 	},
@@ -156,8 +149,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
-			GAMEOPTION_USE_IMGUI_KEYBOARD)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		3
 	},
@@ -172,8 +164,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
-			GAMEOPTION_USE_IMGUI_KEYBOARD)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		3
 	},
@@ -188,8 +179,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO,
-			GAMEOPTION_USE_IMGUI_KEYBOARD)
+		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
 		},
 		3
 	},
diff --git a/engines/comfy/expr.cpp b/engines/comfy/expr.cpp
index e58f3fcf036..7dac5764cb3 100644
--- a/engines/comfy/expr.cpp
+++ b/engines/comfy/expr.cpp
@@ -23,34 +23,36 @@
 
 namespace Comfy {
 
-#define EO_PUSH_LITERAL_01 0x01
-#define EO_PUSH_STRING_TABLE_VALUE 0x02
-#define EO_PUSH_LITERAL_03 0x03
-#define EO_ADD 0x08
-#define EO_SUBTRACT 0x09
-#define EO_MULTIPLY 0x0A
-#define EO_DIVIDE 0x0B
+// EXPRESSION OPS
+
+#define EO_PUSH_LITERAL_01            0x01
+#define EO_PUSH_STRING_TABLE_VALUE    0x02
+#define EO_PUSH_LITERAL_03            0x03
+#define EO_ADD                        0x08
+#define EO_SUBTRACT                   0x09
+#define EO_MULTIPLY                   0x0A
+#define EO_DIVIDE                     0x0B
 #define EO_INDEXED_STRING_TABLE_VALUE 0x0C
-#define EO_END 0x0D
-#define EO_MODULO 0x0E
-#define EO_ACTOR_LOCAL_X 0x10
-#define EO_ACTOR_LOCAL_Y 0x11
-#define EO_ACTOR_WORLD_X 0x12
-#define EO_ACTOR_WORLD_Y 0x13
-#define EO_ACTOR_SPRITE_SELECTOR 0x14
-#define EO_PUSH_LITERAL_15 0x15
-#define EO_RANDOMIZE 0x16
-#define EO_MOUSE_X 0x17
-#define EO_MOUSE_Y 0x18
-#define EO_WAVE_BALANCE_PERCENT 0x19
-#define EO_HOST_MEDIA_VALUE 0x1A
-#define EO_NOOP_1B 0x1B
-#define EO_WAVE_LEFT_PERCENT 0x1C
-#define EO_WAVE_RIGHT_PERCENT 0x1D
-#define EO_LOGICAL_DIMENSION 0x1E
-#define EO_NOOP_1F 0x1F
-#define EO_HOST_MEDIA_PROGRESS 0x20
-#define EO_MIXER_VOLUME_PERCENT 0x21
+#define EO_END                        0x0D
+#define EO_MODULO                     0x0E
+#define EO_ACTOR_LOCAL_X              0x10
+#define EO_ACTOR_LOCAL_Y              0x11
+#define EO_ACTOR_WORLD_X              0x12
+#define EO_ACTOR_WORLD_Y              0x13
+#define EO_ACTOR_SPRITE_SELECTOR      0x14
+#define EO_PUSH_LITERAL_15            0x15
+#define EO_RANDOMIZE                  0x16
+#define EO_MOUSE_X                    0x17
+#define EO_MOUSE_Y                    0x18
+#define EO_WAVE_BALANCE_PERCENT       0x19
+#define EO_HOST_MEDIA_VALUE           0x1A
+#define EO_NOOP_1B                    0x1B
+#define EO_WAVE_LEFT_PERCENT          0x1C
+#define EO_WAVE_RIGHT_PERCENT         0x1D
+#define EO_LOGICAL_DIMENSION          0x1E
+#define EO_NOOP_1F                    0x1F
+#define EO_HOST_MEDIA_PROGRESS        0x20
+#define EO_MIXER_VOLUME_PERCENT       0x21
 
 uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 	_exprStackTop = 0;
@@ -177,7 +179,7 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 				break;
 
 			case EO_WAVE_BALANCE_PERCENT:
-				value = _v3SceneWaveBalancePercent;
+				value = _sceneWaveBalancePercent;
 				break;
 
 			case EO_HOST_MEDIA_VALUE:
@@ -189,11 +191,11 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 				break;
 
 			case EO_WAVE_LEFT_PERCENT:
-				value = _v3SceneWaveLeftPercent;
+				value = _sceneWaveLeftPercent;
 				break;
 
 			case EO_WAVE_RIGHT_PERCENT:
-				value = _v3SceneWaveRightPercent;
+				value = _sceneWaveRightPercent;
 				break;
 
 			case EO_LOGICAL_DIMENSION:
@@ -226,7 +228,7 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 				break;
 
 			case EO_MIXER_VOLUME_PERCENT:
-				value = _v3SceneMixerVolumePercent;
+				value = _sceneMixerVolumePercent;
 				break;
 
 			default:
@@ -299,5 +301,4 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 	}
 }
 
-
 } // End of namespace Comfy
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index a7cee09f77e..c78700b6a1f 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -117,11 +117,13 @@ void ComfyEngine::gameConfigInit() {
 void ComfyEngine::findLanguageDirectories() {
 	uint languageCount = 0;
 	_multiLanguage = false;
+
 	for (uint i = 0; i < ARRAYSIZE(_languageDirectories); i++)
 		_languageDirectories[i] = Common::Path();
 
 	Common::FSNode root(ConfMan.getPath("path"));
 	Common::FSNode gameDirectory;
+
 	if (root.getName().equalsIgnoreCase(_gameDirectory.toString())) {
 		gameDirectory = root;
 	} else {
@@ -178,7 +180,7 @@ bool ComfyEngine::iniReadGameConfig() {
 		_inputDeviceMode = 0;
 
 	_inputDevicePreference = _inputDeviceMode;
-	_v3Sensitivity = ConfMan.hasKey("SENSITIVITY") ? ConfMan.getInt("SENSITIVITY") : 0;
+	_sensitivity = ConfMan.hasKey("SENSITIVITY") ? ConfMan.getInt("SENSITIVITY") : 0;
 
 	return !_gameDirectory.empty();
 }
@@ -532,6 +534,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	uint32 objectTableBytes = assetsAlignEven32((uint32)_numObjects * 0x11);
 	uint32 headerTotalBytes = midiHeaderBytes + soundHeaderBytes + objectTableBytes;
 	uint16 headerPages = (uint16)((headerTotalBytes + 0x400) / 0x400);
+
 	int32 headerHandle = memAllocTrackFar(headerPages);
 	if (headerHandle < 0)
 		return false;
@@ -583,6 +586,7 @@ bool ComfyEngine::assetsLoad(uint32 budget, byte *scenePtr) {
 	_scenePoolSize = xmsLimit > budget ? xmsLimit - budget : 0;
 	_scenePoolSize &= 0xFFFFFFFE;
 	_scenePoolData.resize(_scenePoolSize);
+
 	if (_scenePoolSize)
 		memset(&_scenePoolData[0], 0, _scenePoolSize);
 
diff --git a/engines/comfy/input.cpp b/engines/comfy/input.cpp
index be3af251d78..cdb2130a42e 100644
--- a/engines/comfy/input.cpp
+++ b/engines/comfy/input.cpp
@@ -251,8 +251,7 @@ uint32 ComfyEngine::lptKeyboardScan() {
 
 		if (_keyboardActiveMask & 0x02) {
 			uint32 timeCounter = _midiPlyrDriver ? _midiPlyrDriver->getTimeCounter() : _midiTimeCounter;
-			if (!_inputKeyboardPulseLatched && (_keyboardLatchedMask & 0x02) &&
-					timeCounter - _inputKeyboardPulseTime < 0x64)
+			if (!_inputKeyboardPulseLatched && (_keyboardLatchedMask & 0x02) && timeCounter - _inputKeyboardPulseTime < 0x64)
 				_inputKeyboardPulseTicks = 6;
 		}
 
@@ -313,7 +312,7 @@ uint32 ComfyEngine::lptKeyboardScan() {
 	} else if (_engineVersion == 3 && _inputDeviceMode == 2) {
 		scanState = keyboardState | (_inputKeyboardBit7Held ? 0x80 : 0);
 	} else if (_engineVersion == 3 && (_inputDeviceMode == 3 || _inputDeviceMode == 4)) {
-		// Modes 3 and 4 originally used WinMM MIDI input, we route those signalsthrough the keymapper/UI...
+		// Modes 3 and 4 originally used WinMM MIDI input, we route those signals through the keymapper/UI...
 		scanState = (_toyKeyboardActiveMask | _toyKeyboardHoldMask | _toyKeyboardLatchedMask | _keymapperActiveMask | _keymapperLatchedMask) & 0x00FFFFFF;
 
 		if (_inputDeviceMode == 4) {
@@ -374,6 +373,7 @@ uint16 ComfyEngine::inputDetectDevice(uint32 comfyboardState, uint32 keyboardSta
 	_inputPreviousKeyboardState = filteredKeyboardState;
 	uint32 comfyboardPressed = (filteredComfyboardState ^ previousComfyboardState) & filteredComfyboardState;
 	uint32 keyboardPressed = (filteredKeyboardState ^ previousKeyboardState) & filteredKeyboardState;
+
 	if (!_inputKeyboardActivityCount && (keyboardPressed & 0x80) && !(comfyboardState & 0x80))
 		return 2;
 
diff --git a/engines/comfy/keybits.cpp b/engines/comfy/keybits.cpp
index 5d5078ab2c3..ae8b7d4dcfb 100644
--- a/engines/comfy/keybits.cpp
+++ b/engines/comfy/keybits.cpp
@@ -74,5 +74,4 @@ void ComfyEngine::keyBitClear(uint16 bitIndex) {
 	_keyBits[byteIndex] &= ~(1 << (bitIndex & 7));
 }
 
-
 } // End of namespace Comfy
diff --git a/engines/comfy/midi.cpp b/engines/comfy/midi.cpp
index 82471df351d..60c468444ca 100644
--- a/engines/comfy/midi.cpp
+++ b/engines/comfy/midi.cpp
@@ -234,9 +234,9 @@ void ComfyEngine::midiInitChannels() {
 		_midiChannels[channel] = MidiChannelState();
 
 		MidiChannelState &state = _midiChannels[channel];
-		state.volumeCurrent = state.volumeDefault = 0x6400;
-		state.rateCurrent = state.rateDefault = 0x07D0;
-		state.pitchCurrent = state.pitchDefault = 0x1388;
+		state.volumeCurrent = state.volumeDefault = 25600;
+		state.rateCurrent = state.rateDefault = 2000;
+		state.pitchCurrent = state.pitchDefault = 5000;
 
 		if (_engineVersion != 3) {
 			state.volumeTarget = state.volumeDefault;
@@ -262,6 +262,7 @@ void ComfyEngine::midiQueueAdd(MidiQueue &queue, uint16 id, int16 delta) {
 	queue.entries[queue.count].id = id;
 	queue.entries[queue.count].time = queue.baseTime + delta;
 	queue.count++;
+
 	midiFindNext(queue);
 }
 
@@ -346,12 +347,11 @@ void ComfyEngine::midiStartChannel(uint16 channel) {
 	}
 
 	uint16 size = state.loadedFrameSize;
-	state.rateCurrent = state.rateDefault = size >= 4 ? READ_LE_UINT16(song + 2) : 0x07D0;
+	state.rateCurrent = state.rateDefault = size >= 4 ? READ_LE_UINT16(song + 2) : 2000;
 	state.rateTicksLeft = 0;
 	_midiPlyrDriver->musicPlaySong(song, size, channel);
 }
 
-
 void ComfyEngine::midiRestartChannels() {
 	for (uint channel = 0; channel < COMFY_MIDI_CHANNEL_COUNT; channel++)
 		midiClearLoadedSong(channel);
@@ -423,7 +423,7 @@ void ComfyEngine::midiStopAndFireKeys(uint16 channel) {
 
 	midiClearLoadedSong(channel);
 	for (uint i = 0; i < state.entryCount; i++) {
-		// The original tests every entry but always fires the first entry's key.
+		// The original tests every entry but always fires the first entry's key...
 		if (state.entries[i].completionKey)
 			keyBitSet(firstKey);
 	}
diff --git a/engines/comfy/midiplyr.cpp b/engines/comfy/midiplyr.cpp
index 6756d52156a..037300f8c36 100644
--- a/engines/comfy/midiplyr.cpp
+++ b/engines/comfy/midiplyr.cpp
@@ -202,6 +202,7 @@ void MidiPlyrDriver::timeCallbackInternal() {
 	}
 
 	_seqCurrentTick += 100;
+
 	if (_sendDirectGuard == 0) {
 		_sendDirectGuard = 1;
 		sequencerTick();
@@ -616,6 +617,7 @@ void MidiPlyrDriver::sequencerParseEvent(uint16 trackIndex) {
 	case 0xF0: {
 		byte event = streamReadByte(track);
 		byte skipCount = 0;
+
 		switch (event) {
 		case 0x2F:
 			skipCount = streamReadByte(track);
@@ -668,9 +670,7 @@ void MidiPlyrDriver::trackAdvance(uint16 trackIndex) {
 		return;
 
 	Track &track = _tracks[trackIndex];
-	while (!track.streamFault && track.state && track.eventCursor < track.eventDataSize &&
-	       track.startTick <= _seqCurrentTick) {
-
+	while (!track.streamFault && track.state && track.eventCursor < track.eventDataSize &&  track.startTick <= _seqCurrentTick) {
 		sequencerParseEvent(trackIndex);
 
 		if (track.streamFault) {
diff --git a/engines/comfy/object_file.cpp b/engines/comfy/object_file.cpp
index df21a83c9bc..4e9d3d50dd1 100644
--- a/engines/comfy/object_file.cpp
+++ b/engines/comfy/object_file.cpp
@@ -404,6 +404,7 @@ byte *ComfyEngine::objFileReadTiledCore(uint32 sourceOffset, uint32 byteCount, O
 	if (missing) {
 		uint16 readRow = (uint16)(lastRow - missing + 1);
 		objFileReadRow(objectFile->readBuffer, readRow, missing, blockSize, objectFile);
+
 		for (uint16 i = missing; i != 0; i--) {
 			uint16 tileId = (uint16)(lastRow - i + 1);
 			uint16 bufferRow = (uint16)(missing - i);
diff --git a/engines/comfy/palette.cpp b/engines/comfy/palette.cpp
index daba62fead9..0f8673b210a 100644
--- a/engines/comfy/palette.cpp
+++ b/engines/comfy/palette.cpp
@@ -68,6 +68,7 @@ void ComfyEngine::paletteInterpolate(uint16 step, uint16 maximum) {
 		return;
 
 	int16 remaining = (int16)(maximum - step);
+
 	for (uint i = 0; i < COMFY_PALETTE_BYTES; i++) {
 		int32 from = _paletteFadeSource[i];
 		int32 to = _paletteTarget[i];
diff --git a/engines/comfy/scene.cpp b/engines/comfy/scene.cpp
index 6d6c2e40f8b..e56590525f7 100644
--- a/engines/comfy/scene.cpp
+++ b/engines/comfy/scene.cpp
@@ -54,11 +54,11 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 
 	if (_engineVersion == 3) {
 		byte *vocState = &_sceneMemoryBlock[_sceneMidiInstanceOffset + COMFY_SCENE_MIDI_INSTANCE_BYTES];
-		vocState[0] = _v3SceneWaveBalancePercent;
-		vocState[1] = _v3SceneMediaModeEnabled;
-		vocState[2] = _v3SceneWaveLeftPercent;
-		vocState[3] = _v3SceneWaveRightPercent;
-		vocState[6] = _v3SceneMixerVolumePercent;
+		vocState[0] = _sceneWaveBalancePercent;
+		vocState[1] = _sceneMediaModeEnabled;
+		vocState[2] = _sceneWaveLeftPercent;
+		vocState[3] = _sceneWaveRightPercent;
+		vocState[6] = _sceneMixerVolumePercent;
 
 		for (uint i = 0; i < COMFY_VOC_QUEUE_CAPACITY; i++) {
 			byte *packedEntry = vocState + 7 + i * 0x1F;
@@ -139,6 +139,7 @@ void ComfyEngine::sceneBlockPackRuntimeState() {
 				WRITE_LE_UINT16(packedEntry + 7 + frame * 2, state.entries[entry].frames[frame]);
 		}
 	}
+
 	memcpy(&_sceneMemoryBlock[_sceneActorPcOffset], _actorPcTable, sizeof(_actorPcTable));
 
 	if (!_stringTable.empty())
@@ -285,11 +286,11 @@ void ComfyEngine::sceneBlockUnpackRuntimeState() {
 
 	if (_engineVersion == 3) {
 		byte *vocState = &_sceneMemoryBlock[_sceneMidiInstanceOffset + COMFY_SCENE_MIDI_INSTANCE_BYTES];
-		_v3SceneWaveBalancePercent = vocState[0];
-		_v3SceneMediaModeEnabled = vocState[1];
-		_v3SceneWaveLeftPercent = vocState[2];
-		_v3SceneWaveRightPercent = vocState[3];
-		_v3SceneMixerVolumePercent = vocState[6];
+		_sceneWaveBalancePercent = vocState[0];
+		_sceneMediaModeEnabled = vocState[1];
+		_sceneWaveLeftPercent = vocState[2];
+		_sceneWaveRightPercent = vocState[3];
+		_sceneMixerVolumePercent = vocState[6];
 
 		for (uint i = 0; i < COMFY_VOC_QUEUE_CAPACITY; i++) {
 			byte *packedEntry = vocState + 7 + i * 0x1F;
@@ -657,12 +658,11 @@ void ComfyEngine::sceneShutdown() {
 	_sceneFrameData.clear();
 
 	if (_engineVersion == 3) {
-		_v3SceneWaveLeftPercent = 0xFF;
-		_v3SceneWaveRightPercent = 0xFF;
+		_sceneWaveLeftPercent = 0xFF;
+		_sceneWaveRightPercent = 0xFF;
 	}
 
 	_sceneOpen = false;
 }
 
-
 } // End of namespace Comfy
diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index 5bdc2e2a0c5..b27117cf524 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -26,134 +26,144 @@
 
 namespace Comfy {
 
-#define O_ACTOR_SET_POSITION 0x01
-#define O_ACTOR_ADD_POSITION 0x02
-#define O_ACTOR_SET_FRAME 0x03
-#define O_WAIT_KEY_SET 0x04
-#define O_JUMP_IF_KEY_STATE 0x05
-#define O_SET_KEY_STATE 0x06
-#define O_ACTOR_DESTROY 0x07
-#define O_ACTOR_CREATE 0x08
-#define O_SET_CURRENT_ACTOR_FRAME 0x09
-#define O_ACTOR_SHOW 0x0A
-#define O_ACTOR_HIDE 0x0B
-#define O_ACTOR_ACTIVATE 0x0C
-#define O_ACTOR_DEACTIVATE 0x0D
-#define O_ACTOR_COMPARE_X_SET_KEY 0x0E
-#define O_ACTOR_COMPARE_Y_SET_KEY 0x0F
-#define O_ACTOR_COMPARE_X_CLEAR_KEY 0x10
-#define O_ACTOR_COMPARE_Y_CLEAR_KEY 0x11
-#define O_MIDI_ADD_TRACK 0x12
-#define O_RANDOM_JUMP 0x13
-#define O_ACTOR_REORDER 0x14
-#define O_LOAD_SPRITE_CONV_LIST 0x15
-#define O_LOAD_SOUND_LIST 0x16
-#define O_QUEUE_VOC 0x17
-#define O_ACTOR_RESET 0x18
-#define O_ACTOR_CALL_IF_KEY_STATE 0x19
-#define O_ACTOR_RETURN 0x1A
-#define O_PLAY_VOC_QUEUE 0x1B
-#define O_MIDI_REMOVE_TRACK 0x1C
-#define O_MIDI_CHANNEL_CONTROL 0x1D
-#define O_ACTOR_SET_TRIGGER 0x1E
-#define O_SET_MUSIC_EVENT 0x1F
-#define O_REQUEST_SCENE 0x20
-#define O_PALETTE_CONTROL 0x21
-#define O_SET_MUSIC_ENABLED 0x22
-#define O_SCRIPT_VARIABLE_ADD 0x23
-#define O_MIDI_SET_TIME_SCALE 0x24
-#define O_CLEAR_KEY_RANGE 0x25
-#define O_SCRIPT_VARIABLE_GE_VALUE_SET_KEY 0x26
-#define O_SKIP_WORD_28 0x28
-#define O_SKIP_WORD_29 0x29
-#define O_ACTOR_SET_SPRITE_SELECTOR 0x2A
-#define O_JUMP_RELATIVE 0x2B
-#define O_COPY_KEY 0x2C
-#define O_SCENE_CONTROL 0x2D
+// OPCODES
+
+#define O_ACTOR_SET_POSITION                  0x01
+#define O_ACTOR_ADD_POSITION                  0x02
+#define O_ACTOR_SET_FRAME                     0x03
+#define O_WAIT_KEY_SET                        0x04
+#define O_JUMP_IF_KEY_STATE                   0x05
+#define O_SET_KEY_STATE                       0x06
+#define O_ACTOR_DESTROY                       0x07
+#define O_ACTOR_CREATE                        0x08
+#define O_SET_CURRENT_ACTOR_FRAME             0x09
+#define O_ACTOR_SHOW                          0x0A
+#define O_ACTOR_HIDE                          0x0B
+#define O_ACTOR_ACTIVATE                      0x0C
+#define O_ACTOR_DEACTIVATE                    0x0D
+#define O_ACTOR_COMPARE_X_SET_KEY             0x0E
+#define O_ACTOR_COMPARE_Y_SET_KEY             0x0F
+#define O_ACTOR_COMPARE_X_CLEAR_KEY           0x10
+#define O_ACTOR_COMPARE_Y_CLEAR_KEY           0x11
+#define O_MIDI_ADD_TRACK                      0x12
+#define O_RANDOM_JUMP                         0x13
+#define O_ACTOR_REORDER                       0x14
+#define O_LOAD_SPRITE_CONV_LIST               0x15
+#define O_LOAD_SOUND_LIST                     0x16
+#define O_QUEUE_VOC                           0x17
+#define O_ACTOR_RESET                         0x18
+#define O_ACTOR_CALL_IF_KEY_STATE             0x19
+#define O_ACTOR_RETURN                        0x1A
+#define O_PLAY_VOC_QUEUE                      0x1B
+#define O_MIDI_REMOVE_TRACK                   0x1C
+#define O_MIDI_CHANNEL_CONTROL                0x1D
+#define O_ACTOR_SET_TRIGGER                   0x1E
+#define O_SET_MUSIC_EVENT                     0x1F
+#define O_REQUEST_SCENE                       0x20
+#define O_PALETTE_CONTROL                     0x21
+#define O_SET_MUSIC_ENABLED                   0x22
+#define O_SCRIPT_VARIABLE_ADD                 0x23
+#define O_MIDI_SET_TIME_SCALE                 0x24
+#define O_CLEAR_KEY_RANGE                     0x25
+#define O_SCRIPT_VARIABLE_GE_VALUE_SET_KEY    0x26
+#define O_SKIP_WORD_28                        0x28
+#define O_SKIP_WORD_29                        0x29
+#define O_ACTOR_SET_SPRITE_SELECTOR           0x2A
+#define O_JUMP_RELATIVE                       0x2B
+#define O_COPY_KEY                            0x2C
+#define O_SCENE_CONTROL                       0x2D
 #define O_SCRIPT_VARIABLE_GE_VARIABLE_SET_KEY 0x2E
-#define O_SCRIPT_VARIABLE_COPY 0x2F
-#define O_ANIMATION_CONTROL 0x30
-#define O_SET_LAST_VOC_ARGUMENTS 0x31
-#define O_UNUSED_32 0x32
-#define O_SKIP_TABLE_BLOCK 0x33
-#define O_CONFIG_STRING_COMMAND 0x34
-#define O_MOUSE_SET_ACTOR 0x35
-#define O_HOST_MEDIA_CONTROL 0x36
-#define O_ANIMATION_AUDIO_CONTROL 0x46
-#define O_PRELOAD_SPRITE_CONV_RANGE 0x47
-#define O_JUMP_IF_KEY_CLEAR_V3 0x48
-#define O_JUMP_IF_KEY_SET_V3 0x49
-#define O_STRING_TABLE_COMPARE_SET_KEY 0x50
-#define O_ACTOR_MOVE_BY 0x51
-#define O_ACTOR_MOVE_TO 0x52
-#define O_ACTOR_SET_FRAME_AND_STOP 0x53
-#define O_COPY_INLINE_BLOCK 0x54
-#define O_COPY_PALETTE_ENTRY 0x55
-#define O_WAIT 0x6E
-#define O_MIDI_ADD_EVENT 0x6F
-#define O_ACTOR_MOVE_BY_V2 0x70
-#define O_ACTOR_MOVE_TO_V2 0x71
-#define O_ACTOR_WAIT_TICKS 0x72
-#define O_WAVE_OUTPUT_RESET 0x73
-#define O_WAIT_KEY_CLEAR 0x74
-#define O_CONDITIONAL_SET_KEY 0x75
-#define O_STRING_TABLE_SET 0x76
-#define O_STRING_TABLE_SET_OFFSET 0x77
-#define O_NOP 0x7F
-
-#define SO_MIDI_LOAD_TRACK 1
-#define SO_MIDI_SET_RATE 2
-#define SO_MIDI_SET_PITCH 3
-#define SO_MIDI_SET_VOLUME 4
-#define SO_MIDI_STOP_AND_ADVANCE 5
-#define SO_MIDI_STOP_AND_FIRE_KEYS 6
-#define SO_MIDI_ENABLE_LOOP 7
-#define SO_MIDI_DISABLE_LOOP 8
-#define SO_SCENE_ENTRY_INIT 1
-#define SO_SCENE_ENTRY_STOP 2
-#define SO_SCENE_ENTRY_LOAD 3
-#define SO_SCENE_MIDI_PLAY_AT_FRAME 4
-#define SO_SCENE_MIDI_STOP 5
-#define SO_SCENE_MIDI_SET_VOLUME 6
-#define SO_ANIM_SHUTDOWN 0
-#define SO_ANIM_LOAD_FRAME 1
-#define SO_ANIM_SET_READY 2
-#define SO_ANIM_CLEAR_READY 3
-#define SO_ANIM_NOOP_4 4
-#define SO_ANIM_NOOP_5 5
-#define SO_ANIM_INVALIDATE_ACTOR_RECT 6
-#define SO_CONFIG_READ_INT 0
-#define SO_CONFIG_WRITE_INT 1
-#define SO_CONFIG_SUSPEND_ACTOR 2
-#define SO_CONFIG_RUN_COMMAND 3
-#define SO_CONFIG_TEST_VALUE 4
-#define SO_CONFIG_TEST_FILE 5
+#define O_SCRIPT_VARIABLE_COPY                0x2F
+#define O_ANIMATION_CONTROL                   0x30
+#define O_SET_LAST_VOC_ARGUMENTS              0x31
+#define O_UNUSED_32                           0x32
+#define O_SKIP_TABLE_BLOCK                    0x33
+#define O_CONFIG_STRING_COMMAND               0x34
+#define O_MOUSE_SET_ACTOR                     0x35
+#define O_HOST_MEDIA_CONTROL                  0x36
+#define O_ANIMATION_AUDIO_CONTROL             0x46
+#define O_PRELOAD_SPRITE_CONV_RANGE           0x47
+#define O_JUMP_IF_KEY_CLEAR_V3                0x48
+#define O_JUMP_IF_KEY_SET_V3                  0x49
+#define O_STRING_TABLE_COMPARE_SET_KEY        0x50
+#define O_ACTOR_MOVE_BY                       0x51
+#define O_ACTOR_MOVE_TO                       0x52
+#define O_ACTOR_SET_FRAME_AND_STOP            0x53
+#define O_COPY_INLINE_BLOCK                   0x54
+#define O_COPY_PALETTE_ENTRY                  0x55
+#define O_WAIT                                0x6E
+#define O_MIDI_ADD_EVENT                      0x6F
+#define O_ACTOR_MOVE_BY_V2                    0x70
+#define O_ACTOR_MOVE_TO_V2                    0x71
+#define O_ACTOR_WAIT_TICKS                    0x72
+#define O_WAVE_OUTPUT_RESET                   0x73
+#define O_WAIT_KEY_CLEAR                      0x74
+#define O_CONDITIONAL_SET_KEY                 0x75
+#define O_STRING_TABLE_SET                    0x76
+#define O_STRING_TABLE_SET_OFFSET             0x77
+#define O_NOP                                 0x7F
+
+// SUBOPCODES
+
+#define SO_MIDI_LOAD_TRACK                       1
+#define SO_MIDI_SET_RATE                         2
+#define SO_MIDI_SET_PITCH                        3
+#define SO_MIDI_SET_VOLUME                       4
+#define SO_MIDI_STOP_AND_ADVANCE                 5
+#define SO_MIDI_STOP_AND_FIRE_KEYS               6
+#define SO_MIDI_ENABLE_LOOP                      7
+#define SO_MIDI_DISABLE_LOOP                     8
+
+#define SO_SCENE_ENTRY_INIT                      1
+#define SO_SCENE_ENTRY_STOP                      2
+#define SO_SCENE_ENTRY_LOAD                      3
+#define SO_SCENE_MIDI_PLAY_AT_FRAME              4
+#define SO_SCENE_MIDI_STOP                       5
+#define SO_SCENE_MIDI_SET_VOLUME                 6
+
+#define SO_ANIM_SHUTDOWN                         0
+#define SO_ANIM_LOAD_FRAME                       1
+#define SO_ANIM_SET_READY                        2
+#define SO_ANIM_CLEAR_READY                      3
+#define SO_ANIM_NOOP_4                           4
+#define SO_ANIM_NOOP_5                           5
+#define SO_ANIM_INVALIDATE_ACTOR_RECT            6
+
+#define SO_CONFIG_READ_INT                       0
+#define SO_CONFIG_WRITE_INT                      1
+#define SO_CONFIG_SUSPEND_ACTOR                  2
+#define SO_CONFIG_RUN_COMMAND                    3
+#define SO_CONFIG_TEST_VALUE                     4
+#define SO_CONFIG_TEST_FILE                      5
 #define SO_CONFIG_SET_LANGUAGE_DATA_SUBDIRECTORY 6
-#define SO_MOUSE_SET_ACTOR 1
-#define SO_MOUSE_CLEAR_ACTOR 2
-#define SO_HOST_MEDIA_START_INPUT 1
-#define SO_HOST_MEDIA_STOP_INPUT 2
-#define SO_HOST_MEDIA_START_RECORDING_2_ARGS 3
-#define SO_HOST_MEDIA_START_RECORDING_3_ARGS 4
-#define SO_HOST_MEDIA_START_RECORDING_4_ARGS 5
-#define SO_ANIMATION_INDEX_OFFSET 1
-#define SO_WAVE_BALANCE 2
-#define SO_ANIMATION_ACTOR_SCENE 3
-#define SO_WAVE_LEFT 4
-#define SO_WAVE_RIGHT 5
-#define SO_ANIMATION_AUDIO_NOOP 6
-#define SO_HOST_MEDIA_RANGE 7
-#define SO_MIXER_VOLUME 8
-#define SO_CONDITION_SCENE_EXISTS 1
-#define SO_CONDITION_INPUT_MODE 2
-#define SO_CONDITION_MOUSE_LEFT_BUTTON 3
-#define SO_CONDITION_MOUSE_LEFT_BUTTON_ALT 4
-#define SO_CONDITION_MOUSE_RIGHT_BUTTON 5
-#define SO_CONDITION_MOUSE_RIGHT_BUTTON_ALT 6
-#define SO_CONDITION_ACTOR_HIT_TEST 7
-#define SO_CONDITION_ACTOR_BLIT_HIT_TEST 8
-#define SO_CONDITION_FALSE 13
-#define SO_CONDITION_SYSTEM_FEATURE 14
+
+#define SO_MOUSE_SET_ACTOR                       1
+#define SO_MOUSE_CLEAR_ACTOR                     2
+#define SO_HOST_MEDIA_START_INPUT                1
+#define SO_HOST_MEDIA_STOP_INPUT                 2
+#define SO_HOST_MEDIA_START_RECORDING_2_ARGS     3
+#define SO_HOST_MEDIA_START_RECORDING_3_ARGS     4
+#define SO_HOST_MEDIA_START_RECORDING_4_ARGS     5
+
+#define SO_ANIMATION_INDEX_OFFSET                1
+#define SO_WAVE_BALANCE                          2
+#define SO_ANIMATION_ACTOR_SCENE                 3
+#define SO_WAVE_LEFT                             4
+#define SO_WAVE_RIGHT                            5
+#define SO_ANIMATION_AUDIO_NOOP                  6
+#define SO_HOST_MEDIA_RANGE                      7
+#define SO_MIXER_VOLUME                          8
+
+#define SO_CONDITION_SCENE_EXISTS                1
+#define SO_CONDITION_INPUT_MODE                  2
+#define SO_CONDITION_MOUSE_LEFT_BUTTON           3
+#define SO_CONDITION_MOUSE_LEFT_BUTTON_ALT       4
+#define SO_CONDITION_MOUSE_RIGHT_BUTTON          5
+#define SO_CONDITION_MOUSE_RIGHT_BUTTON_ALT      6
+#define SO_CONDITION_ACTOR_HIT_TEST              7
+#define SO_CONDITION_ACTOR_BLIT_HIT_TEST         8
+#define SO_CONDITION_FALSE                       13
+#define SO_CONDITION_SYSTEM_FEATURE              14
 
 ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte opcode, uint32 &pc) {
 	switch (opcode) {
@@ -201,7 +211,6 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			target->yFixed = (int32)((uint32)target->yFixed + (uint32)((int32)y * 0x1000));
 		}
 
-
 		return kScriptContinue;
 	}
 
@@ -286,8 +295,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		if (!parentSlot)
 			parentSlot = actor.sceneHandle;
 
-		actorInit(sceneSlot, parentSlot, (flags & 1) != 0, (flags & 2) != 0,
-			newPc, x, y, sprite, (flags & 4) != 0);
+		actorInit(sceneSlot, parentSlot, (flags & 1) != 0, (flags & 2) != 0, newPc, x, y, sprite, (flags & 4) != 0);
 		return kScriptContinue;
 	}
 
@@ -381,6 +389,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		byte choice = (byte)((getRandomNumber(0x7FFF) * totalWeight) / 0x8000);
 		byte accumulated = 0;
 		uint32 targetPc = 0;
+
 		do {
 			accumulated += scriptReadByte(pc++);
 			targetPc = scriptReadDword(pc);
@@ -398,6 +407,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		byte mode = scriptReadByte(pc + 2);
 		pc += 3;
+
 		if (!target)
 			error("Script opcode 0x14 resolved an invalid actor");
 
@@ -464,6 +474,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		target->active = 1;
 		target->waitTarget = 0;
 		target->waitAccum = 0;
+
 		if (target->moveTicks) {
 			target->moveTicks = 0;
 			uint16 completionKey = target->completionKey;
@@ -498,6 +509,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	case O_MIDI_CHANNEL_CONTROL: {
 		byte packed = scriptReadByte(pc++);
 		byte channel = (packed >> 4) - 1;
+
 		byte subop = packed & 0x0F;
 		switch (subop) {
 		case SO_MIDI_LOAD_TRACK: {
@@ -511,6 +523,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			for (uint i = 0; i < count; i++) {
 				uint16 frame = scriptReadWord(pc);
 				pc += 2;
+
 				if (i < COMFY_ANIM_FRAME_CAPACITY)
 					frames[i] = frame;
 			}
@@ -554,6 +567,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		byte flags = scriptReadByte(pc + 4);
 		uint32 triggerPc = scriptReadDword(pc + 5);
 		pc += 9;
+
 		if (!target)
 			error("Script opcode 0x1E resolved an invalid actor");
 
@@ -600,6 +614,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint16 fadeTicks = scriptReadStringIndex(pc + 2);
 		byte brightness = scriptReadByte(pc + 4);
 		pc += 5;
+
 		if (!brightness) {
 			actorSetPos(1, (int16)paletteId);
 			paletteLoadWithFade(paletteId, fadeTicks);
@@ -636,6 +651,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint16 first = scriptReadWord(pc);
 		uint16 last = scriptReadWord(pc + 2);
 		pc += 4;
+
 		for (uint16 key = first; key <= last; key++) {
 			keyBitClear(key);
 			if (key == 0xFFFF)
@@ -651,6 +667,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint16 second = scriptReadWord(pc + 2);
 		uint16 key = scriptReadWord(pc + 4);
 		pc += 6;
+
 		int16 lhs = (int16)scriptVariableGet(first);
 		int16 rhs = opcode == O_SCRIPT_VARIABLE_GE_VALUE_SET_KEY ? (int16)second : (int16)scriptVariableGet(second);
 		if (lhs >= rhs)
@@ -669,6 +686,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		Actor *target = actorResolve(scriptReadWord(pc), _currentActor);
 		uint32 selector = scriptReadDword(pc + 2);
 		pc += 6;
+
 		if (target)
 			target->spriteSelector = (selector + 1) | 0xFF000000;
 
@@ -745,11 +763,11 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint16 first = scriptReadWord(pc + 3);
 		uint16 second = scriptReadWord(pc + 5);
 		pc += 7;
+
 		if (command == '=')
 			scriptVariableCopy(destination, first);
 		else if (command == 'm')
-			scriptVariableCopy(destination,
-				(int16)scriptVariableGet(second) <= (int16)scriptVariableGet(first) ? first : second);
+			scriptVariableCopy(destination, (int16)scriptVariableGet(second) <= (int16)scriptVariableGet(first) ? first : second);
 
 		return kScriptContinue;
 	}
@@ -769,15 +787,15 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			pc += 4;
 
 			if (_engineVersion == 3) {
-				animIndex += _v3AnimIndexOffset;
-				_v3AnimIndexOffset = 0;
+				animIndex += _animIndexOffset;
+				_animIndexOffset = 0;
 
 				if (!animFrameIsActive()) {
-					if (!_v3AnimActorSceneHandle)
-						_v3AnimActorSceneHandle = actor.sceneHandle;
+					if (!_animActorSceneHandle)
+						_animActorSceneHandle = actor.sceneHandle;
 
-					animFileLoadFrame(animIndex, frameKey, _v3AnimActorSceneHandle);
-					_v3AnimActorSceneHandle = 0;
+					animFileLoadFrame(animIndex, frameKey, _animActorSceneHandle);
+					_animActorSceneHandle = 0;
 				}
 			} else {
 				animFileLoadFrame(animIndex, frameKey, actor.sceneHandle);
@@ -809,6 +827,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	case O_SET_LAST_VOC_ARGUMENTS: { // Added in version 2
 		uint16 count = scriptReadStringIndex(pc);
 		pc += 2;
+
 		if (_animUsesWaveVocCounter) {
 			uint16 slot = _soundEventMaximum ? _soundEventMaximum - 1 : _vocQueueCapacity - 1;
 			if (_engineVersion == 3) {
@@ -847,6 +866,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		byte subop = scriptReadByte(pc++);
 		uint16 value = scriptReadWord(pc);
 		pc += 2;
+
 		Common::String key;
 		for (byte character = scriptReadByte(pc++); character; character = scriptReadByte(pc++))
 			key += (char)character;
@@ -860,16 +880,16 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		case SO_CONFIG_WRITE_INT:
 			ConfMan.setInt(key, value);
 			if (key.equalsIgnoreCase("SENSITIVITY"))
-				_v3Sensitivity = value;
+				_sensitivity = value;
 
 			ConfMan.flushToDisk();
 			break;
 		case SO_CONFIG_SUSPEND_ACTOR:
 		case SO_CONFIG_RUN_COMMAND:
-			_v3ConfigCommandPending = true;
-			_v3ConfigCommandSubop = subop;
-			_v3ConfigCommandValue = value;
-			_v3ConfigCommandText = key;
+			_configCommandPending = true;
+			_configCommandSubop = subop;
+			_configCommandValue = value;
+			_configCommandText = key;
 
 			if (subop == SO_CONFIG_SUSPEND_ACTOR) {
 				Actor *configActor = actorGetPtr(sceneGetHandle(1));
@@ -914,6 +934,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		byte subop = 0;
 		Actor *mouseActor = nullptr;
 		pc = scriptReadArgs(pc, _currentActor, "CO", &subop, &mouseActor);
+
 		switch (subop) {
 		case SO_MOUSE_SET_ACTOR:
 			mouseSetActor(mouseActor);
@@ -936,25 +957,25 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			break;
 		case SO_HOST_MEDIA_STOP_INPUT:
 			setMediaMode(subop);
-			_v3MediaRecording = false;
+			_mediaRecording = false;
 			break;
 		case SO_HOST_MEDIA_START_RECORDING_2_ARGS:
 		case SO_HOST_MEDIA_START_RECORDING_3_ARGS:
 		case SO_HOST_MEDIA_START_RECORDING_4_ARGS:
-			_v3MediaRecordingArg0 = scriptReadStringIndex(pc);
-			_v3MediaRecordingArg1 = scriptReadWord(pc + 2);
+			_mediaRecordingArg0 = scriptReadStringIndex(pc);
+			_mediaRecordingArg1 = scriptReadWord(pc + 2);
 			pc += 4;
-			_v3MediaRecording = true;
-			if (!_v3SceneMediaModeEnabled)
+			_mediaRecording = true;
+			if (!_sceneMediaModeEnabled)
 				setMediaMode(SO_HOST_MEDIA_START_INPUT);
 
 			if (subop != SO_HOST_MEDIA_START_RECORDING_2_ARGS) {
-				_v3MediaRecordingArg2 = scriptReadStringIndex(pc);
+				_mediaRecordingArg2 = scriptReadStringIndex(pc);
 				pc += 2;
 			}
 
 			if (subop == SO_HOST_MEDIA_START_RECORDING_4_ARGS) {
-				_v3MediaRecordingArg3 = scriptReadStringIndex(pc);
+				_mediaRecordingArg3 = scriptReadStringIndex(pc);
 				pc += 2;
 			}
 
@@ -976,7 +997,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 		switch (subop) {
 		case SO_ANIMATION_INDEX_OFFSET:
-			_v3AnimIndexOffset = scriptReadStringIndex(pc);
+			_animIndexOffset = scriptReadStringIndex(pc);
 			pc += 2;
 			break;
 		case SO_WAVE_BALANCE:
@@ -984,7 +1005,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			pc += 2;
 			break;
 		case SO_ANIMATION_ACTOR_SCENE:
-			_v3AnimActorSceneHandle = scriptReadWord(pc);
+			_animActorSceneHandle = scriptReadWord(pc);
 			pc += 2;
 			break;
 		case SO_WAVE_LEFT:
@@ -1019,6 +1040,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint16 first = scriptReadStringIndex(pc);
 		uint16 last = scriptReadStringIndex(pc + 2);
 		pc += 4;
+
 		for (uint16 spriteId = first; (int16)spriteId <= (int16)last; spriteId++)
 			spriteGetConvPtr((int16)spriteId);
 
@@ -1033,6 +1055,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		pc += 7;
 		int16 lhs = lhsIndex < _stringTable.size() ? _stringTable[lhsIndex] : 0;
 		int16 rhs = rhsIndex < _stringTable.size() ? _stringTable[rhsIndex] : 0;
+
 		bool matched = ((mode & 4) && lhs > rhs) || ((mode & 2) && lhs == rhs) || ((mode & 1) && lhs < rhs);
 		if (matched)
 			keyBitSet(key);
@@ -1058,6 +1081,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		byte blocking = scriptReadByte(pc++);
 		uint16 completionKey = scriptReadWord(pc);
 		pc += 2;
+
 		if (!target)
 			error("Script opcode 0x%02X resolved an invalid actor", opcode);
 
@@ -1101,6 +1125,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			int16 distanceX = ABS((int16)(dx >> 12));
 			int16 distanceY = ABS((int16)(dy >> 12));
 			int16 distance = MAX(distanceX, distanceY);
+
 			duration = (int16)(((int32)distance * 100) / duration);
 			if (!duration)
 				duration = 1;
@@ -1111,6 +1136,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		target->moveTicks = duration;
 		target->blockingMove = blocking;
 		target->completionKey = completionKey;
+
 		return blocking && target == &actor ? kScriptYield : kScriptContinue;
 	}
 
@@ -1123,6 +1149,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint32 targetPc = scriptReadDword(pc + 2);
 		bool jumpWhenSet = opcode == O_JUMP_IF_KEY_SET_V3;
 		pc = keyBitTest(key) == jumpWhenSet ? targetPc : pc + 6;
+
 		return kScriptContinue;
 	}
 
@@ -1139,6 +1166,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		target->spriteSelector = (uint32)(int32)(int16)frame;
 		target->moveDx = 0;
 		target->moveDy = 0;
+
 		return kScriptContinue;
 	}
 
@@ -1148,6 +1176,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 
 		uint32 endPc = scriptReadDword(pc);
 		pc += 4;
+
 		uint32 size = endPc >= pc ? endPc - pc : 0;
 		size = MIN<uint32>(size, COMFY_FRAME_LOADER_DATA_BYTES);
 		if (_comfyObjFile && pc <= _comfyObjFile->fileSize && size <= _comfyObjFile->fileSize - pc) {
@@ -1168,6 +1197,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint16 source = scriptReadStringIndex(pc);
 		uint16 destination = scriptReadStringIndex(pc + 2);
 		pc += 4;
+
 		if (source < 256 && destination < 256)
 			memcpy(&_paletteDisplay[destination * 3], &_paletteDisplay[source * 3], 3);
 
@@ -1191,6 +1221,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint16 requested = scriptReadStringIndex(pc);
 		pc += 2;
 		uint16 balance = actor.waitAccum;
+
 		if (!requested)
 			balance = 0;
 
@@ -1225,6 +1256,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 		uint16 key = scriptReadWord(pc);
 		pc += 2;
 		bool condition = false;
+
 		if (_engineVersion == 3) {
 			uint16 argument = scriptReadWord(pc);
 			pc += 2;
@@ -1255,12 +1287,13 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 				if (argument <= 4) {
 					condition = _inputDeviceMode == argument;
 				} else if (argument == 20) {
-					condition = _v3MediaRecording;
+					condition = _mediaRecording;
 				} else if (argument == 30) {
 					Common::SeekableReadStream *stream = pathFOpen(Common::Path("comfy.htm"), true);
 					condition = stream != nullptr;
 					delete stream;
 				}
+
 				break;
 			default:
 				error("Unknown script opcode 0x75 subopcode 0x%02X at script PC 0x%08X", kind, pc - 6);
@@ -1290,6 +1323,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 	case O_STRING_TABLE_SET_OFFSET: {
 		uint16 index = scriptReadWord(pc);
 		pc += 2;
+
 		if (opcode == O_STRING_TABLE_SET_OFFSET) {
 			if (_stringTable.size() <= 1)
 				error("Script opcode 0x77 requires string table entry 1");
@@ -1327,6 +1361,7 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptStep(Actor &actor, uint32 &
 	uint32 originalPc = pc;
 	_scriptFault = false;
 	byte opcode = scriptReadByte(pc++);
+
 	if (_scriptFault)
 		error("Script fault while fetching opcode at script PC 0x%08X", originalPc);
 
diff --git a/engines/comfy/sound.cpp b/engines/comfy/sound.cpp
index 4d0c1fdba79..e0388146e2e 100644
--- a/engines/comfy/sound.cpp
+++ b/engines/comfy/sound.cpp
@@ -26,14 +26,16 @@
 #include "common/debug.h"
 #include "common/endian.h"
 
-#define SOUND_CMD_START 0
-#define SOUND_CMD_BEGIN_EVENT 1
-#define SOUND_CMD_BEGIN_LOOP_EVENT 2
+// SOUND COMMANDS
+
+#define SOUND_CMD_START                0
+#define SOUND_CMD_BEGIN_EVENT          1
+#define SOUND_CMD_BEGIN_LOOP_EVENT     2
 #define SOUND_CMD_FILL_OR_SAMPLE_DELAY 3
-#define SOUND_CMD_PITCH_CHANGE 4
-#define SOUND_CMD_LOOP_START 6
-#define SOUND_CMD_LOOP_END 7
-#define SOUND_CMD_SET_SAMPLE 99
+#define SOUND_CMD_PITCH_CHANGE         4
+#define SOUND_CMD_LOOP_START           6
+#define SOUND_CMD_LOOP_END             7
+#define SOUND_CMD_SET_SAMPLE           99
 
 namespace Comfy {
 
@@ -119,7 +121,6 @@ byte ComfyEngine::soundOpenEntry(uint16 index) {
 	return _soundFault ? 0 : _soundSample;
 }
 
-
 void ComfyEngine::setWaveBalancePercent(uint16 value) {
 	if ((int16)value < 0) {
 		value = 0;
@@ -127,8 +128,8 @@ void ComfyEngine::setWaveBalancePercent(uint16 value) {
 		value = 100;
 	}
 
-	_v3SceneWaveBalancePercent = (byte)value;
-	_v3WaveBalancePercent = value;
+	_sceneWaveBalancePercent = (byte)value;
+	_waveBalancePercent = value;
 }
 
 void ComfyEngine::setWaveLeftPercent(uint16 value) {
@@ -141,8 +142,8 @@ void ComfyEngine::setWaveLeftPercent(uint16 value) {
 		value = 100;
 	}
 
-	_v3SceneWaveLeftPercent = (byte)value;
-	_v3WaveLeftPercent = value;
+	_sceneWaveLeftPercent = (byte)value;
+	_waveLeftPercent = value;
 }
 
 void ComfyEngine::setWaveRightPercent(uint16 value) {
@@ -155,8 +156,8 @@ void ComfyEngine::setWaveRightPercent(uint16 value) {
 		value = 100;
 	}
 
-	_v3SceneWaveRightPercent = (byte)value;
-	_v3WaveRightPercent = value;
+	_sceneWaveRightPercent = (byte)value;
+	_waveRightPercent = value;
 }
 
 void ComfyEngine::setMixerVolumePercent(uint16 value) {
@@ -169,8 +170,8 @@ void ComfyEngine::setMixerVolumePercent(uint16 value) {
 		value = 100;
 	}
 
-	_v3SceneMixerVolumePercent = (byte)value;
-	_v3MixerVolumePercent = value;
+	_sceneMixerVolumePercent = (byte)value;
+	_mixerVolumePercent = value;
 }
 
 void ComfyEngine::setMediaRangePercent(uint16 value) {
@@ -180,31 +181,31 @@ void ComfyEngine::setMediaRangePercent(uint16 value) {
 		value = 100;
 	}
 
-	_v3MixerAltPercent = value;
+	_mixerAltPercent = value;
 }
 
 void ComfyEngine::setMediaMode(byte mode) {
 	if (mode == 1 || mode == 3) {
-		_v3SceneMediaModeEnabled = 1;
+		_sceneMediaModeEnabled = 1;
 
-		if (!_v3MediaValueAvailable) {
-			_v3MediaValue = 0;
-			_v3MediaValueAvailable = true;
+		if (!_mediaValueAvailable) {
+			_mediaValue = 0;
+			_mediaValueAvailable = true;
 		}
 	} else if (mode == 2) {
-		_v3SceneMediaModeEnabled = 0;
-		_v3MediaValue = 0;
-		_v3MediaValueAvailable = false;
+		_sceneMediaModeEnabled = 0;
+		_mediaValue = 0;
+		_mediaValueAvailable = false;
 	}
 }
 
 void ComfyEngine::restoreWaveStateAfterSceneStart() {
-	setWaveBalancePercent(_v3SceneWaveBalancePercent);
-	setWaveLeftPercent(_v3SceneWaveLeftPercent);
-	setWaveRightPercent(_v3SceneWaveRightPercent);
-	setMixerVolumePercent(_v3SceneMixerVolumePercent);
+	setWaveBalancePercent(_sceneWaveBalancePercent);
+	setWaveLeftPercent(_sceneWaveLeftPercent);
+	setWaveRightPercent(_sceneWaveRightPercent);
+	setMixerVolumePercent(_sceneMixerVolumePercent);
 
-	if (_v3SceneMediaModeEnabled) {
+	if (_sceneMediaModeEnabled) {
 		setMediaMode(2);
 		setMediaMode(1);
 	} else {
@@ -235,6 +236,7 @@ bool ComfyEngine::soundOpenVocFile() {
 	_soundCompressed = !_isPanther && header[1] == 'W';
 	_soundUsesAnimData = false;
 	_soundTileStride = READ_LE_UINT16(header + 2);
+
 	return true;
 }
 
@@ -544,7 +546,7 @@ uint32 ComfyEngine::soundCalcSampleRate(byte &sample) {
 		_midiPlyrDriver->vocSrGetCounters(timeFrac, blockNo);
 
 		if (blockNo && timeFrac)
-			return ((uint32)blockNo * 0x1E8480) / timeFrac;
+			return ((uint32)blockNo * 2000000) / timeFrac;
 	}
 
 	uint32 denominator = 0x100 - sample;
@@ -929,7 +931,6 @@ void ComfyEngine::soundDecompressBlock(uint16 size) {
 
 		_soundRate++;
 	}
-
 }
 
 void ComfyEngine::soundLoadDataBlock(uint16 size) {
@@ -1404,6 +1405,7 @@ void ComfyEngine::soundPackState() {
 	uint32 playbackPosition = (vocCounter * _soundSampleRate) / 100;
 	uint16 bufferIndex = _soundWaveBufferIndex;
 	uint32 blockSize = _isPanther ? COMFY_PANTHER_SOUND_PCM_BLOCK_BYTES : (_engineVersion == 3 ? COMFY_V3_SOUND_PCM_BLOCK_BYTES : COMFY_SOUND_PCM_BLOCK_BYTES);
+
 	if ((int32)(_soundStreamPosition - blockSize) < (int32)playbackPosition)
 		bufferIndex = 1 - bufferIndex;
 
diff --git a/engines/comfy/video.cpp b/engines/comfy/video.cpp
index 8d56a50a456..c178b3ced8e 100644
--- a/engines/comfy/video.cpp
+++ b/engines/comfy/video.cpp
@@ -271,18 +271,15 @@ void ComfyEngine::videoPresentFrame() {
 	if (_renderInterleaved && framebufferBytes() == 64000) {
 		uint32 byteOffset = 0;
 
-		for (uint16 i = 0; i < 16000;) {
+		for (uint16 i = 0; i < 16000; i++) {
 			memcpy(_presentBuffer + byteOffset, _framebufPtr + byteOffset, 4);
 			byteOffset += 4;
 
 			if ((i % 20000) > 17000)
 				i++;
-
-			i++;
 		}
 
-		_screen->copyRectToSurface(_presentBuffer, _logicalScreenWidth, 0, 0,
-			_logicalScreenWidth, _logicalScreenHeight);
+		_screen->copyRectToSurface(_presentBuffer, _logicalScreenWidth, 0, 0, _logicalScreenWidth, _logicalScreenHeight);
 	} else {
 		uint32 dirtyArea = 0;
 


Commit: 6701ea65207af1bb574fe94341160a09987dd708
    https://github.com/scummvm/scummvm/commit/6701ea65207af1bb574fe94341160a09987dd708
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: DETECTION: Avoid showing ImGui options for non ImGui builds

Changed paths:
    engines/comfy/detection.h
    engines/comfy/detection_tables.h
    engines/comfy/metaengine.cpp


diff --git a/engines/comfy/detection.h b/engines/comfy/detection.h
index 5f9ebdfbc5e..eed98b248b0 100644
--- a/engines/comfy/detection.h
+++ b/engines/comfy/detection.h
@@ -56,6 +56,20 @@ extern const ComfyGameDescription gameDescriptions[];
 #define GAMEOPTION_SKIP_INTRO           GUIO_GAMEOPTIONS2
 #define GAMEOPTION_USE_IMGUI_KEYBOARD   GUIO_GAMEOPTIONS3
 
+// Avoid showing the "Use ImGui based virtual keyboard" option entirely, if this build doesn't have ImGui...
+
+#ifdef USE_IMGUI
+
+#define COMFY_GUIO_STANDARD GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
+#define COMFY_GUIO_NO_INTRO GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_USE_IMGUI_KEYBOARD)
+
+#else
+
+#define COMFY_GUIO_STANDARD GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO)
+#define COMFY_GUIO_NO_INTRO GUIO1(GAMEOPTION_FORCE_LANGUAGE_SETUP)
+
+#endif
+
 } // End of namespace Comfy
 
 class ComfyMetaEngineDetection : public AdvancedMetaEngineDetection<Comfy::ComfyGameDescription> {
diff --git a/engines/comfy/detection_tables.h b/engines/comfy/detection_tables.h
index 325db2226cb..e347ca8094d 100644
--- a/engines/comfy/detection_tables.h
+++ b/engines/comfy/detection_tables.h
@@ -45,7 +45,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
+		COMFY_GUIO_STANDARD
 		},
 		1
 	},
@@ -62,7 +62,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
+		COMFY_GUIO_STANDARD
 		},
 		3
 	},
@@ -77,7 +77,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
+		COMFY_GUIO_STANDARD
 		},
 		1
 	},
@@ -92,7 +92,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
+		COMFY_GUIO_STANDARD
 		},
 		2
 	},
@@ -106,7 +106,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
+		COMFY_GUIO_STANDARD
 		},
 		2
 	},
@@ -120,7 +120,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
+		COMFY_GUIO_STANDARD
 		},
 		1
 	},
@@ -134,7 +134,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
+		COMFY_GUIO_STANDARD
 		},
 		2
 	},
@@ -149,7 +149,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
+		COMFY_GUIO_STANDARD
 		},
 		3
 	},
@@ -164,7 +164,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
+		COMFY_GUIO_STANDARD
 		},
 		3
 	},
@@ -179,7 +179,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO3(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_SKIP_INTRO, GAMEOPTION_USE_IMGUI_KEYBOARD)
+		COMFY_GUIO_STANDARD
 		},
 		3
 	},
@@ -194,7 +194,7 @@ const ComfyGameDescription gameDescriptions[] = {
 		Common::UNK_LANG,
 		Common::kPlatformWindows,
 		ADGF_UNSTABLE,
-		GUIO2(GAMEOPTION_FORCE_LANGUAGE_SETUP, GAMEOPTION_USE_IMGUI_KEYBOARD)
+		COMFY_GUIO_NO_INTRO
 		},
 		2
 	},
diff --git a/engines/comfy/metaengine.cpp b/engines/comfy/metaengine.cpp
index f591f9d68b0..d6dda9ad327 100644
--- a/engines/comfy/metaengine.cpp
+++ b/engines/comfy/metaengine.cpp
@@ -54,6 +54,7 @@ static const ADExtraGuiOptionsMap optionsList[] = {
 			0
 		}
 	},
+#ifdef USE_IMGUI
 	{
 		GAMEOPTION_USE_IMGUI_KEYBOARD,
 		{
@@ -65,6 +66,7 @@ static const ADExtraGuiOptionsMap optionsList[] = {
 			0
 		}
 	},
+#endif
 	AD_EXTRA_GUI_OPTIONS_TERMINATOR
 };
 


Commit: f9488ba34668fc393e2a851735f08a41944c63b8
    https://github.com/scummvm/scummvm/commit/f9488ba34668fc393e2a851735f08a41944c63b8
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Leftover clean-up edits to be committed

Whoops

Changed paths:
    engines/comfy/comfy.h
    engines/comfy/expr.cpp


diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index ee2f06672d6..a1020e7afca 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -721,8 +721,8 @@ private:
 	byte _sceneWaveLeftPercent = 0;
 	byte _sceneWaveRightPercent = 0;
 	byte _sceneMixerVolumePercent = 0;
-	bool _v3MediaValueAvailable = false;
-	uint16 _v3MediaValue = 0;
+	bool _mediaValueAvailable = false;
+	uint16 _mediaValue = 0;
 	uint16 _v3MediaProgress = 0;
 	uint16 _sensitivity = 0;
 	bool _configCommandPending = false;
diff --git a/engines/comfy/expr.cpp b/engines/comfy/expr.cpp
index 7dac5764cb3..8bb4d6ce1e9 100644
--- a/engines/comfy/expr.cpp
+++ b/engines/comfy/expr.cpp
@@ -183,7 +183,7 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 				break;
 
 			case EO_HOST_MEDIA_VALUE:
-				value = _v3MediaValueAvailable ? _v3MediaValue : 0;
+				value = _mediaValueAvailable ? _mediaValue : 0;
 				break;
 
 			case EO_NOOP_1B:


Commit: 2b2b983666bf5bc0db726cc920e8015a3fdc4831
    https://github.com/scummvm/scummvm/commit/2b2b983666bf5bc0db726cc920e8015a3fdc4831
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Show a reminder to configure the keymapper at game boot-up

Changed paths:
    engines/comfy/comfy.cpp
    engines/comfy/comfy.h
    engines/comfy/game.cpp


diff --git a/engines/comfy/comfy.cpp b/engines/comfy/comfy.cpp
index 3e3f6242f1b..4fd38739cc9 100644
--- a/engines/comfy/comfy.cpp
+++ b/engines/comfy/comfy.cpp
@@ -27,8 +27,10 @@
 #include "common/debug-channels.h"
 #include "common/events.h"
 #include "common/system.h"
+#include "common/translation.h"
 #include "engines/util.h"
 #include "graphics/paletteman.h"
+#include "gui/message.h"
 
 #ifdef USE_IMGUI
 #include "backends/imgui/imgui.h"
@@ -49,6 +51,30 @@ void ComfyEngine::configRunPendingCommand() {
 		_configCommandSubop, _configCommandValue, _configCommandText.c_str());
 }
 
+void ComfyEngine::showPeripheralWarning() {
+	if (ConfMan.getBool("shown_peripheral_warning"))
+		return;
+
+#ifdef USE_IMGUI
+	// I18N: Shown at startup, the games were designed for a physical toy keyboard
+	Common::U32String message = _("WARNING: this game was originally designed to be played using an external Comfy Keyboard toy peripheral. "
+		"This device is emulated via an ImGui window, or via the keymapper. "
+		"It is advised to configure the keymapper before starting the game.");
+#else
+	// I18N: Shown at startup, the games were designed for a physical toy keyboard
+	Common::U32String message = _("WARNING: this game was originally designed to be played using an external Comfy Keyboard toy peripheral. "
+		"This device is emulated via the keymapper. "
+		"It is advised to configure the keymapper before starting the game.");
+#endif
+
+	GUI::MessageDialog dialog(message, _("Understood"), _("Remind me later"));
+
+	if (dialog.runModal() == GUI::kMessageOK) {
+		ConfMan.setBool("shown_peripheral_warning", true);
+		ConfMan.flushToDisk();
+	}
+}
+
 #ifdef USE_IMGUI
 ImGuiState *_state = nullptr;
 
@@ -147,6 +173,12 @@ Common::Error ComfyEngine::gameInit() {
 	if (!iniReadGameConfig())
 		return Common::kNoGameDataFoundError;
 
+	showPeripheralWarning();
+
+	// Avoid continuing if the user bails out during the warning...
+	if (shouldQuit())
+		return Common::kNoError;
+
 #ifdef USE_IMGUI
 	ImGuiCallbacks imGuiCallbacks;
 	imGuiCallbacks.init = onImGuiInit;
diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index a1020e7afca..8739d536e5f 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -857,6 +857,7 @@ private:
 	Common::Error gameInit();
 	void gameShutdown();
 	void gameConfigInit();
+	void showPeripheralWarning();
 	void findLanguageDirectories();
 	bool iniReadGameConfig();
 	bool iniSelectGameDataPath(uint16 sceneId);
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index c78700b6a1f..cb112a25884 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -112,6 +112,7 @@ void ComfyEngine::gameConfigInit() {
 	ConfMan.registerDefault("skip_intro", false);
 	ConfMan.registerDefault("comfy_screen_update_interleaved", false);
 	ConfMan.registerDefault("comfy_input_device", 0);
+	ConfMan.registerDefault("shown_peripheral_warning", false);
 }
 
 void ComfyEngine::findLanguageDirectories() {


Commit: 647ad22e3698b6f426efc41a6e1221b38e3f6b1c
    https://github.com/scummvm/scummvm/commit/647ad22e3698b6f426efc41a6e1221b38e3f6b1c
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Fix warning

Changed paths:
    engines/comfy/memory.cpp


diff --git a/engines/comfy/memory.cpp b/engines/comfy/memory.cpp
index 66b38de0814..5f0c232e536 100644
--- a/engines/comfy/memory.cpp
+++ b/engines/comfy/memory.cpp
@@ -129,7 +129,7 @@ int32 ComfyEngine::memFreeTrackFar(uint16 handle) {
 }
 
 int32 ComfyEngine::xmsTransfer(XmsMove &move) {
-	byte *source = (byte *)move.sourceMemory;
+	const byte *source = move.sourceMemory;
 	byte *destination = move.destinationMemory;
 	uint32 sourceSize = UINT32_MAX;
 	uint32 destinationSize = UINT32_MAX;


Commit: d4db1ed533e0f50a5f06b1f2e7bc3f4583124945
    https://github.com/scummvm/scummvm/commit/d4db1ed533e0f50a5f06b1f2e7bc3f4583124945
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Forgot to rename a couple of globals

Changed paths:
    engines/comfy/comfy.h
    engines/comfy/expr.cpp
    engines/comfy/game.cpp


diff --git a/engines/comfy/comfy.h b/engines/comfy/comfy.h
index 8739d536e5f..18108bc548d 100644
--- a/engines/comfy/comfy.h
+++ b/engines/comfy/comfy.h
@@ -523,7 +523,7 @@ private:
 	Common::Path _gameDataPath;
 	bool _hasDataPath = false;
 	Common::Path _languageDirectories[16];
-	Common::String _v3LanguageDataSubdirectory;
+	Common::String _languageDataSubdirectory;
 	uint16 _language = 2;
 	bool _multiLanguage = true;
 	Common::RandomSource _randomSource;
@@ -723,7 +723,7 @@ private:
 	byte _sceneMixerVolumePercent = 0;
 	bool _mediaValueAvailable = false;
 	uint16 _mediaValue = 0;
-	uint16 _v3MediaProgress = 0;
+	uint16 _mediaProgress = 0;
 	uint16 _sensitivity = 0;
 	bool _configCommandPending = false;
 	byte _configCommandSubop = 0;
diff --git a/engines/comfy/expr.cpp b/engines/comfy/expr.cpp
index 8bb4d6ce1e9..3f1fd99bd79 100644
--- a/engines/comfy/expr.cpp
+++ b/engines/comfy/expr.cpp
@@ -224,7 +224,7 @@ uint16 ComfyEngine::scriptEvalExpr(uint32 &pc, uint16 fallbackActor) {
 				break;
 
 			case EO_HOST_MEDIA_PROGRESS:
-				value = _v3MediaProgress;
+				value = _mediaProgress;
 				break;
 
 			case EO_MIXER_VOLUME_PERCENT:
diff --git a/engines/comfy/game.cpp b/engines/comfy/game.cpp
index cb112a25884..3cc09d4dc72 100644
--- a/engines/comfy/game.cpp
+++ b/engines/comfy/game.cpp
@@ -205,8 +205,8 @@ bool ComfyEngine::iniSelectGameDataPath(uint16 sceneId) {
 		return false;
 
 	Common::Path gameDataPath = _gameDirectory.join(languageDirectory);
-	if (_engineVersion == 3 && !_v3LanguageDataSubdirectory.empty() && _v3LanguageDataSubdirectory != ".")
-		gameDataPath = gameDataPath.join(Common::Path(_v3LanguageDataSubdirectory, '/'));
+	if (_engineVersion == 3 && !_languageDataSubdirectory.empty() && _languageDataSubdirectory != ".")
+		gameDataPath = gameDataPath.join(Common::Path(_languageDataSubdirectory, '/'));
 
 	pathSetGameDataDir(gameDataPath);
 	return true;
@@ -228,13 +228,13 @@ uint16 ComfyEngine::languageSetDataSubdirectory(Common::String text) {
 	while (end > start && Common::isSpace((byte)text[end - 1]))
 		end--;
 
-	_v3LanguageDataSubdirectory = text.substr(start, end - start);
+	_languageDataSubdirectory = text.substr(start, end - start);
 	_languageSessionRestartRequested = true;
 
-	if (_v3LanguageDataSubdirectory.empty())
+	if (_languageDataSubdirectory.empty())
 		return 0x20;
 
-	byte character = _v3LanguageDataSubdirectory.lastChar();
+	byte character = _languageDataSubdirectory.lastChar();
 	if (character == ' ')
 		return 0x81;
 


Commit: a2c194156f67e5d409b354eb694afc0149b5f5cd
    https://github.com/scummvm/scummvm/commit/a2c194156f67e5d409b354eb694afc0149b5f5cd
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: KEYMAPPER: Set a nicer default mapping configuration

Changed paths:
    engines/comfy/metaengine.cpp


diff --git a/engines/comfy/metaengine.cpp b/engines/comfy/metaengine.cpp
index d6dda9ad327..0b6f9c34610 100644
--- a/engines/comfy/metaengine.cpp
+++ b/engines/comfy/metaengine.cpp
@@ -109,16 +109,23 @@ Common::KeymapArray ComfyMetaEngine::initKeymaps(const char *target) const {
 		_s("Flute"), _s("Keyboard contact 19"), _s("Comfy phone"), _s("Rainy cloud"),
 		_s("Feely phone"), _s("Music")
 	};
+
+	// Laid out to loosely resemble the original toy keyboard: phones on the number row, instruments in
+	// the QWERTY/home rows, weather as a column on the right, colors on the bottom row, ROLL on space...
 	static const char *defaultMappings[COMFY_KEYBOARD_CONTACT_COUNT] = {
-		"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "q", "w",
-		"e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f"
+		"u", "SPACE", "n", "r", "1", "z", "f", "RETURN",
+		"x", "j", "3", "b", "p", "TAB", "v", "e",
+		"2", "c", "t", nullptr, "5", "m", "4", "g"
 	};
 
 	Keymap *keymap = new Keymap(Keymap::kKeymapTypeGame, "comfy-keyboard", _s("Comfy Keyboard"));
 	for (uint i = 0; i < COMFY_KEYBOARD_CONTACT_COUNT; i++) {
 		Action *action = new Action(actionIds[i], _(actionNames[i]));
 		action->setCustomEngineActionEvent(Comfy::kActionKeyboardContact0 + i);
-		action->addDefaultInputMapping(defaultMappings[i]);
+
+		if (defaultMappings[i])
+			action->addDefaultInputMapping(defaultMappings[i]);
+
 		keymap->addAction(action);
 	}
 


Commit: 11669e692e8aab983e44bd1984242e5f836c4ef0
    https://github.com/scummvm/scummvm/commit/11669e692e8aab983e44bd1984242e5f836c4ef0
Author: AndywinXp (andywinxp at gmail.com)
Date: 2026-11-15T15:08:52+01:00

Commit Message:
COMFY: Fix opcode O_ACTOR_SET_FRAME_AND_STOP

This fixes some weird glitches in Colorful Adventures

Changed paths:
    engines/comfy/script_vm.cpp


diff --git a/engines/comfy/script_vm.cpp b/engines/comfy/script_vm.cpp
index b27117cf524..336f897c51f 100644
--- a/engines/comfy/script_vm.cpp
+++ b/engines/comfy/script_vm.cpp
@@ -1164,8 +1164,8 @@ ComfyEngine::ScriptDispatchStatus ComfyEngine::scriptDispatch(Actor &actor, byte
 			error("Script opcode 0x53 resolved an invalid actor");
 
 		target->spriteSelector = (uint32)(int32)(int16)frame;
-		target->moveDx = 0;
-		target->moveDy = 0;
+		target->xFixed = 0;
+		target->yFixed = 0;
 
 		return kScriptContinue;
 	}




More information about the Scummvm-git-logs mailing list